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.

34028 lines
1.0 MiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 3.7.2-SNAPSHOT
  8. * @date 2014-12-24
  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__(6);
  84. // data
  85. exports.DataSet = __webpack_require__(7);
  86. exports.DataView = __webpack_require__(9);
  87. exports.Queue = __webpack_require__(8);
  88. // Graph3d
  89. exports.Graph3d = __webpack_require__(10);
  90. exports.graph3d = {
  91. Camera: __webpack_require__(14),
  92. Filter: __webpack_require__(15),
  93. Point2d: __webpack_require__(13),
  94. Point3d: __webpack_require__(12),
  95. Slider: __webpack_require__(16),
  96. StepNumber: __webpack_require__(17)
  97. };
  98. // Timeline
  99. exports.Timeline = __webpack_require__(18);
  100. exports.Graph2d = __webpack_require__(42);
  101. exports.timeline = {
  102. DateUtil: __webpack_require__(24),
  103. DataStep: __webpack_require__(45),
  104. Range: __webpack_require__(21),
  105. stack: __webpack_require__(28),
  106. TimeStep: __webpack_require__(38),
  107. components: {
  108. items: {
  109. Item: __webpack_require__(30),
  110. BackgroundItem: __webpack_require__(34),
  111. BoxItem: __webpack_require__(32),
  112. PointItem: __webpack_require__(33),
  113. RangeItem: __webpack_require__(29)
  114. },
  115. Component: __webpack_require__(23),
  116. CurrentTime: __webpack_require__(39),
  117. CustomTime: __webpack_require__(41),
  118. DataAxis: __webpack_require__(44),
  119. GraphGroup: __webpack_require__(46),
  120. Group: __webpack_require__(27),
  121. BackgroundGroup: __webpack_require__(31),
  122. ItemSet: __webpack_require__(26),
  123. Legend: __webpack_require__(50),
  124. LineGraph: __webpack_require__(43),
  125. TimeAxis: __webpack_require__(37)
  126. }
  127. };
  128. // Network
  129. exports.Network = __webpack_require__(51);
  130. exports.network = {
  131. Edge: __webpack_require__(52),
  132. Groups: __webpack_require__(54),
  133. Images: __webpack_require__(55),
  134. Node: __webpack_require__(53),
  135. Popup: __webpack_require__(56),
  136. dotparser: __webpack_require__(57),
  137. gephiParser: __webpack_require__(58)
  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__(2);
  145. exports.hammer = __webpack_require__(19);
  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__(2);
  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. // first check if moment.js is already loaded in the browser window, if so,
  1301. // use this instance. Else, load via commonjs.
  1302. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(3);
  1303. /***/ },
  1304. /* 3 */
  1305. /***/ function(module, exports, __webpack_require__) {
  1306. var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {//! moment.js
  1307. //! version : 2.8.4
  1308. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  1309. //! license : MIT
  1310. //! momentjs.com
  1311. (function (undefined) {
  1312. /************************************
  1313. Constants
  1314. ************************************/
  1315. var moment,
  1316. VERSION = '2.8.4',
  1317. // the global-scope this is NOT the global object in Node.js
  1318. globalScope = typeof global !== 'undefined' ? global : this,
  1319. oldGlobalMoment,
  1320. round = Math.round,
  1321. hasOwnProperty = Object.prototype.hasOwnProperty,
  1322. i,
  1323. YEAR = 0,
  1324. MONTH = 1,
  1325. DATE = 2,
  1326. HOUR = 3,
  1327. MINUTE = 4,
  1328. SECOND = 5,
  1329. MILLISECOND = 6,
  1330. // internal storage for locale config files
  1331. locales = {},
  1332. // extra moment internal properties (plugins register props here)
  1333. momentProperties = [],
  1334. // check for nodeJS
  1335. hasModule = (typeof module !== 'undefined' && module && module.exports),
  1336. // ASP.NET json date format regex
  1337. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  1338. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  1339. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  1340. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  1341. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  1342. // format tokens
  1343. 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,
  1344. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  1345. // parsing token regexes
  1346. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  1347. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  1348. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  1349. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  1350. parseTokenDigits = /\d+/, // nonzero number of digits
  1351. 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.
  1352. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  1353. parseTokenT = /T/i, // T (ISO separator)
  1354. parseTokenOffsetMs = /[\+\-]?\d+/, // 1234567890123
  1355. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  1356. //strict parsing regexes
  1357. parseTokenOneDigit = /\d/, // 0 - 9
  1358. parseTokenTwoDigits = /\d\d/, // 00 - 99
  1359. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  1360. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  1361. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  1362. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  1363. // iso 8601 regex
  1364. // 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)
  1365. 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)?)?$/,
  1366. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  1367. isoDates = [
  1368. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  1369. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  1370. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  1371. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  1372. ['YYYY-DDD', /\d{4}-\d{3}/]
  1373. ],
  1374. // iso time formats and regexes
  1375. isoTimes = [
  1376. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  1377. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  1378. ['HH:mm', /(T| )\d\d:\d\d/],
  1379. ['HH', /(T| )\d\d/]
  1380. ],
  1381. // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-15', '30']
  1382. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  1383. // getter and setter names
  1384. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  1385. unitMillisecondFactors = {
  1386. 'Milliseconds' : 1,
  1387. 'Seconds' : 1e3,
  1388. 'Minutes' : 6e4,
  1389. 'Hours' : 36e5,
  1390. 'Days' : 864e5,
  1391. 'Months' : 2592e6,
  1392. 'Years' : 31536e6
  1393. },
  1394. unitAliases = {
  1395. ms : 'millisecond',
  1396. s : 'second',
  1397. m : 'minute',
  1398. h : 'hour',
  1399. d : 'day',
  1400. D : 'date',
  1401. w : 'week',
  1402. W : 'isoWeek',
  1403. M : 'month',
  1404. Q : 'quarter',
  1405. y : 'year',
  1406. DDD : 'dayOfYear',
  1407. e : 'weekday',
  1408. E : 'isoWeekday',
  1409. gg: 'weekYear',
  1410. GG: 'isoWeekYear'
  1411. },
  1412. camelFunctions = {
  1413. dayofyear : 'dayOfYear',
  1414. isoweekday : 'isoWeekday',
  1415. isoweek : 'isoWeek',
  1416. weekyear : 'weekYear',
  1417. isoweekyear : 'isoWeekYear'
  1418. },
  1419. // format function strings
  1420. formatFunctions = {},
  1421. // default relative time thresholds
  1422. relativeTimeThresholds = {
  1423. s: 45, // seconds to minute
  1424. m: 45, // minutes to hour
  1425. h: 22, // hours to day
  1426. d: 26, // days to month
  1427. M: 11 // months to year
  1428. },
  1429. // tokens to ordinalize and pad
  1430. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  1431. paddedTokens = 'M D H h m s w W'.split(' '),
  1432. formatTokenFunctions = {
  1433. M : function () {
  1434. return this.month() + 1;
  1435. },
  1436. MMM : function (format) {
  1437. return this.localeData().monthsShort(this, format);
  1438. },
  1439. MMMM : function (format) {
  1440. return this.localeData().months(this, format);
  1441. },
  1442. D : function () {
  1443. return this.date();
  1444. },
  1445. DDD : function () {
  1446. return this.dayOfYear();
  1447. },
  1448. d : function () {
  1449. return this.day();
  1450. },
  1451. dd : function (format) {
  1452. return this.localeData().weekdaysMin(this, format);
  1453. },
  1454. ddd : function (format) {
  1455. return this.localeData().weekdaysShort(this, format);
  1456. },
  1457. dddd : function (format) {
  1458. return this.localeData().weekdays(this, format);
  1459. },
  1460. w : function () {
  1461. return this.week();
  1462. },
  1463. W : function () {
  1464. return this.isoWeek();
  1465. },
  1466. YY : function () {
  1467. return leftZeroFill(this.year() % 100, 2);
  1468. },
  1469. YYYY : function () {
  1470. return leftZeroFill(this.year(), 4);
  1471. },
  1472. YYYYY : function () {
  1473. return leftZeroFill(this.year(), 5);
  1474. },
  1475. YYYYYY : function () {
  1476. var y = this.year(), sign = y >= 0 ? '+' : '-';
  1477. return sign + leftZeroFill(Math.abs(y), 6);
  1478. },
  1479. gg : function () {
  1480. return leftZeroFill(this.weekYear() % 100, 2);
  1481. },
  1482. gggg : function () {
  1483. return leftZeroFill(this.weekYear(), 4);
  1484. },
  1485. ggggg : function () {
  1486. return leftZeroFill(this.weekYear(), 5);
  1487. },
  1488. GG : function () {
  1489. return leftZeroFill(this.isoWeekYear() % 100, 2);
  1490. },
  1491. GGGG : function () {
  1492. return leftZeroFill(this.isoWeekYear(), 4);
  1493. },
  1494. GGGGG : function () {
  1495. return leftZeroFill(this.isoWeekYear(), 5);
  1496. },
  1497. e : function () {
  1498. return this.weekday();
  1499. },
  1500. E : function () {
  1501. return this.isoWeekday();
  1502. },
  1503. a : function () {
  1504. return this.localeData().meridiem(this.hours(), this.minutes(), true);
  1505. },
  1506. A : function () {
  1507. return this.localeData().meridiem(this.hours(), this.minutes(), false);
  1508. },
  1509. H : function () {
  1510. return this.hours();
  1511. },
  1512. h : function () {
  1513. return this.hours() % 12 || 12;
  1514. },
  1515. m : function () {
  1516. return this.minutes();
  1517. },
  1518. s : function () {
  1519. return this.seconds();
  1520. },
  1521. S : function () {
  1522. return toInt(this.milliseconds() / 100);
  1523. },
  1524. SS : function () {
  1525. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  1526. },
  1527. SSS : function () {
  1528. return leftZeroFill(this.milliseconds(), 3);
  1529. },
  1530. SSSS : function () {
  1531. return leftZeroFill(this.milliseconds(), 3);
  1532. },
  1533. Z : function () {
  1534. var a = -this.zone(),
  1535. b = '+';
  1536. if (a < 0) {
  1537. a = -a;
  1538. b = '-';
  1539. }
  1540. return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2);
  1541. },
  1542. ZZ : function () {
  1543. var a = -this.zone(),
  1544. b = '+';
  1545. if (a < 0) {
  1546. a = -a;
  1547. b = '-';
  1548. }
  1549. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  1550. },
  1551. z : function () {
  1552. return this.zoneAbbr();
  1553. },
  1554. zz : function () {
  1555. return this.zoneName();
  1556. },
  1557. x : function () {
  1558. return this.valueOf();
  1559. },
  1560. X : function () {
  1561. return this.unix();
  1562. },
  1563. Q : function () {
  1564. return this.quarter();
  1565. }
  1566. },
  1567. deprecations = {},
  1568. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  1569. // Pick the first defined of two or three arguments. dfl comes from
  1570. // default.
  1571. function dfl(a, b, c) {
  1572. switch (arguments.length) {
  1573. case 2: return a != null ? a : b;
  1574. case 3: return a != null ? a : b != null ? b : c;
  1575. default: throw new Error('Implement me');
  1576. }
  1577. }
  1578. function hasOwnProp(a, b) {
  1579. return hasOwnProperty.call(a, b);
  1580. }
  1581. function defaultParsingFlags() {
  1582. // We need to deep clone this object, and es5 standard is not very
  1583. // helpful.
  1584. return {
  1585. empty : false,
  1586. unusedTokens : [],
  1587. unusedInput : [],
  1588. overflow : -2,
  1589. charsLeftOver : 0,
  1590. nullInput : false,
  1591. invalidMonth : null,
  1592. invalidFormat : false,
  1593. userInvalidated : false,
  1594. iso: false
  1595. };
  1596. }
  1597. function printMsg(msg) {
  1598. if (moment.suppressDeprecationWarnings === false &&
  1599. typeof console !== 'undefined' && console.warn) {
  1600. console.warn('Deprecation warning: ' + msg);
  1601. }
  1602. }
  1603. function deprecate(msg, fn) {
  1604. var firstTime = true;
  1605. return extend(function () {
  1606. if (firstTime) {
  1607. printMsg(msg);
  1608. firstTime = false;
  1609. }
  1610. return fn.apply(this, arguments);
  1611. }, fn);
  1612. }
  1613. function deprecateSimple(name, msg) {
  1614. if (!deprecations[name]) {
  1615. printMsg(msg);
  1616. deprecations[name] = true;
  1617. }
  1618. }
  1619. function padToken(func, count) {
  1620. return function (a) {
  1621. return leftZeroFill(func.call(this, a), count);
  1622. };
  1623. }
  1624. function ordinalizeToken(func, period) {
  1625. return function (a) {
  1626. return this.localeData().ordinal(func.call(this, a), period);
  1627. };
  1628. }
  1629. while (ordinalizeTokens.length) {
  1630. i = ordinalizeTokens.pop();
  1631. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  1632. }
  1633. while (paddedTokens.length) {
  1634. i = paddedTokens.pop();
  1635. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  1636. }
  1637. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  1638. /************************************
  1639. Constructors
  1640. ************************************/
  1641. function Locale() {
  1642. }
  1643. // Moment prototype object
  1644. function Moment(config, skipOverflow) {
  1645. if (skipOverflow !== false) {
  1646. checkOverflow(config);
  1647. }
  1648. copyConfig(this, config);
  1649. this._d = new Date(+config._d);
  1650. }
  1651. // Duration Constructor
  1652. function Duration(duration) {
  1653. var normalizedInput = normalizeObjectUnits(duration),
  1654. years = normalizedInput.year || 0,
  1655. quarters = normalizedInput.quarter || 0,
  1656. months = normalizedInput.month || 0,
  1657. weeks = normalizedInput.week || 0,
  1658. days = normalizedInput.day || 0,
  1659. hours = normalizedInput.hour || 0,
  1660. minutes = normalizedInput.minute || 0,
  1661. seconds = normalizedInput.second || 0,
  1662. milliseconds = normalizedInput.millisecond || 0;
  1663. // representation for dateAddRemove
  1664. this._milliseconds = +milliseconds +
  1665. seconds * 1e3 + // 1000
  1666. minutes * 6e4 + // 1000 * 60
  1667. hours * 36e5; // 1000 * 60 * 60
  1668. // Because of dateAddRemove treats 24 hours as different from a
  1669. // day when working around DST, we need to store them separately
  1670. this._days = +days +
  1671. weeks * 7;
  1672. // It is impossible translate months into days without knowing
  1673. // which months you are are talking about, so we have to store
  1674. // it separately.
  1675. this._months = +months +
  1676. quarters * 3 +
  1677. years * 12;
  1678. this._data = {};
  1679. this._locale = moment.localeData();
  1680. this._bubble();
  1681. }
  1682. /************************************
  1683. Helpers
  1684. ************************************/
  1685. function extend(a, b) {
  1686. for (var i in b) {
  1687. if (hasOwnProp(b, i)) {
  1688. a[i] = b[i];
  1689. }
  1690. }
  1691. if (hasOwnProp(b, 'toString')) {
  1692. a.toString = b.toString;
  1693. }
  1694. if (hasOwnProp(b, 'valueOf')) {
  1695. a.valueOf = b.valueOf;
  1696. }
  1697. return a;
  1698. }
  1699. function copyConfig(to, from) {
  1700. var i, prop, val;
  1701. if (typeof from._isAMomentObject !== 'undefined') {
  1702. to._isAMomentObject = from._isAMomentObject;
  1703. }
  1704. if (typeof from._i !== 'undefined') {
  1705. to._i = from._i;
  1706. }
  1707. if (typeof from._f !== 'undefined') {
  1708. to._f = from._f;
  1709. }
  1710. if (typeof from._l !== 'undefined') {
  1711. to._l = from._l;
  1712. }
  1713. if (typeof from._strict !== 'undefined') {
  1714. to._strict = from._strict;
  1715. }
  1716. if (typeof from._tzm !== 'undefined') {
  1717. to._tzm = from._tzm;
  1718. }
  1719. if (typeof from._isUTC !== 'undefined') {
  1720. to._isUTC = from._isUTC;
  1721. }
  1722. if (typeof from._offset !== 'undefined') {
  1723. to._offset = from._offset;
  1724. }
  1725. if (typeof from._pf !== 'undefined') {
  1726. to._pf = from._pf;
  1727. }
  1728. if (typeof from._locale !== 'undefined') {
  1729. to._locale = from._locale;
  1730. }
  1731. if (momentProperties.length > 0) {
  1732. for (i in momentProperties) {
  1733. prop = momentProperties[i];
  1734. val = from[prop];
  1735. if (typeof val !== 'undefined') {
  1736. to[prop] = val;
  1737. }
  1738. }
  1739. }
  1740. return to;
  1741. }
  1742. function absRound(number) {
  1743. if (number < 0) {
  1744. return Math.ceil(number);
  1745. } else {
  1746. return Math.floor(number);
  1747. }
  1748. }
  1749. // left zero fill a number
  1750. // see http://jsperf.com/left-zero-filling for performance comparison
  1751. function leftZeroFill(number, targetLength, forceSign) {
  1752. var output = '' + Math.abs(number),
  1753. sign = number >= 0;
  1754. while (output.length < targetLength) {
  1755. output = '0' + output;
  1756. }
  1757. return (sign ? (forceSign ? '+' : '') : '-') + output;
  1758. }
  1759. function positiveMomentsDifference(base, other) {
  1760. var res = {milliseconds: 0, months: 0};
  1761. res.months = other.month() - base.month() +
  1762. (other.year() - base.year()) * 12;
  1763. if (base.clone().add(res.months, 'M').isAfter(other)) {
  1764. --res.months;
  1765. }
  1766. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  1767. return res;
  1768. }
  1769. function momentsDifference(base, other) {
  1770. var res;
  1771. other = makeAs(other, base);
  1772. if (base.isBefore(other)) {
  1773. res = positiveMomentsDifference(base, other);
  1774. } else {
  1775. res = positiveMomentsDifference(other, base);
  1776. res.milliseconds = -res.milliseconds;
  1777. res.months = -res.months;
  1778. }
  1779. return res;
  1780. }
  1781. // TODO: remove 'name' arg after deprecation is removed
  1782. function createAdder(direction, name) {
  1783. return function (val, period) {
  1784. var dur, tmp;
  1785. //invert the arguments, but complain about it
  1786. if (period !== null && !isNaN(+period)) {
  1787. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
  1788. tmp = val; val = period; period = tmp;
  1789. }
  1790. val = typeof val === 'string' ? +val : val;
  1791. dur = moment.duration(val, period);
  1792. addOrSubtractDurationFromMoment(this, dur, direction);
  1793. return this;
  1794. };
  1795. }
  1796. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  1797. var milliseconds = duration._milliseconds,
  1798. days = duration._days,
  1799. months = duration._months;
  1800. updateOffset = updateOffset == null ? true : updateOffset;
  1801. if (milliseconds) {
  1802. mom._d.setTime(+mom._d + milliseconds * isAdding);
  1803. }
  1804. if (days) {
  1805. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  1806. }
  1807. if (months) {
  1808. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  1809. }
  1810. if (updateOffset) {
  1811. moment.updateOffset(mom, days || months);
  1812. }
  1813. }
  1814. // check if is an array
  1815. function isArray(input) {
  1816. return Object.prototype.toString.call(input) === '[object Array]';
  1817. }
  1818. function isDate(input) {
  1819. return Object.prototype.toString.call(input) === '[object Date]' ||
  1820. input instanceof Date;
  1821. }
  1822. // compare two arrays, return the number of differences
  1823. function compareArrays(array1, array2, dontConvert) {
  1824. var len = Math.min(array1.length, array2.length),
  1825. lengthDiff = Math.abs(array1.length - array2.length),
  1826. diffs = 0,
  1827. i;
  1828. for (i = 0; i < len; i++) {
  1829. if ((dontConvert && array1[i] !== array2[i]) ||
  1830. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  1831. diffs++;
  1832. }
  1833. }
  1834. return diffs + lengthDiff;
  1835. }
  1836. function normalizeUnits(units) {
  1837. if (units) {
  1838. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  1839. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  1840. }
  1841. return units;
  1842. }
  1843. function normalizeObjectUnits(inputObject) {
  1844. var normalizedInput = {},
  1845. normalizedProp,
  1846. prop;
  1847. for (prop in inputObject) {
  1848. if (hasOwnProp(inputObject, prop)) {
  1849. normalizedProp = normalizeUnits(prop);
  1850. if (normalizedProp) {
  1851. normalizedInput[normalizedProp] = inputObject[prop];
  1852. }
  1853. }
  1854. }
  1855. return normalizedInput;
  1856. }
  1857. function makeList(field) {
  1858. var count, setter;
  1859. if (field.indexOf('week') === 0) {
  1860. count = 7;
  1861. setter = 'day';
  1862. }
  1863. else if (field.indexOf('month') === 0) {
  1864. count = 12;
  1865. setter = 'month';
  1866. }
  1867. else {
  1868. return;
  1869. }
  1870. moment[field] = function (format, index) {
  1871. var i, getter,
  1872. method = moment._locale[field],
  1873. results = [];
  1874. if (typeof format === 'number') {
  1875. index = format;
  1876. format = undefined;
  1877. }
  1878. getter = function (i) {
  1879. var m = moment().utc().set(setter, i);
  1880. return method.call(moment._locale, m, format || '');
  1881. };
  1882. if (index != null) {
  1883. return getter(index);
  1884. }
  1885. else {
  1886. for (i = 0; i < count; i++) {
  1887. results.push(getter(i));
  1888. }
  1889. return results;
  1890. }
  1891. };
  1892. }
  1893. function toInt(argumentForCoercion) {
  1894. var coercedNumber = +argumentForCoercion,
  1895. value = 0;
  1896. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  1897. if (coercedNumber >= 0) {
  1898. value = Math.floor(coercedNumber);
  1899. } else {
  1900. value = Math.ceil(coercedNumber);
  1901. }
  1902. }
  1903. return value;
  1904. }
  1905. function daysInMonth(year, month) {
  1906. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  1907. }
  1908. function weeksInYear(year, dow, doy) {
  1909. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  1910. }
  1911. function daysInYear(year) {
  1912. return isLeapYear(year) ? 366 : 365;
  1913. }
  1914. function isLeapYear(year) {
  1915. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  1916. }
  1917. function checkOverflow(m) {
  1918. var overflow;
  1919. if (m._a && m._pf.overflow === -2) {
  1920. overflow =
  1921. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  1922. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  1923. m._a[HOUR] < 0 || m._a[HOUR] > 24 ||
  1924. (m._a[HOUR] === 24 && (m._a[MINUTE] !== 0 ||
  1925. m._a[SECOND] !== 0 ||
  1926. m._a[MILLISECOND] !== 0)) ? HOUR :
  1927. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  1928. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  1929. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  1930. -1;
  1931. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  1932. overflow = DATE;
  1933. }
  1934. m._pf.overflow = overflow;
  1935. }
  1936. }
  1937. function isValid(m) {
  1938. if (m._isValid == null) {
  1939. m._isValid = !isNaN(m._d.getTime()) &&
  1940. m._pf.overflow < 0 &&
  1941. !m._pf.empty &&
  1942. !m._pf.invalidMonth &&
  1943. !m._pf.nullInput &&
  1944. !m._pf.invalidFormat &&
  1945. !m._pf.userInvalidated;
  1946. if (m._strict) {
  1947. m._isValid = m._isValid &&
  1948. m._pf.charsLeftOver === 0 &&
  1949. m._pf.unusedTokens.length === 0 &&
  1950. m._pf.bigHour === undefined;
  1951. }
  1952. }
  1953. return m._isValid;
  1954. }
  1955. function normalizeLocale(key) {
  1956. return key ? key.toLowerCase().replace('_', '-') : key;
  1957. }
  1958. // pick the locale from the array
  1959. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  1960. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  1961. function chooseLocale(names) {
  1962. var i = 0, j, next, locale, split;
  1963. while (i < names.length) {
  1964. split = normalizeLocale(names[i]).split('-');
  1965. j = split.length;
  1966. next = normalizeLocale(names[i + 1]);
  1967. next = next ? next.split('-') : null;
  1968. while (j > 0) {
  1969. locale = loadLocale(split.slice(0, j).join('-'));
  1970. if (locale) {
  1971. return locale;
  1972. }
  1973. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  1974. //the next array item is better than a shallower substring of this one
  1975. break;
  1976. }
  1977. j--;
  1978. }
  1979. i++;
  1980. }
  1981. return null;
  1982. }
  1983. function loadLocale(name) {
  1984. var oldLocale = null;
  1985. if (!locales[name] && hasModule) {
  1986. try {
  1987. oldLocale = moment.locale();
  1988. !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
  1989. // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales
  1990. moment.locale(oldLocale);
  1991. } catch (e) { }
  1992. }
  1993. return locales[name];
  1994. }
  1995. // Return a moment from input, that is local/utc/zone equivalent to model.
  1996. function makeAs(input, model) {
  1997. var res, diff;
  1998. if (model._isUTC) {
  1999. res = model.clone();
  2000. diff = (moment.isMoment(input) || isDate(input) ?
  2001. +input : +moment(input)) - (+res);
  2002. // Use low-level api, because this fn is low-level api.
  2003. res._d.setTime(+res._d + diff);
  2004. moment.updateOffset(res, false);
  2005. return res;
  2006. } else {
  2007. return moment(input).local();
  2008. }
  2009. }
  2010. /************************************
  2011. Locale
  2012. ************************************/
  2013. extend(Locale.prototype, {
  2014. set : function (config) {
  2015. var prop, i;
  2016. for (i in config) {
  2017. prop = config[i];
  2018. if (typeof prop === 'function') {
  2019. this[i] = prop;
  2020. } else {
  2021. this['_' + i] = prop;
  2022. }
  2023. }
  2024. // Lenient ordinal parsing accepts just a number in addition to
  2025. // number + (possibly) stuff coming from _ordinalParseLenient.
  2026. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source);
  2027. },
  2028. _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
  2029. months : function (m) {
  2030. return this._months[m.month()];
  2031. },
  2032. _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
  2033. monthsShort : function (m) {
  2034. return this._monthsShort[m.month()];
  2035. },
  2036. monthsParse : function (monthName, format, strict) {
  2037. var i, mom, regex;
  2038. if (!this._monthsParse) {
  2039. this._monthsParse = [];
  2040. this._longMonthsParse = [];
  2041. this._shortMonthsParse = [];
  2042. }
  2043. for (i = 0; i < 12; i++) {
  2044. // make the regex if we don't have it already
  2045. mom = moment.utc([2000, i]);
  2046. if (strict && !this._longMonthsParse[i]) {
  2047. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  2048. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  2049. }
  2050. if (!strict && !this._monthsParse[i]) {
  2051. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  2052. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2053. }
  2054. // test the regex
  2055. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  2056. return i;
  2057. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  2058. return i;
  2059. } else if (!strict && this._monthsParse[i].test(monthName)) {
  2060. return i;
  2061. }
  2062. }
  2063. },
  2064. _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
  2065. weekdays : function (m) {
  2066. return this._weekdays[m.day()];
  2067. },
  2068. _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  2069. weekdaysShort : function (m) {
  2070. return this._weekdaysShort[m.day()];
  2071. },
  2072. _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  2073. weekdaysMin : function (m) {
  2074. return this._weekdaysMin[m.day()];
  2075. },
  2076. weekdaysParse : function (weekdayName) {
  2077. var i, mom, regex;
  2078. if (!this._weekdaysParse) {
  2079. this._weekdaysParse = [];
  2080. }
  2081. for (i = 0; i < 7; i++) {
  2082. // make the regex if we don't have it already
  2083. if (!this._weekdaysParse[i]) {
  2084. mom = moment([2000, 1]).day(i);
  2085. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  2086. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2087. }
  2088. // test the regex
  2089. if (this._weekdaysParse[i].test(weekdayName)) {
  2090. return i;
  2091. }
  2092. }
  2093. },
  2094. _longDateFormat : {
  2095. LTS : 'h:mm:ss A',
  2096. LT : 'h:mm A',
  2097. L : 'MM/DD/YYYY',
  2098. LL : 'MMMM D, YYYY',
  2099. LLL : 'MMMM D, YYYY LT',
  2100. LLLL : 'dddd, MMMM D, YYYY LT'
  2101. },
  2102. longDateFormat : function (key) {
  2103. var output = this._longDateFormat[key];
  2104. if (!output && this._longDateFormat[key.toUpperCase()]) {
  2105. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  2106. return val.slice(1);
  2107. });
  2108. this._longDateFormat[key] = output;
  2109. }
  2110. return output;
  2111. },
  2112. isPM : function (input) {
  2113. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  2114. // Using charAt should be more compatible.
  2115. return ((input + '').toLowerCase().charAt(0) === 'p');
  2116. },
  2117. _meridiemParse : /[ap]\.?m?\.?/i,
  2118. meridiem : function (hours, minutes, isLower) {
  2119. if (hours > 11) {
  2120. return isLower ? 'pm' : 'PM';
  2121. } else {
  2122. return isLower ? 'am' : 'AM';
  2123. }
  2124. },
  2125. _calendar : {
  2126. sameDay : '[Today at] LT',
  2127. nextDay : '[Tomorrow at] LT',
  2128. nextWeek : 'dddd [at] LT',
  2129. lastDay : '[Yesterday at] LT',
  2130. lastWeek : '[Last] dddd [at] LT',
  2131. sameElse : 'L'
  2132. },
  2133. calendar : function (key, mom, now) {
  2134. var output = this._calendar[key];
  2135. return typeof output === 'function' ? output.apply(mom, [now]) : output;
  2136. },
  2137. _relativeTime : {
  2138. future : 'in %s',
  2139. past : '%s ago',
  2140. s : 'a few seconds',
  2141. m : 'a minute',
  2142. mm : '%d minutes',
  2143. h : 'an hour',
  2144. hh : '%d hours',
  2145. d : 'a day',
  2146. dd : '%d days',
  2147. M : 'a month',
  2148. MM : '%d months',
  2149. y : 'a year',
  2150. yy : '%d years'
  2151. },
  2152. relativeTime : function (number, withoutSuffix, string, isFuture) {
  2153. var output = this._relativeTime[string];
  2154. return (typeof output === 'function') ?
  2155. output(number, withoutSuffix, string, isFuture) :
  2156. output.replace(/%d/i, number);
  2157. },
  2158. pastFuture : function (diff, output) {
  2159. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  2160. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  2161. },
  2162. ordinal : function (number) {
  2163. return this._ordinal.replace('%d', number);
  2164. },
  2165. _ordinal : '%d',
  2166. _ordinalParse : /\d{1,2}/,
  2167. preparse : function (string) {
  2168. return string;
  2169. },
  2170. postformat : function (string) {
  2171. return string;
  2172. },
  2173. week : function (mom) {
  2174. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  2175. },
  2176. _week : {
  2177. dow : 0, // Sunday is the first day of the week.
  2178. doy : 6 // The week that contains Jan 1st is the first week of the year.
  2179. },
  2180. _invalidDate: 'Invalid date',
  2181. invalidDate: function () {
  2182. return this._invalidDate;
  2183. }
  2184. });
  2185. /************************************
  2186. Formatting
  2187. ************************************/
  2188. function removeFormattingTokens(input) {
  2189. if (input.match(/\[[\s\S]/)) {
  2190. return input.replace(/^\[|\]$/g, '');
  2191. }
  2192. return input.replace(/\\/g, '');
  2193. }
  2194. function makeFormatFunction(format) {
  2195. var array = format.match(formattingTokens), i, length;
  2196. for (i = 0, length = array.length; i < length; i++) {
  2197. if (formatTokenFunctions[array[i]]) {
  2198. array[i] = formatTokenFunctions[array[i]];
  2199. } else {
  2200. array[i] = removeFormattingTokens(array[i]);
  2201. }
  2202. }
  2203. return function (mom) {
  2204. var output = '';
  2205. for (i = 0; i < length; i++) {
  2206. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  2207. }
  2208. return output;
  2209. };
  2210. }
  2211. // format date using native date object
  2212. function formatMoment(m, format) {
  2213. if (!m.isValid()) {
  2214. return m.localeData().invalidDate();
  2215. }
  2216. format = expandFormat(format, m.localeData());
  2217. if (!formatFunctions[format]) {
  2218. formatFunctions[format] = makeFormatFunction(format);
  2219. }
  2220. return formatFunctions[format](m);
  2221. }
  2222. function expandFormat(format, locale) {
  2223. var i = 5;
  2224. function replaceLongDateFormatTokens(input) {
  2225. return locale.longDateFormat(input) || input;
  2226. }
  2227. localFormattingTokens.lastIndex = 0;
  2228. while (i >= 0 && localFormattingTokens.test(format)) {
  2229. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  2230. localFormattingTokens.lastIndex = 0;
  2231. i -= 1;
  2232. }
  2233. return format;
  2234. }
  2235. /************************************
  2236. Parsing
  2237. ************************************/
  2238. // get the regex to find the next token
  2239. function getParseRegexForToken(token, config) {
  2240. var a, strict = config._strict;
  2241. switch (token) {
  2242. case 'Q':
  2243. return parseTokenOneDigit;
  2244. case 'DDDD':
  2245. return parseTokenThreeDigits;
  2246. case 'YYYY':
  2247. case 'GGGG':
  2248. case 'gggg':
  2249. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  2250. case 'Y':
  2251. case 'G':
  2252. case 'g':
  2253. return parseTokenSignedNumber;
  2254. case 'YYYYYY':
  2255. case 'YYYYY':
  2256. case 'GGGGG':
  2257. case 'ggggg':
  2258. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  2259. case 'S':
  2260. if (strict) {
  2261. return parseTokenOneDigit;
  2262. }
  2263. /* falls through */
  2264. case 'SS':
  2265. if (strict) {
  2266. return parseTokenTwoDigits;
  2267. }
  2268. /* falls through */
  2269. case 'SSS':
  2270. if (strict) {
  2271. return parseTokenThreeDigits;
  2272. }
  2273. /* falls through */
  2274. case 'DDD':
  2275. return parseTokenOneToThreeDigits;
  2276. case 'MMM':
  2277. case 'MMMM':
  2278. case 'dd':
  2279. case 'ddd':
  2280. case 'dddd':
  2281. return parseTokenWord;
  2282. case 'a':
  2283. case 'A':
  2284. return config._locale._meridiemParse;
  2285. case 'x':
  2286. return parseTokenOffsetMs;
  2287. case 'X':
  2288. return parseTokenTimestampMs;
  2289. case 'Z':
  2290. case 'ZZ':
  2291. return parseTokenTimezone;
  2292. case 'T':
  2293. return parseTokenT;
  2294. case 'SSSS':
  2295. return parseTokenDigits;
  2296. case 'MM':
  2297. case 'DD':
  2298. case 'YY':
  2299. case 'GG':
  2300. case 'gg':
  2301. case 'HH':
  2302. case 'hh':
  2303. case 'mm':
  2304. case 'ss':
  2305. case 'ww':
  2306. case 'WW':
  2307. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  2308. case 'M':
  2309. case 'D':
  2310. case 'd':
  2311. case 'H':
  2312. case 'h':
  2313. case 'm':
  2314. case 's':
  2315. case 'w':
  2316. case 'W':
  2317. case 'e':
  2318. case 'E':
  2319. return parseTokenOneOrTwoDigits;
  2320. case 'Do':
  2321. return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient;
  2322. default :
  2323. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i'));
  2324. return a;
  2325. }
  2326. }
  2327. function timezoneMinutesFromString(string) {
  2328. string = string || '';
  2329. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  2330. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  2331. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  2332. minutes = +(parts[1] * 60) + toInt(parts[2]);
  2333. return parts[0] === '+' ? -minutes : minutes;
  2334. }
  2335. // function to convert string input to date
  2336. function addTimeToArrayFromToken(token, input, config) {
  2337. var a, datePartArray = config._a;
  2338. switch (token) {
  2339. // QUARTER
  2340. case 'Q':
  2341. if (input != null) {
  2342. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  2343. }
  2344. break;
  2345. // MONTH
  2346. case 'M' : // fall through to MM
  2347. case 'MM' :
  2348. if (input != null) {
  2349. datePartArray[MONTH] = toInt(input) - 1;
  2350. }
  2351. break;
  2352. case 'MMM' : // fall through to MMMM
  2353. case 'MMMM' :
  2354. a = config._locale.monthsParse(input, token, config._strict);
  2355. // if we didn't find a month name, mark the date as invalid.
  2356. if (a != null) {
  2357. datePartArray[MONTH] = a;
  2358. } else {
  2359. config._pf.invalidMonth = input;
  2360. }
  2361. break;
  2362. // DAY OF MONTH
  2363. case 'D' : // fall through to DD
  2364. case 'DD' :
  2365. if (input != null) {
  2366. datePartArray[DATE] = toInt(input);
  2367. }
  2368. break;
  2369. case 'Do' :
  2370. if (input != null) {
  2371. datePartArray[DATE] = toInt(parseInt(
  2372. input.match(/\d{1,2}/)[0], 10));
  2373. }
  2374. break;
  2375. // DAY OF YEAR
  2376. case 'DDD' : // fall through to DDDD
  2377. case 'DDDD' :
  2378. if (input != null) {
  2379. config._dayOfYear = toInt(input);
  2380. }
  2381. break;
  2382. // YEAR
  2383. case 'YY' :
  2384. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  2385. break;
  2386. case 'YYYY' :
  2387. case 'YYYYY' :
  2388. case 'YYYYYY' :
  2389. datePartArray[YEAR] = toInt(input);
  2390. break;
  2391. // AM / PM
  2392. case 'a' : // fall through to A
  2393. case 'A' :
  2394. config._isPm = config._locale.isPM(input);
  2395. break;
  2396. // HOUR
  2397. case 'h' : // fall through to hh
  2398. case 'hh' :
  2399. config._pf.bigHour = true;
  2400. /* falls through */
  2401. case 'H' : // fall through to HH
  2402. case 'HH' :
  2403. datePartArray[HOUR] = toInt(input);
  2404. break;
  2405. // MINUTE
  2406. case 'm' : // fall through to mm
  2407. case 'mm' :
  2408. datePartArray[MINUTE] = toInt(input);
  2409. break;
  2410. // SECOND
  2411. case 's' : // fall through to ss
  2412. case 'ss' :
  2413. datePartArray[SECOND] = toInt(input);
  2414. break;
  2415. // MILLISECOND
  2416. case 'S' :
  2417. case 'SS' :
  2418. case 'SSS' :
  2419. case 'SSSS' :
  2420. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  2421. break;
  2422. // UNIX OFFSET (MILLISECONDS)
  2423. case 'x':
  2424. config._d = new Date(toInt(input));
  2425. break;
  2426. // UNIX TIMESTAMP WITH MS
  2427. case 'X':
  2428. config._d = new Date(parseFloat(input) * 1000);
  2429. break;
  2430. // TIMEZONE
  2431. case 'Z' : // fall through to ZZ
  2432. case 'ZZ' :
  2433. config._useUTC = true;
  2434. config._tzm = timezoneMinutesFromString(input);
  2435. break;
  2436. // WEEKDAY - human
  2437. case 'dd':
  2438. case 'ddd':
  2439. case 'dddd':
  2440. a = config._locale.weekdaysParse(input);
  2441. // if we didn't get a weekday name, mark the date as invalid
  2442. if (a != null) {
  2443. config._w = config._w || {};
  2444. config._w['d'] = a;
  2445. } else {
  2446. config._pf.invalidWeekday = input;
  2447. }
  2448. break;
  2449. // WEEK, WEEK DAY - numeric
  2450. case 'w':
  2451. case 'ww':
  2452. case 'W':
  2453. case 'WW':
  2454. case 'd':
  2455. case 'e':
  2456. case 'E':
  2457. token = token.substr(0, 1);
  2458. /* falls through */
  2459. case 'gggg':
  2460. case 'GGGG':
  2461. case 'GGGGG':
  2462. token = token.substr(0, 2);
  2463. if (input) {
  2464. config._w = config._w || {};
  2465. config._w[token] = toInt(input);
  2466. }
  2467. break;
  2468. case 'gg':
  2469. case 'GG':
  2470. config._w = config._w || {};
  2471. config._w[token] = moment.parseTwoDigitYear(input);
  2472. }
  2473. }
  2474. function dayOfYearFromWeekInfo(config) {
  2475. var w, weekYear, week, weekday, dow, doy, temp;
  2476. w = config._w;
  2477. if (w.GG != null || w.W != null || w.E != null) {
  2478. dow = 1;
  2479. doy = 4;
  2480. // TODO: We need to take the current isoWeekYear, but that depends on
  2481. // how we interpret now (local, utc, fixed offset). So create
  2482. // a now version of current config (take local/utc/offset flags, and
  2483. // create now).
  2484. weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year);
  2485. week = dfl(w.W, 1);
  2486. weekday = dfl(w.E, 1);
  2487. } else {
  2488. dow = config._locale._week.dow;
  2489. doy = config._locale._week.doy;
  2490. weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year);
  2491. week = dfl(w.w, 1);
  2492. if (w.d != null) {
  2493. // weekday -- low day numbers are considered next week
  2494. weekday = w.d;
  2495. if (weekday < dow) {
  2496. ++week;
  2497. }
  2498. } else if (w.e != null) {
  2499. // local weekday -- counting starts from begining of week
  2500. weekday = w.e + dow;
  2501. } else {
  2502. // default to begining of week
  2503. weekday = dow;
  2504. }
  2505. }
  2506. temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
  2507. config._a[YEAR] = temp.year;
  2508. config._dayOfYear = temp.dayOfYear;
  2509. }
  2510. // convert an array to a date.
  2511. // the array should mirror the parameters below
  2512. // note: all values past the year are optional and will default to the lowest possible value.
  2513. // [year, month, day , hour, minute, second, millisecond]
  2514. function dateFromConfig(config) {
  2515. var i, date, input = [], currentDate, yearToUse;
  2516. if (config._d) {
  2517. return;
  2518. }
  2519. currentDate = currentDateArray(config);
  2520. //compute day of the year from weeks and weekdays
  2521. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  2522. dayOfYearFromWeekInfo(config);
  2523. }
  2524. //if the day of the year is set, figure out what it is
  2525. if (config._dayOfYear) {
  2526. yearToUse = dfl(config._a[YEAR], currentDate[YEAR]);
  2527. if (config._dayOfYear > daysInYear(yearToUse)) {
  2528. config._pf._overflowDayOfYear = true;
  2529. }
  2530. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  2531. config._a[MONTH] = date.getUTCMonth();
  2532. config._a[DATE] = date.getUTCDate();
  2533. }
  2534. // Default to current date.
  2535. // * if no year, month, day of month are given, default to today
  2536. // * if day of month is given, default month and year
  2537. // * if month is given, default only year
  2538. // * if year is given, don't default anything
  2539. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  2540. config._a[i] = input[i] = currentDate[i];
  2541. }
  2542. // Zero out whatever was not defaulted, including time
  2543. for (; i < 7; i++) {
  2544. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  2545. }
  2546. // Check for 24:00:00.000
  2547. if (config._a[HOUR] === 24 &&
  2548. config._a[MINUTE] === 0 &&
  2549. config._a[SECOND] === 0 &&
  2550. config._a[MILLISECOND] === 0) {
  2551. config._nextDay = true;
  2552. config._a[HOUR] = 0;
  2553. }
  2554. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  2555. // Apply timezone offset from input. The actual zone can be changed
  2556. // with parseZone.
  2557. if (config._tzm != null) {
  2558. config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm);
  2559. }
  2560. if (config._nextDay) {
  2561. config._a[HOUR] = 24;
  2562. }
  2563. }
  2564. function dateFromObject(config) {
  2565. var normalizedInput;
  2566. if (config._d) {
  2567. return;
  2568. }
  2569. normalizedInput = normalizeObjectUnits(config._i);
  2570. config._a = [
  2571. normalizedInput.year,
  2572. normalizedInput.month,
  2573. normalizedInput.day || normalizedInput.date,
  2574. normalizedInput.hour,
  2575. normalizedInput.minute,
  2576. normalizedInput.second,
  2577. normalizedInput.millisecond
  2578. ];
  2579. dateFromConfig(config);
  2580. }
  2581. function currentDateArray(config) {
  2582. var now = new Date();
  2583. if (config._useUTC) {
  2584. return [
  2585. now.getUTCFullYear(),
  2586. now.getUTCMonth(),
  2587. now.getUTCDate()
  2588. ];
  2589. } else {
  2590. return [now.getFullYear(), now.getMonth(), now.getDate()];
  2591. }
  2592. }
  2593. // date from string and format string
  2594. function makeDateFromStringAndFormat(config) {
  2595. if (config._f === moment.ISO_8601) {
  2596. parseISO(config);
  2597. return;
  2598. }
  2599. config._a = [];
  2600. config._pf.empty = true;
  2601. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  2602. var string = '' + config._i,
  2603. i, parsedInput, tokens, token, skipped,
  2604. stringLength = string.length,
  2605. totalParsedInputLength = 0;
  2606. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  2607. for (i = 0; i < tokens.length; i++) {
  2608. token = tokens[i];
  2609. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  2610. if (parsedInput) {
  2611. skipped = string.substr(0, string.indexOf(parsedInput));
  2612. if (skipped.length > 0) {
  2613. config._pf.unusedInput.push(skipped);
  2614. }
  2615. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  2616. totalParsedInputLength += parsedInput.length;
  2617. }
  2618. // don't parse if it's not a known token
  2619. if (formatTokenFunctions[token]) {
  2620. if (parsedInput) {
  2621. config._pf.empty = false;
  2622. }
  2623. else {
  2624. config._pf.unusedTokens.push(token);
  2625. }
  2626. addTimeToArrayFromToken(token, parsedInput, config);
  2627. }
  2628. else if (config._strict && !parsedInput) {
  2629. config._pf.unusedTokens.push(token);
  2630. }
  2631. }
  2632. // add remaining unparsed input length to the string
  2633. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  2634. if (string.length > 0) {
  2635. config._pf.unusedInput.push(string);
  2636. }
  2637. // clear _12h flag if hour is <= 12
  2638. if (config._pf.bigHour === true && config._a[HOUR] <= 12) {
  2639. config._pf.bigHour = undefined;
  2640. }
  2641. // handle am pm
  2642. if (config._isPm && config._a[HOUR] < 12) {
  2643. config._a[HOUR] += 12;
  2644. }
  2645. // if is 12 am, change hours to 0
  2646. if (config._isPm === false && config._a[HOUR] === 12) {
  2647. config._a[HOUR] = 0;
  2648. }
  2649. dateFromConfig(config);
  2650. checkOverflow(config);
  2651. }
  2652. function unescapeFormat(s) {
  2653. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  2654. return p1 || p2 || p3 || p4;
  2655. });
  2656. }
  2657. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  2658. function regexpEscape(s) {
  2659. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  2660. }
  2661. // date from string and array of format strings
  2662. function makeDateFromStringAndArray(config) {
  2663. var tempConfig,
  2664. bestMoment,
  2665. scoreToBeat,
  2666. i,
  2667. currentScore;
  2668. if (config._f.length === 0) {
  2669. config._pf.invalidFormat = true;
  2670. config._d = new Date(NaN);
  2671. return;
  2672. }
  2673. for (i = 0; i < config._f.length; i++) {
  2674. currentScore = 0;
  2675. tempConfig = copyConfig({}, config);
  2676. if (config._useUTC != null) {
  2677. tempConfig._useUTC = config._useUTC;
  2678. }
  2679. tempConfig._pf = defaultParsingFlags();
  2680. tempConfig._f = config._f[i];
  2681. makeDateFromStringAndFormat(tempConfig);
  2682. if (!isValid(tempConfig)) {
  2683. continue;
  2684. }
  2685. // if there is any input that was not parsed add a penalty for that format
  2686. currentScore += tempConfig._pf.charsLeftOver;
  2687. //or tokens
  2688. currentScore += tempConfig._pf.unusedTokens.length * 10;
  2689. tempConfig._pf.score = currentScore;
  2690. if (scoreToBeat == null || currentScore < scoreToBeat) {
  2691. scoreToBeat = currentScore;
  2692. bestMoment = tempConfig;
  2693. }
  2694. }
  2695. extend(config, bestMoment || tempConfig);
  2696. }
  2697. // date from iso format
  2698. function parseISO(config) {
  2699. var i, l,
  2700. string = config._i,
  2701. match = isoRegex.exec(string);
  2702. if (match) {
  2703. config._pf.iso = true;
  2704. for (i = 0, l = isoDates.length; i < l; i++) {
  2705. if (isoDates[i][1].exec(string)) {
  2706. // match[5] should be 'T' or undefined
  2707. config._f = isoDates[i][0] + (match[6] || ' ');
  2708. break;
  2709. }
  2710. }
  2711. for (i = 0, l = isoTimes.length; i < l; i++) {
  2712. if (isoTimes[i][1].exec(string)) {
  2713. config._f += isoTimes[i][0];
  2714. break;
  2715. }
  2716. }
  2717. if (string.match(parseTokenTimezone)) {
  2718. config._f += 'Z';
  2719. }
  2720. makeDateFromStringAndFormat(config);
  2721. } else {
  2722. config._isValid = false;
  2723. }
  2724. }
  2725. // date from iso format or fallback
  2726. function makeDateFromString(config) {
  2727. parseISO(config);
  2728. if (config._isValid === false) {
  2729. delete config._isValid;
  2730. moment.createFromInputFallback(config);
  2731. }
  2732. }
  2733. function map(arr, fn) {
  2734. var res = [], i;
  2735. for (i = 0; i < arr.length; ++i) {
  2736. res.push(fn(arr[i], i));
  2737. }
  2738. return res;
  2739. }
  2740. function makeDateFromInput(config) {
  2741. var input = config._i, matched;
  2742. if (input === undefined) {
  2743. config._d = new Date();
  2744. } else if (isDate(input)) {
  2745. config._d = new Date(+input);
  2746. } else if ((matched = aspNetJsonRegex.exec(input)) !== null) {
  2747. config._d = new Date(+matched[1]);
  2748. } else if (typeof input === 'string') {
  2749. makeDateFromString(config);
  2750. } else if (isArray(input)) {
  2751. config._a = map(input.slice(0), function (obj) {
  2752. return parseInt(obj, 10);
  2753. });
  2754. dateFromConfig(config);
  2755. } else if (typeof(input) === 'object') {
  2756. dateFromObject(config);
  2757. } else if (typeof(input) === 'number') {
  2758. // from milliseconds
  2759. config._d = new Date(input);
  2760. } else {
  2761. moment.createFromInputFallback(config);
  2762. }
  2763. }
  2764. function makeDate(y, m, d, h, M, s, ms) {
  2765. //can't just apply() to create a date:
  2766. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  2767. var date = new Date(y, m, d, h, M, s, ms);
  2768. //the date constructor doesn't accept years < 1970
  2769. if (y < 1970) {
  2770. date.setFullYear(y);
  2771. }
  2772. return date;
  2773. }
  2774. function makeUTCDate(y) {
  2775. var date = new Date(Date.UTC.apply(null, arguments));
  2776. if (y < 1970) {
  2777. date.setUTCFullYear(y);
  2778. }
  2779. return date;
  2780. }
  2781. function parseWeekday(input, locale) {
  2782. if (typeof input === 'string') {
  2783. if (!isNaN(input)) {
  2784. input = parseInt(input, 10);
  2785. }
  2786. else {
  2787. input = locale.weekdaysParse(input);
  2788. if (typeof input !== 'number') {
  2789. return null;
  2790. }
  2791. }
  2792. }
  2793. return input;
  2794. }
  2795. /************************************
  2796. Relative Time
  2797. ************************************/
  2798. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  2799. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  2800. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  2801. }
  2802. function relativeTime(posNegDuration, withoutSuffix, locale) {
  2803. var duration = moment.duration(posNegDuration).abs(),
  2804. seconds = round(duration.as('s')),
  2805. minutes = round(duration.as('m')),
  2806. hours = round(duration.as('h')),
  2807. days = round(duration.as('d')),
  2808. months = round(duration.as('M')),
  2809. years = round(duration.as('y')),
  2810. args = seconds < relativeTimeThresholds.s && ['s', seconds] ||
  2811. minutes === 1 && ['m'] ||
  2812. minutes < relativeTimeThresholds.m && ['mm', minutes] ||
  2813. hours === 1 && ['h'] ||
  2814. hours < relativeTimeThresholds.h && ['hh', hours] ||
  2815. days === 1 && ['d'] ||
  2816. days < relativeTimeThresholds.d && ['dd', days] ||
  2817. months === 1 && ['M'] ||
  2818. months < relativeTimeThresholds.M && ['MM', months] ||
  2819. years === 1 && ['y'] || ['yy', years];
  2820. args[2] = withoutSuffix;
  2821. args[3] = +posNegDuration > 0;
  2822. args[4] = locale;
  2823. return substituteTimeAgo.apply({}, args);
  2824. }
  2825. /************************************
  2826. Week of Year
  2827. ************************************/
  2828. // firstDayOfWeek 0 = sun, 6 = sat
  2829. // the day of the week that starts the week
  2830. // (usually sunday or monday)
  2831. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  2832. // the first week is the week that contains the first
  2833. // of this day of the week
  2834. // (eg. ISO weeks use thursday (4))
  2835. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  2836. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  2837. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  2838. adjustedMoment;
  2839. if (daysToDayOfWeek > end) {
  2840. daysToDayOfWeek -= 7;
  2841. }
  2842. if (daysToDayOfWeek < end - 7) {
  2843. daysToDayOfWeek += 7;
  2844. }
  2845. adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd');
  2846. return {
  2847. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  2848. year: adjustedMoment.year()
  2849. };
  2850. }
  2851. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  2852. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  2853. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  2854. d = d === 0 ? 7 : d;
  2855. weekday = weekday != null ? weekday : firstDayOfWeek;
  2856. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  2857. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  2858. return {
  2859. year: dayOfYear > 0 ? year : year - 1,
  2860. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  2861. };
  2862. }
  2863. /************************************
  2864. Top Level Functions
  2865. ************************************/
  2866. function makeMoment(config) {
  2867. var input = config._i,
  2868. format = config._f,
  2869. res;
  2870. config._locale = config._locale || moment.localeData(config._l);
  2871. if (input === null || (format === undefined && input === '')) {
  2872. return moment.invalid({nullInput: true});
  2873. }
  2874. if (typeof input === 'string') {
  2875. config._i = input = config._locale.preparse(input);
  2876. }
  2877. if (moment.isMoment(input)) {
  2878. return new Moment(input, true);
  2879. } else if (format) {
  2880. if (isArray(format)) {
  2881. makeDateFromStringAndArray(config);
  2882. } else {
  2883. makeDateFromStringAndFormat(config);
  2884. }
  2885. } else {
  2886. makeDateFromInput(config);
  2887. }
  2888. res = new Moment(config);
  2889. if (res._nextDay) {
  2890. // Adding is smart enough around DST
  2891. res.add(1, 'd');
  2892. res._nextDay = undefined;
  2893. }
  2894. return res;
  2895. }
  2896. moment = function (input, format, locale, strict) {
  2897. var c;
  2898. if (typeof(locale) === 'boolean') {
  2899. strict = locale;
  2900. locale = undefined;
  2901. }
  2902. // object construction must be done this way.
  2903. // https://github.com/moment/moment/issues/1423
  2904. c = {};
  2905. c._isAMomentObject = true;
  2906. c._i = input;
  2907. c._f = format;
  2908. c._l = locale;
  2909. c._strict = strict;
  2910. c._isUTC = false;
  2911. c._pf = defaultParsingFlags();
  2912. return makeMoment(c);
  2913. };
  2914. moment.suppressDeprecationWarnings = false;
  2915. moment.createFromInputFallback = deprecate(
  2916. 'moment construction falls back to js Date. This is ' +
  2917. 'discouraged and will be removed in upcoming major ' +
  2918. 'release. Please refer to ' +
  2919. 'https://github.com/moment/moment/issues/1407 for more info.',
  2920. function (config) {
  2921. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  2922. }
  2923. );
  2924. // Pick a moment m from moments so that m[fn](other) is true for all
  2925. // other. This relies on the function fn to be transitive.
  2926. //
  2927. // moments should either be an array of moment objects or an array, whose
  2928. // first element is an array of moment objects.
  2929. function pickBy(fn, moments) {
  2930. var res, i;
  2931. if (moments.length === 1 && isArray(moments[0])) {
  2932. moments = moments[0];
  2933. }
  2934. if (!moments.length) {
  2935. return moment();
  2936. }
  2937. res = moments[0];
  2938. for (i = 1; i < moments.length; ++i) {
  2939. if (moments[i][fn](res)) {
  2940. res = moments[i];
  2941. }
  2942. }
  2943. return res;
  2944. }
  2945. moment.min = function () {
  2946. var args = [].slice.call(arguments, 0);
  2947. return pickBy('isBefore', args);
  2948. };
  2949. moment.max = function () {
  2950. var args = [].slice.call(arguments, 0);
  2951. return pickBy('isAfter', args);
  2952. };
  2953. // creating with utc
  2954. moment.utc = function (input, format, locale, strict) {
  2955. var c;
  2956. if (typeof(locale) === 'boolean') {
  2957. strict = locale;
  2958. locale = undefined;
  2959. }
  2960. // object construction must be done this way.
  2961. // https://github.com/moment/moment/issues/1423
  2962. c = {};
  2963. c._isAMomentObject = true;
  2964. c._useUTC = true;
  2965. c._isUTC = true;
  2966. c._l = locale;
  2967. c._i = input;
  2968. c._f = format;
  2969. c._strict = strict;
  2970. c._pf = defaultParsingFlags();
  2971. return makeMoment(c).utc();
  2972. };
  2973. // creating with unix timestamp (in seconds)
  2974. moment.unix = function (input) {
  2975. return moment(input * 1000);
  2976. };
  2977. // duration
  2978. moment.duration = function (input, key) {
  2979. var duration = input,
  2980. // matching against regexp is expensive, do it on demand
  2981. match = null,
  2982. sign,
  2983. ret,
  2984. parseIso,
  2985. diffRes;
  2986. if (moment.isDuration(input)) {
  2987. duration = {
  2988. ms: input._milliseconds,
  2989. d: input._days,
  2990. M: input._months
  2991. };
  2992. } else if (typeof input === 'number') {
  2993. duration = {};
  2994. if (key) {
  2995. duration[key] = input;
  2996. } else {
  2997. duration.milliseconds = input;
  2998. }
  2999. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  3000. sign = (match[1] === '-') ? -1 : 1;
  3001. duration = {
  3002. y: 0,
  3003. d: toInt(match[DATE]) * sign,
  3004. h: toInt(match[HOUR]) * sign,
  3005. m: toInt(match[MINUTE]) * sign,
  3006. s: toInt(match[SECOND]) * sign,
  3007. ms: toInt(match[MILLISECOND]) * sign
  3008. };
  3009. } else if (!!(match = isoDurationRegex.exec(input))) {
  3010. sign = (match[1] === '-') ? -1 : 1;
  3011. parseIso = function (inp) {
  3012. // We'd normally use ~~inp for this, but unfortunately it also
  3013. // converts floats to ints.
  3014. // inp may be undefined, so careful calling replace on it.
  3015. var res = inp && parseFloat(inp.replace(',', '.'));
  3016. // apply sign while we're at it
  3017. return (isNaN(res) ? 0 : res) * sign;
  3018. };
  3019. duration = {
  3020. y: parseIso(match[2]),
  3021. M: parseIso(match[3]),
  3022. d: parseIso(match[4]),
  3023. h: parseIso(match[5]),
  3024. m: parseIso(match[6]),
  3025. s: parseIso(match[7]),
  3026. w: parseIso(match[8])
  3027. };
  3028. } else if (typeof duration === 'object' &&
  3029. ('from' in duration || 'to' in duration)) {
  3030. diffRes = momentsDifference(moment(duration.from), moment(duration.to));
  3031. duration = {};
  3032. duration.ms = diffRes.milliseconds;
  3033. duration.M = diffRes.months;
  3034. }
  3035. ret = new Duration(duration);
  3036. if (moment.isDuration(input) && hasOwnProp(input, '_locale')) {
  3037. ret._locale = input._locale;
  3038. }
  3039. return ret;
  3040. };
  3041. // version number
  3042. moment.version = VERSION;
  3043. // default format
  3044. moment.defaultFormat = isoFormat;
  3045. // constant that refers to the ISO standard
  3046. moment.ISO_8601 = function () {};
  3047. // Plugins that add properties should also add the key here (null value),
  3048. // so we can properly clone ourselves.
  3049. moment.momentProperties = momentProperties;
  3050. // This function will be called whenever a moment is mutated.
  3051. // It is intended to keep the offset in sync with the timezone.
  3052. moment.updateOffset = function () {};
  3053. // This function allows you to set a threshold for relative time strings
  3054. moment.relativeTimeThreshold = function (threshold, limit) {
  3055. if (relativeTimeThresholds[threshold] === undefined) {
  3056. return false;
  3057. }
  3058. if (limit === undefined) {
  3059. return relativeTimeThresholds[threshold];
  3060. }
  3061. relativeTimeThresholds[threshold] = limit;
  3062. return true;
  3063. };
  3064. moment.lang = deprecate(
  3065. 'moment.lang is deprecated. Use moment.locale instead.',
  3066. function (key, value) {
  3067. return moment.locale(key, value);
  3068. }
  3069. );
  3070. // This function will load locale and then set the global locale. If
  3071. // no arguments are passed in, it will simply return the current global
  3072. // locale key.
  3073. moment.locale = function (key, values) {
  3074. var data;
  3075. if (key) {
  3076. if (typeof(values) !== 'undefined') {
  3077. data = moment.defineLocale(key, values);
  3078. }
  3079. else {
  3080. data = moment.localeData(key);
  3081. }
  3082. if (data) {
  3083. moment.duration._locale = moment._locale = data;
  3084. }
  3085. }
  3086. return moment._locale._abbr;
  3087. };
  3088. moment.defineLocale = function (name, values) {
  3089. if (values !== null) {
  3090. values.abbr = name;
  3091. if (!locales[name]) {
  3092. locales[name] = new Locale();
  3093. }
  3094. locales[name].set(values);
  3095. // backwards compat for now: also set the locale
  3096. moment.locale(name);
  3097. return locales[name];
  3098. } else {
  3099. // useful for testing
  3100. delete locales[name];
  3101. return null;
  3102. }
  3103. };
  3104. moment.langData = deprecate(
  3105. 'moment.langData is deprecated. Use moment.localeData instead.',
  3106. function (key) {
  3107. return moment.localeData(key);
  3108. }
  3109. );
  3110. // returns locale data
  3111. moment.localeData = function (key) {
  3112. var locale;
  3113. if (key && key._locale && key._locale._abbr) {
  3114. key = key._locale._abbr;
  3115. }
  3116. if (!key) {
  3117. return moment._locale;
  3118. }
  3119. if (!isArray(key)) {
  3120. //short-circuit everything else
  3121. locale = loadLocale(key);
  3122. if (locale) {
  3123. return locale;
  3124. }
  3125. key = [key];
  3126. }
  3127. return chooseLocale(key);
  3128. };
  3129. // compare moment object
  3130. moment.isMoment = function (obj) {
  3131. return obj instanceof Moment ||
  3132. (obj != null && hasOwnProp(obj, '_isAMomentObject'));
  3133. };
  3134. // for typechecking Duration objects
  3135. moment.isDuration = function (obj) {
  3136. return obj instanceof Duration;
  3137. };
  3138. for (i = lists.length - 1; i >= 0; --i) {
  3139. makeList(lists[i]);
  3140. }
  3141. moment.normalizeUnits = function (units) {
  3142. return normalizeUnits(units);
  3143. };
  3144. moment.invalid = function (flags) {
  3145. var m = moment.utc(NaN);
  3146. if (flags != null) {
  3147. extend(m._pf, flags);
  3148. }
  3149. else {
  3150. m._pf.userInvalidated = true;
  3151. }
  3152. return m;
  3153. };
  3154. moment.parseZone = function () {
  3155. return moment.apply(null, arguments).parseZone();
  3156. };
  3157. moment.parseTwoDigitYear = function (input) {
  3158. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  3159. };
  3160. /************************************
  3161. Moment Prototype
  3162. ************************************/
  3163. extend(moment.fn = Moment.prototype, {
  3164. clone : function () {
  3165. return moment(this);
  3166. },
  3167. valueOf : function () {
  3168. return +this._d + ((this._offset || 0) * 60000);
  3169. },
  3170. unix : function () {
  3171. return Math.floor(+this / 1000);
  3172. },
  3173. toString : function () {
  3174. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  3175. },
  3176. toDate : function () {
  3177. return this._offset ? new Date(+this) : this._d;
  3178. },
  3179. toISOString : function () {
  3180. var m = moment(this).utc();
  3181. if (0 < m.year() && m.year() <= 9999) {
  3182. if ('function' === typeof Date.prototype.toISOString) {
  3183. // native implementation is ~50x faster, use it when we can
  3184. return this.toDate().toISOString();
  3185. } else {
  3186. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  3187. }
  3188. } else {
  3189. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  3190. }
  3191. },
  3192. toArray : function () {
  3193. var m = this;
  3194. return [
  3195. m.year(),
  3196. m.month(),
  3197. m.date(),
  3198. m.hours(),
  3199. m.minutes(),
  3200. m.seconds(),
  3201. m.milliseconds()
  3202. ];
  3203. },
  3204. isValid : function () {
  3205. return isValid(this);
  3206. },
  3207. isDSTShifted : function () {
  3208. if (this._a) {
  3209. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  3210. }
  3211. return false;
  3212. },
  3213. parsingFlags : function () {
  3214. return extend({}, this._pf);
  3215. },
  3216. invalidAt: function () {
  3217. return this._pf.overflow;
  3218. },
  3219. utc : function (keepLocalTime) {
  3220. return this.zone(0, keepLocalTime);
  3221. },
  3222. local : function (keepLocalTime) {
  3223. if (this._isUTC) {
  3224. this.zone(0, keepLocalTime);
  3225. this._isUTC = false;
  3226. if (keepLocalTime) {
  3227. this.add(this._dateTzOffset(), 'm');
  3228. }
  3229. }
  3230. return this;
  3231. },
  3232. format : function (inputString) {
  3233. var output = formatMoment(this, inputString || moment.defaultFormat);
  3234. return this.localeData().postformat(output);
  3235. },
  3236. add : createAdder(1, 'add'),
  3237. subtract : createAdder(-1, 'subtract'),
  3238. diff : function (input, units, asFloat) {
  3239. var that = makeAs(input, this),
  3240. zoneDiff = (this.zone() - that.zone()) * 6e4,
  3241. diff, output, daysAdjust;
  3242. units = normalizeUnits(units);
  3243. if (units === 'year' || units === 'month') {
  3244. // average number of days in the months in the given dates
  3245. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  3246. // difference in months
  3247. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  3248. // adjust by taking difference in days, average number of days
  3249. // and dst in the given months.
  3250. daysAdjust = (this - moment(this).startOf('month')) -
  3251. (that - moment(that).startOf('month'));
  3252. // same as above but with zones, to negate all dst
  3253. daysAdjust -= ((this.zone() - moment(this).startOf('month').zone()) -
  3254. (that.zone() - moment(that).startOf('month').zone())) * 6e4;
  3255. output += daysAdjust / diff;
  3256. if (units === 'year') {
  3257. output = output / 12;
  3258. }
  3259. } else {
  3260. diff = (this - that);
  3261. output = units === 'second' ? diff / 1e3 : // 1000
  3262. units === 'minute' ? diff / 6e4 : // 1000 * 60
  3263. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  3264. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  3265. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  3266. diff;
  3267. }
  3268. return asFloat ? output : absRound(output);
  3269. },
  3270. from : function (time, withoutSuffix) {
  3271. return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  3272. },
  3273. fromNow : function (withoutSuffix) {
  3274. return this.from(moment(), withoutSuffix);
  3275. },
  3276. calendar : function (time) {
  3277. // We want to compare the start of today, vs this.
  3278. // Getting start-of-today depends on whether we're zone'd or not.
  3279. var now = time || moment(),
  3280. sod = makeAs(now, this).startOf('day'),
  3281. diff = this.diff(sod, 'days', true),
  3282. format = diff < -6 ? 'sameElse' :
  3283. diff < -1 ? 'lastWeek' :
  3284. diff < 0 ? 'lastDay' :
  3285. diff < 1 ? 'sameDay' :
  3286. diff < 2 ? 'nextDay' :
  3287. diff < 7 ? 'nextWeek' : 'sameElse';
  3288. return this.format(this.localeData().calendar(format, this, moment(now)));
  3289. },
  3290. isLeapYear : function () {
  3291. return isLeapYear(this.year());
  3292. },
  3293. isDST : function () {
  3294. return (this.zone() < this.clone().month(0).zone() ||
  3295. this.zone() < this.clone().month(5).zone());
  3296. },
  3297. day : function (input) {
  3298. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  3299. if (input != null) {
  3300. input = parseWeekday(input, this.localeData());
  3301. return this.add(input - day, 'd');
  3302. } else {
  3303. return day;
  3304. }
  3305. },
  3306. month : makeAccessor('Month', true),
  3307. startOf : function (units) {
  3308. units = normalizeUnits(units);
  3309. // the following switch intentionally omits break keywords
  3310. // to utilize falling through the cases.
  3311. switch (units) {
  3312. case 'year':
  3313. this.month(0);
  3314. /* falls through */
  3315. case 'quarter':
  3316. case 'month':
  3317. this.date(1);
  3318. /* falls through */
  3319. case 'week':
  3320. case 'isoWeek':
  3321. case 'day':
  3322. this.hours(0);
  3323. /* falls through */
  3324. case 'hour':
  3325. this.minutes(0);
  3326. /* falls through */
  3327. case 'minute':
  3328. this.seconds(0);
  3329. /* falls through */
  3330. case 'second':
  3331. this.milliseconds(0);
  3332. /* falls through */
  3333. }
  3334. // weeks are a special case
  3335. if (units === 'week') {
  3336. this.weekday(0);
  3337. } else if (units === 'isoWeek') {
  3338. this.isoWeekday(1);
  3339. }
  3340. // quarters are also special
  3341. if (units === 'quarter') {
  3342. this.month(Math.floor(this.month() / 3) * 3);
  3343. }
  3344. return this;
  3345. },
  3346. endOf: function (units) {
  3347. units = normalizeUnits(units);
  3348. if (units === undefined || units === 'millisecond') {
  3349. return this;
  3350. }
  3351. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  3352. },
  3353. isAfter: function (input, units) {
  3354. var inputMs;
  3355. units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
  3356. if (units === 'millisecond') {
  3357. input = moment.isMoment(input) ? input : moment(input);
  3358. return +this > +input;
  3359. } else {
  3360. inputMs = moment.isMoment(input) ? +input : +moment(input);
  3361. return inputMs < +this.clone().startOf(units);
  3362. }
  3363. },
  3364. isBefore: function (input, units) {
  3365. var inputMs;
  3366. units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
  3367. if (units === 'millisecond') {
  3368. input = moment.isMoment(input) ? input : moment(input);
  3369. return +this < +input;
  3370. } else {
  3371. inputMs = moment.isMoment(input) ? +input : +moment(input);
  3372. return +this.clone().endOf(units) < inputMs;
  3373. }
  3374. },
  3375. isSame: function (input, units) {
  3376. var inputMs;
  3377. units = normalizeUnits(units || 'millisecond');
  3378. if (units === 'millisecond') {
  3379. input = moment.isMoment(input) ? input : moment(input);
  3380. return +this === +input;
  3381. } else {
  3382. inputMs = +moment(input);
  3383. return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
  3384. }
  3385. },
  3386. min: deprecate(
  3387. 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
  3388. function (other) {
  3389. other = moment.apply(null, arguments);
  3390. return other < this ? this : other;
  3391. }
  3392. ),
  3393. max: deprecate(
  3394. 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
  3395. function (other) {
  3396. other = moment.apply(null, arguments);
  3397. return other > this ? this : other;
  3398. }
  3399. ),
  3400. // keepLocalTime = true means only change the timezone, without
  3401. // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]-->
  3402. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone
  3403. // +0200, so we adjust the time as needed, to be valid.
  3404. //
  3405. // Keeping the time actually adds/subtracts (one hour)
  3406. // from the actual represented time. That is why we call updateOffset
  3407. // a second time. In case it wants us to change the offset again
  3408. // _changeInProgress == true case, then we have to adjust, because
  3409. // there is no such time in the given timezone.
  3410. zone : function (input, keepLocalTime) {
  3411. var offset = this._offset || 0,
  3412. localAdjust;
  3413. if (input != null) {
  3414. if (typeof input === 'string') {
  3415. input = timezoneMinutesFromString(input);
  3416. }
  3417. if (Math.abs(input) < 16) {
  3418. input = input * 60;
  3419. }
  3420. if (!this._isUTC && keepLocalTime) {
  3421. localAdjust = this._dateTzOffset();
  3422. }
  3423. this._offset = input;
  3424. this._isUTC = true;
  3425. if (localAdjust != null) {
  3426. this.subtract(localAdjust, 'm');
  3427. }
  3428. if (offset !== input) {
  3429. if (!keepLocalTime || this._changeInProgress) {
  3430. addOrSubtractDurationFromMoment(this,
  3431. moment.duration(offset - input, 'm'), 1, false);
  3432. } else if (!this._changeInProgress) {
  3433. this._changeInProgress = true;
  3434. moment.updateOffset(this, true);
  3435. this._changeInProgress = null;
  3436. }
  3437. }
  3438. } else {
  3439. return this._isUTC ? offset : this._dateTzOffset();
  3440. }
  3441. return this;
  3442. },
  3443. zoneAbbr : function () {
  3444. return this._isUTC ? 'UTC' : '';
  3445. },
  3446. zoneName : function () {
  3447. return this._isUTC ? 'Coordinated Universal Time' : '';
  3448. },
  3449. parseZone : function () {
  3450. if (this._tzm) {
  3451. this.zone(this._tzm);
  3452. } else if (typeof this._i === 'string') {
  3453. this.zone(this._i);
  3454. }
  3455. return this;
  3456. },
  3457. hasAlignedHourOffset : function (input) {
  3458. if (!input) {
  3459. input = 0;
  3460. }
  3461. else {
  3462. input = moment(input).zone();
  3463. }
  3464. return (this.zone() - input) % 60 === 0;
  3465. },
  3466. daysInMonth : function () {
  3467. return daysInMonth(this.year(), this.month());
  3468. },
  3469. dayOfYear : function (input) {
  3470. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  3471. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  3472. },
  3473. quarter : function (input) {
  3474. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  3475. },
  3476. weekYear : function (input) {
  3477. var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
  3478. return input == null ? year : this.add((input - year), 'y');
  3479. },
  3480. isoWeekYear : function (input) {
  3481. var year = weekOfYear(this, 1, 4).year;
  3482. return input == null ? year : this.add((input - year), 'y');
  3483. },
  3484. week : function (input) {
  3485. var week = this.localeData().week(this);
  3486. return input == null ? week : this.add((input - week) * 7, 'd');
  3487. },
  3488. isoWeek : function (input) {
  3489. var week = weekOfYear(this, 1, 4).week;
  3490. return input == null ? week : this.add((input - week) * 7, 'd');
  3491. },
  3492. weekday : function (input) {
  3493. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  3494. return input == null ? weekday : this.add(input - weekday, 'd');
  3495. },
  3496. isoWeekday : function (input) {
  3497. // behaves the same as moment#day except
  3498. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  3499. // as a setter, sunday should belong to the previous week.
  3500. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  3501. },
  3502. isoWeeksInYear : function () {
  3503. return weeksInYear(this.year(), 1, 4);
  3504. },
  3505. weeksInYear : function () {
  3506. var weekInfo = this.localeData()._week;
  3507. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  3508. },
  3509. get : function (units) {
  3510. units = normalizeUnits(units);
  3511. return this[units]();
  3512. },
  3513. set : function (units, value) {
  3514. units = normalizeUnits(units);
  3515. if (typeof this[units] === 'function') {
  3516. this[units](value);
  3517. }
  3518. return this;
  3519. },
  3520. // If passed a locale key, it will set the locale for this
  3521. // instance. Otherwise, it will return the locale configuration
  3522. // variables for this instance.
  3523. locale : function (key) {
  3524. var newLocaleData;
  3525. if (key === undefined) {
  3526. return this._locale._abbr;
  3527. } else {
  3528. newLocaleData = moment.localeData(key);
  3529. if (newLocaleData != null) {
  3530. this._locale = newLocaleData;
  3531. }
  3532. return this;
  3533. }
  3534. },
  3535. lang : deprecate(
  3536. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  3537. function (key) {
  3538. if (key === undefined) {
  3539. return this.localeData();
  3540. } else {
  3541. return this.locale(key);
  3542. }
  3543. }
  3544. ),
  3545. localeData : function () {
  3546. return this._locale;
  3547. },
  3548. _dateTzOffset : function () {
  3549. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  3550. // https://github.com/moment/moment/pull/1871
  3551. return Math.round(this._d.getTimezoneOffset() / 15) * 15;
  3552. }
  3553. });
  3554. function rawMonthSetter(mom, value) {
  3555. var dayOfMonth;
  3556. // TODO: Move this out of here!
  3557. if (typeof value === 'string') {
  3558. value = mom.localeData().monthsParse(value);
  3559. // TODO: Another silent failure?
  3560. if (typeof value !== 'number') {
  3561. return mom;
  3562. }
  3563. }
  3564. dayOfMonth = Math.min(mom.date(),
  3565. daysInMonth(mom.year(), value));
  3566. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  3567. return mom;
  3568. }
  3569. function rawGetter(mom, unit) {
  3570. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  3571. }
  3572. function rawSetter(mom, unit, value) {
  3573. if (unit === 'Month') {
  3574. return rawMonthSetter(mom, value);
  3575. } else {
  3576. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  3577. }
  3578. }
  3579. function makeAccessor(unit, keepTime) {
  3580. return function (value) {
  3581. if (value != null) {
  3582. rawSetter(this, unit, value);
  3583. moment.updateOffset(this, keepTime);
  3584. return this;
  3585. } else {
  3586. return rawGetter(this, unit);
  3587. }
  3588. };
  3589. }
  3590. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  3591. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  3592. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  3593. // Setting the hour should keep the time, because the user explicitly
  3594. // specified which hour he wants. So trying to maintain the same hour (in
  3595. // a new timezone) makes sense. Adding/subtracting hours does not follow
  3596. // this rule.
  3597. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  3598. // moment.fn.month is defined separately
  3599. moment.fn.date = makeAccessor('Date', true);
  3600. moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true));
  3601. moment.fn.year = makeAccessor('FullYear', true);
  3602. moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true));
  3603. // add plural methods
  3604. moment.fn.days = moment.fn.day;
  3605. moment.fn.months = moment.fn.month;
  3606. moment.fn.weeks = moment.fn.week;
  3607. moment.fn.isoWeeks = moment.fn.isoWeek;
  3608. moment.fn.quarters = moment.fn.quarter;
  3609. // add aliased format methods
  3610. moment.fn.toJSON = moment.fn.toISOString;
  3611. /************************************
  3612. Duration Prototype
  3613. ************************************/
  3614. function daysToYears (days) {
  3615. // 400 years have 146097 days (taking into account leap year rules)
  3616. return days * 400 / 146097;
  3617. }
  3618. function yearsToDays (years) {
  3619. // years * 365 + absRound(years / 4) -
  3620. // absRound(years / 100) + absRound(years / 400);
  3621. return years * 146097 / 400;
  3622. }
  3623. extend(moment.duration.fn = Duration.prototype, {
  3624. _bubble : function () {
  3625. var milliseconds = this._milliseconds,
  3626. days = this._days,
  3627. months = this._months,
  3628. data = this._data,
  3629. seconds, minutes, hours, years = 0;
  3630. // The following code bubbles up values, see the tests for
  3631. // examples of what that means.
  3632. data.milliseconds = milliseconds % 1000;
  3633. seconds = absRound(milliseconds / 1000);
  3634. data.seconds = seconds % 60;
  3635. minutes = absRound(seconds / 60);
  3636. data.minutes = minutes % 60;
  3637. hours = absRound(minutes / 60);
  3638. data.hours = hours % 24;
  3639. days += absRound(hours / 24);
  3640. // Accurately convert days to years, assume start from year 0.
  3641. years = absRound(daysToYears(days));
  3642. days -= absRound(yearsToDays(years));
  3643. // 30 days to a month
  3644. // TODO (iskren): Use anchor date (like 1st Jan) to compute this.
  3645. months += absRound(days / 30);
  3646. days %= 30;
  3647. // 12 months -> 1 year
  3648. years += absRound(months / 12);
  3649. months %= 12;
  3650. data.days = days;
  3651. data.months = months;
  3652. data.years = years;
  3653. },
  3654. abs : function () {
  3655. this._milliseconds = Math.abs(this._milliseconds);
  3656. this._days = Math.abs(this._days);
  3657. this._months = Math.abs(this._months);
  3658. this._data.milliseconds = Math.abs(this._data.milliseconds);
  3659. this._data.seconds = Math.abs(this._data.seconds);
  3660. this._data.minutes = Math.abs(this._data.minutes);
  3661. this._data.hours = Math.abs(this._data.hours);
  3662. this._data.months = Math.abs(this._data.months);
  3663. this._data.years = Math.abs(this._data.years);
  3664. return this;
  3665. },
  3666. weeks : function () {
  3667. return absRound(this.days() / 7);
  3668. },
  3669. valueOf : function () {
  3670. return this._milliseconds +
  3671. this._days * 864e5 +
  3672. (this._months % 12) * 2592e6 +
  3673. toInt(this._months / 12) * 31536e6;
  3674. },
  3675. humanize : function (withSuffix) {
  3676. var output = relativeTime(this, !withSuffix, this.localeData());
  3677. if (withSuffix) {
  3678. output = this.localeData().pastFuture(+this, output);
  3679. }
  3680. return this.localeData().postformat(output);
  3681. },
  3682. add : function (input, val) {
  3683. // supports only 2.0-style add(1, 's') or add(moment)
  3684. var dur = moment.duration(input, val);
  3685. this._milliseconds += dur._milliseconds;
  3686. this._days += dur._days;
  3687. this._months += dur._months;
  3688. this._bubble();
  3689. return this;
  3690. },
  3691. subtract : function (input, val) {
  3692. var dur = moment.duration(input, val);
  3693. this._milliseconds -= dur._milliseconds;
  3694. this._days -= dur._days;
  3695. this._months -= dur._months;
  3696. this._bubble();
  3697. return this;
  3698. },
  3699. get : function (units) {
  3700. units = normalizeUnits(units);
  3701. return this[units.toLowerCase() + 's']();
  3702. },
  3703. as : function (units) {
  3704. var days, months;
  3705. units = normalizeUnits(units);
  3706. if (units === 'month' || units === 'year') {
  3707. days = this._days + this._milliseconds / 864e5;
  3708. months = this._months + daysToYears(days) * 12;
  3709. return units === 'month' ? months : months / 12;
  3710. } else {
  3711. // handle milliseconds separately because of floating point math errors (issue #1867)
  3712. days = this._days + Math.round(yearsToDays(this._months / 12));
  3713. switch (units) {
  3714. case 'week': return days / 7 + this._milliseconds / 6048e5;
  3715. case 'day': return days + this._milliseconds / 864e5;
  3716. case 'hour': return days * 24 + this._milliseconds / 36e5;
  3717. case 'minute': return days * 24 * 60 + this._milliseconds / 6e4;
  3718. case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000;
  3719. // Math.floor prevents floating point math errors here
  3720. case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds;
  3721. default: throw new Error('Unknown unit ' + units);
  3722. }
  3723. }
  3724. },
  3725. lang : moment.fn.lang,
  3726. locale : moment.fn.locale,
  3727. toIsoString : deprecate(
  3728. 'toIsoString() is deprecated. Please use toISOString() instead ' +
  3729. '(notice the capitals)',
  3730. function () {
  3731. return this.toISOString();
  3732. }
  3733. ),
  3734. toISOString : function () {
  3735. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  3736. var years = Math.abs(this.years()),
  3737. months = Math.abs(this.months()),
  3738. days = Math.abs(this.days()),
  3739. hours = Math.abs(this.hours()),
  3740. minutes = Math.abs(this.minutes()),
  3741. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  3742. if (!this.asSeconds()) {
  3743. // this is the same as C#'s (Noda) and python (isodate)...
  3744. // but not other JS (goog.date)
  3745. return 'P0D';
  3746. }
  3747. return (this.asSeconds() < 0 ? '-' : '') +
  3748. 'P' +
  3749. (years ? years + 'Y' : '') +
  3750. (months ? months + 'M' : '') +
  3751. (days ? days + 'D' : '') +
  3752. ((hours || minutes || seconds) ? 'T' : '') +
  3753. (hours ? hours + 'H' : '') +
  3754. (minutes ? minutes + 'M' : '') +
  3755. (seconds ? seconds + 'S' : '');
  3756. },
  3757. localeData : function () {
  3758. return this._locale;
  3759. }
  3760. });
  3761. moment.duration.fn.toString = moment.duration.fn.toISOString;
  3762. function makeDurationGetter(name) {
  3763. moment.duration.fn[name] = function () {
  3764. return this._data[name];
  3765. };
  3766. }
  3767. for (i in unitMillisecondFactors) {
  3768. if (hasOwnProp(unitMillisecondFactors, i)) {
  3769. makeDurationGetter(i.toLowerCase());
  3770. }
  3771. }
  3772. moment.duration.fn.asMilliseconds = function () {
  3773. return this.as('ms');
  3774. };
  3775. moment.duration.fn.asSeconds = function () {
  3776. return this.as('s');
  3777. };
  3778. moment.duration.fn.asMinutes = function () {
  3779. return this.as('m');
  3780. };
  3781. moment.duration.fn.asHours = function () {
  3782. return this.as('h');
  3783. };
  3784. moment.duration.fn.asDays = function () {
  3785. return this.as('d');
  3786. };
  3787. moment.duration.fn.asWeeks = function () {
  3788. return this.as('weeks');
  3789. };
  3790. moment.duration.fn.asMonths = function () {
  3791. return this.as('M');
  3792. };
  3793. moment.duration.fn.asYears = function () {
  3794. return this.as('y');
  3795. };
  3796. /************************************
  3797. Default Locale
  3798. ************************************/
  3799. // Set default locale, other locale will inherit from English.
  3800. moment.locale('en', {
  3801. ordinalParse: /\d{1,2}(th|st|nd|rd)/,
  3802. ordinal : function (number) {
  3803. var b = number % 10,
  3804. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  3805. (b === 1) ? 'st' :
  3806. (b === 2) ? 'nd' :
  3807. (b === 3) ? 'rd' : 'th';
  3808. return number + output;
  3809. }
  3810. });
  3811. /* EMBED_LOCALES */
  3812. /************************************
  3813. Exposing Moment
  3814. ************************************/
  3815. function makeGlobal(shouldDeprecate) {
  3816. /*global ender:false */
  3817. if (typeof ender !== 'undefined') {
  3818. return;
  3819. }
  3820. oldGlobalMoment = globalScope.moment;
  3821. if (shouldDeprecate) {
  3822. globalScope.moment = deprecate(
  3823. 'Accessing Moment through the global scope is ' +
  3824. 'deprecated, and will be removed in an upcoming ' +
  3825. 'release.',
  3826. moment);
  3827. } else {
  3828. globalScope.moment = moment;
  3829. }
  3830. }
  3831. // CommonJS module is defined
  3832. if (hasModule) {
  3833. module.exports = moment;
  3834. } else if (true) {
  3835. !(__WEBPACK_AMD_DEFINE_RESULT__ = function (require, exports, module) {
  3836. if (module.config && module.config() && module.config().noGlobal === true) {
  3837. // release the global variable
  3838. globalScope.moment = oldGlobalMoment;
  3839. }
  3840. return moment;
  3841. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  3842. makeGlobal(true);
  3843. } else {
  3844. makeGlobal();
  3845. }
  3846. }).call(this);
  3847. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(5)(module)))
  3848. /***/ },
  3849. /* 4 */
  3850. /***/ function(module, exports, __webpack_require__) {
  3851. function webpackContext(req) {
  3852. throw new Error("Cannot find module '" + req + "'.");
  3853. }
  3854. webpackContext.keys = function() { return []; };
  3855. webpackContext.resolve = webpackContext;
  3856. module.exports = webpackContext;
  3857. webpackContext.id = 4;
  3858. /***/ },
  3859. /* 5 */
  3860. /***/ function(module, exports, __webpack_require__) {
  3861. module.exports = function(module) {
  3862. if(!module.webpackPolyfill) {
  3863. module.deprecate = function() {};
  3864. module.paths = [];
  3865. // module.parent = undefined by default
  3866. module.children = [];
  3867. module.webpackPolyfill = 1;
  3868. }
  3869. return module;
  3870. }
  3871. /***/ },
  3872. /* 6 */
  3873. /***/ function(module, exports, __webpack_require__) {
  3874. // DOM utility methods
  3875. /**
  3876. * this prepares the JSON container for allocating SVG elements
  3877. * @param JSONcontainer
  3878. * @private
  3879. */
  3880. exports.prepareElements = function(JSONcontainer) {
  3881. // cleanup the redundant svgElements;
  3882. for (var elementType in JSONcontainer) {
  3883. if (JSONcontainer.hasOwnProperty(elementType)) {
  3884. JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
  3885. JSONcontainer[elementType].used = [];
  3886. }
  3887. }
  3888. };
  3889. /**
  3890. * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
  3891. * which to remove the redundant elements.
  3892. *
  3893. * @param JSONcontainer
  3894. * @private
  3895. */
  3896. exports.cleanupElements = function(JSONcontainer) {
  3897. // cleanup the redundant svgElements;
  3898. for (var elementType in JSONcontainer) {
  3899. if (JSONcontainer.hasOwnProperty(elementType)) {
  3900. if (JSONcontainer[elementType].redundant) {
  3901. for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
  3902. JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
  3903. }
  3904. JSONcontainer[elementType].redundant = [];
  3905. }
  3906. }
  3907. }
  3908. };
  3909. /**
  3910. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  3911. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  3912. *
  3913. * @param elementType
  3914. * @param JSONcontainer
  3915. * @param svgContainer
  3916. * @returns {*}
  3917. * @private
  3918. */
  3919. exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
  3920. var element;
  3921. // allocate SVG element, if it doesnt yet exist, create one.
  3922. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  3923. // check if there is an redundant element
  3924. if (JSONcontainer[elementType].redundant.length > 0) {
  3925. element = JSONcontainer[elementType].redundant[0];
  3926. JSONcontainer[elementType].redundant.shift();
  3927. }
  3928. else {
  3929. // create a new element and add it to the SVG
  3930. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  3931. svgContainer.appendChild(element);
  3932. }
  3933. }
  3934. else {
  3935. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  3936. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  3937. JSONcontainer[elementType] = {used: [], redundant: []};
  3938. svgContainer.appendChild(element);
  3939. }
  3940. JSONcontainer[elementType].used.push(element);
  3941. return element;
  3942. };
  3943. /**
  3944. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  3945. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  3946. *
  3947. * @param elementType
  3948. * @param JSONcontainer
  3949. * @param DOMContainer
  3950. * @returns {*}
  3951. * @private
  3952. */
  3953. exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
  3954. var element;
  3955. // allocate DOM element, if it doesnt yet exist, create one.
  3956. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  3957. // check if there is an redundant element
  3958. if (JSONcontainer[elementType].redundant.length > 0) {
  3959. element = JSONcontainer[elementType].redundant[0];
  3960. JSONcontainer[elementType].redundant.shift();
  3961. }
  3962. else {
  3963. // create a new element and add it to the SVG
  3964. element = document.createElement(elementType);
  3965. if (insertBefore !== undefined) {
  3966. DOMContainer.insertBefore(element, insertBefore);
  3967. }
  3968. else {
  3969. DOMContainer.appendChild(element);
  3970. }
  3971. }
  3972. }
  3973. else {
  3974. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  3975. element = document.createElement(elementType);
  3976. JSONcontainer[elementType] = {used: [], redundant: []};
  3977. if (insertBefore !== undefined) {
  3978. DOMContainer.insertBefore(element, insertBefore);
  3979. }
  3980. else {
  3981. DOMContainer.appendChild(element);
  3982. }
  3983. }
  3984. JSONcontainer[elementType].used.push(element);
  3985. return element;
  3986. };
  3987. /**
  3988. * draw a point object. this is a seperate function because it can also be called by the legend.
  3989. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
  3990. * as well.
  3991. *
  3992. * @param x
  3993. * @param y
  3994. * @param group
  3995. * @param JSONcontainer
  3996. * @param svgContainer
  3997. * @returns {*}
  3998. */
  3999. exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) {
  4000. var point;
  4001. if (group.options.drawPoints.style == 'circle') {
  4002. point = exports.getSVGElement('circle',JSONcontainer,svgContainer);
  4003. point.setAttributeNS(null, "cx", x);
  4004. point.setAttributeNS(null, "cy", y);
  4005. point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size);
  4006. }
  4007. else {
  4008. point = exports.getSVGElement('rect',JSONcontainer,svgContainer);
  4009. point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size);
  4010. point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size);
  4011. point.setAttributeNS(null, "width", group.options.drawPoints.size);
  4012. point.setAttributeNS(null, "height", group.options.drawPoints.size);
  4013. }
  4014. if(group.options.drawPoints.styles !== undefined) {
  4015. point.setAttributeNS(null, "style", group.group.options.drawPoints.styles);
  4016. }
  4017. point.setAttributeNS(null, "class", group.className + " point");
  4018. return point;
  4019. };
  4020. /**
  4021. * draw a bar SVG element centered on the X coordinate
  4022. *
  4023. * @param x
  4024. * @param y
  4025. * @param className
  4026. */
  4027. exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
  4028. if (height != 0) {
  4029. if (height < 0) {
  4030. height *= -1;
  4031. y -= height;
  4032. }
  4033. var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer);
  4034. rect.setAttributeNS(null, "x", x - 0.5 * width);
  4035. rect.setAttributeNS(null, "y", y);
  4036. rect.setAttributeNS(null, "width", width);
  4037. rect.setAttributeNS(null, "height", height);
  4038. rect.setAttributeNS(null, "class", className);
  4039. }
  4040. };
  4041. /***/ },
  4042. /* 7 */
  4043. /***/ function(module, exports, __webpack_require__) {
  4044. var util = __webpack_require__(1);
  4045. var Queue = __webpack_require__(8);
  4046. /**
  4047. * DataSet
  4048. *
  4049. * Usage:
  4050. * var dataSet = new DataSet({
  4051. * fieldId: '_id',
  4052. * type: {
  4053. * // ...
  4054. * }
  4055. * });
  4056. *
  4057. * dataSet.add(item);
  4058. * dataSet.add(data);
  4059. * dataSet.update(item);
  4060. * dataSet.update(data);
  4061. * dataSet.remove(id);
  4062. * dataSet.remove(ids);
  4063. * var data = dataSet.get();
  4064. * var data = dataSet.get(id);
  4065. * var data = dataSet.get(ids);
  4066. * var data = dataSet.get(ids, options, data);
  4067. * dataSet.clear();
  4068. *
  4069. * A data set can:
  4070. * - add/remove/update data
  4071. * - gives triggers upon changes in the data
  4072. * - can import/export data in various data formats
  4073. *
  4074. * @param {Array | DataTable} [data] Optional array with initial data
  4075. * @param {Object} [options] Available options:
  4076. * {String} fieldId Field name of the id in the
  4077. * items, 'id' by default.
  4078. * {Object.<String, String} type
  4079. * A map with field names as key,
  4080. * and the field type as value.
  4081. * {Object} queue Queue changes to the DataSet,
  4082. * flush them all at once.
  4083. * Queue options:
  4084. * - {number} delay Delay in ms, null by default
  4085. * - {number} max Maximum number of entries in the queue, Infinity by default
  4086. * @constructor DataSet
  4087. */
  4088. // TODO: add a DataSet constructor DataSet(data, options)
  4089. function DataSet (data, options) {
  4090. // correctly read optional arguments
  4091. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  4092. options = data;
  4093. data = null;
  4094. }
  4095. this._options = options || {};
  4096. this._data = {}; // map with data indexed by id
  4097. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  4098. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  4099. // all variants of a Date are internally stored as Date, so we can convert
  4100. // from everything to everything (also from ISODate to Number for example)
  4101. if (this._options.type) {
  4102. for (var field in this._options.type) {
  4103. if (this._options.type.hasOwnProperty(field)) {
  4104. var value = this._options.type[field];
  4105. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  4106. this._type[field] = 'Date';
  4107. }
  4108. else {
  4109. this._type[field] = value;
  4110. }
  4111. }
  4112. }
  4113. }
  4114. // TODO: deprecated since version 1.1.1 (or 2.0.0?)
  4115. if (this._options.convert) {
  4116. throw new Error('Option "convert" is deprecated. Use "type" instead.');
  4117. }
  4118. this._subscribers = {}; // event subscribers
  4119. // add initial data when provided
  4120. if (data) {
  4121. this.add(data);
  4122. }
  4123. this.setOptions(options);
  4124. }
  4125. /**
  4126. * @param {Object} [options] Available options:
  4127. * {Object} queue Queue changes to the DataSet,
  4128. * flush them all at once.
  4129. * Queue options:
  4130. * - {number} delay Delay in ms, null by default
  4131. * - {number} max Maximum number of entries in the queue, Infinity by default
  4132. * @param options
  4133. */
  4134. DataSet.prototype.setOptions = function(options) {
  4135. if (options && options.queue !== undefined) {
  4136. if (options.queue === false) {
  4137. // delete queue if loaded
  4138. if (this._queue) {
  4139. this._queue.destroy();
  4140. delete this._queue;
  4141. }
  4142. }
  4143. else {
  4144. // create queue and update its options
  4145. if (!this._queue) {
  4146. this._queue = Queue.extend(this, {
  4147. replace: ['add', 'update', 'remove']
  4148. });
  4149. }
  4150. if (typeof options.queue === 'object') {
  4151. this._queue.setOptions(options.queue);
  4152. }
  4153. }
  4154. }
  4155. };
  4156. /**
  4157. * Subscribe to an event, add an event listener
  4158. * @param {String} event Event name. Available events: 'put', 'update',
  4159. * 'remove'
  4160. * @param {function} callback Callback method. Called with three parameters:
  4161. * {String} event
  4162. * {Object | null} params
  4163. * {String | Number} senderId
  4164. */
  4165. DataSet.prototype.on = function(event, callback) {
  4166. var subscribers = this._subscribers[event];
  4167. if (!subscribers) {
  4168. subscribers = [];
  4169. this._subscribers[event] = subscribers;
  4170. }
  4171. subscribers.push({
  4172. callback: callback
  4173. });
  4174. };
  4175. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  4176. DataSet.prototype.subscribe = DataSet.prototype.on;
  4177. /**
  4178. * Unsubscribe from an event, remove an event listener
  4179. * @param {String} event
  4180. * @param {function} callback
  4181. */
  4182. DataSet.prototype.off = function(event, callback) {
  4183. var subscribers = this._subscribers[event];
  4184. if (subscribers) {
  4185. this._subscribers[event] = subscribers.filter(function (listener) {
  4186. return (listener.callback != callback);
  4187. });
  4188. }
  4189. };
  4190. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  4191. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  4192. /**
  4193. * Trigger an event
  4194. * @param {String} event
  4195. * @param {Object | null} params
  4196. * @param {String} [senderId] Optional id of the sender.
  4197. * @private
  4198. */
  4199. DataSet.prototype._trigger = function (event, params, senderId) {
  4200. if (event == '*') {
  4201. throw new Error('Cannot trigger event *');
  4202. }
  4203. var subscribers = [];
  4204. if (event in this._subscribers) {
  4205. subscribers = subscribers.concat(this._subscribers[event]);
  4206. }
  4207. if ('*' in this._subscribers) {
  4208. subscribers = subscribers.concat(this._subscribers['*']);
  4209. }
  4210. for (var i = 0; i < subscribers.length; i++) {
  4211. var subscriber = subscribers[i];
  4212. if (subscriber.callback) {
  4213. subscriber.callback(event, params, senderId || null);
  4214. }
  4215. }
  4216. };
  4217. /**
  4218. * Add data.
  4219. * Adding an item will fail when there already is an item with the same id.
  4220. * @param {Object | Array | DataTable} data
  4221. * @param {String} [senderId] Optional sender id
  4222. * @return {Array} addedIds Array with the ids of the added items
  4223. */
  4224. DataSet.prototype.add = function (data, senderId) {
  4225. var addedIds = [],
  4226. id,
  4227. me = this;
  4228. if (Array.isArray(data)) {
  4229. // Array
  4230. for (var i = 0, len = data.length; i < len; i++) {
  4231. id = me._addItem(data[i]);
  4232. addedIds.push(id);
  4233. }
  4234. }
  4235. else if (util.isDataTable(data)) {
  4236. // Google DataTable
  4237. var columns = this._getColumnNames(data);
  4238. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  4239. var item = {};
  4240. for (var col = 0, cols = columns.length; col < cols; col++) {
  4241. var field = columns[col];
  4242. item[field] = data.getValue(row, col);
  4243. }
  4244. id = me._addItem(item);
  4245. addedIds.push(id);
  4246. }
  4247. }
  4248. else if (data instanceof Object) {
  4249. // Single item
  4250. id = me._addItem(data);
  4251. addedIds.push(id);
  4252. }
  4253. else {
  4254. throw new Error('Unknown dataType');
  4255. }
  4256. if (addedIds.length) {
  4257. this._trigger('add', {items: addedIds}, senderId);
  4258. }
  4259. return addedIds;
  4260. };
  4261. /**
  4262. * Update existing items. When an item does not exist, it will be created
  4263. * @param {Object | Array | DataTable} data
  4264. * @param {String} [senderId] Optional sender id
  4265. * @return {Array} updatedIds The ids of the added or updated items
  4266. */
  4267. DataSet.prototype.update = function (data, senderId) {
  4268. var addedIds = [];
  4269. var updatedIds = [];
  4270. var updatedData = [];
  4271. var me = this;
  4272. var fieldId = me._fieldId;
  4273. var addOrUpdate = function (item) {
  4274. var id = item[fieldId];
  4275. if (me._data[id]) {
  4276. // update item
  4277. id = me._updateItem(item);
  4278. updatedIds.push(id);
  4279. updatedData.push(item);
  4280. }
  4281. else {
  4282. // add new item
  4283. id = me._addItem(item);
  4284. addedIds.push(id);
  4285. }
  4286. };
  4287. if (Array.isArray(data)) {
  4288. // Array
  4289. for (var i = 0, len = data.length; i < len; i++) {
  4290. addOrUpdate(data[i]);
  4291. }
  4292. }
  4293. else if (util.isDataTable(data)) {
  4294. // Google DataTable
  4295. var columns = this._getColumnNames(data);
  4296. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  4297. var item = {};
  4298. for (var col = 0, cols = columns.length; col < cols; col++) {
  4299. var field = columns[col];
  4300. item[field] = data.getValue(row, col);
  4301. }
  4302. addOrUpdate(item);
  4303. }
  4304. }
  4305. else if (data instanceof Object) {
  4306. // Single item
  4307. addOrUpdate(data);
  4308. }
  4309. else {
  4310. throw new Error('Unknown dataType');
  4311. }
  4312. if (addedIds.length) {
  4313. this._trigger('add', {items: addedIds}, senderId);
  4314. }
  4315. if (updatedIds.length) {
  4316. this._trigger('update', {items: updatedIds, data: updatedData}, senderId);
  4317. }
  4318. return addedIds.concat(updatedIds);
  4319. };
  4320. /**
  4321. * Get a data item or multiple items.
  4322. *
  4323. * Usage:
  4324. *
  4325. * get()
  4326. * get(options: Object)
  4327. * get(options: Object, data: Array | DataTable)
  4328. *
  4329. * get(id: Number | String)
  4330. * get(id: Number | String, options: Object)
  4331. * get(id: Number | String, options: Object, data: Array | DataTable)
  4332. *
  4333. * get(ids: Number[] | String[])
  4334. * get(ids: Number[] | String[], options: Object)
  4335. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  4336. *
  4337. * Where:
  4338. *
  4339. * {Number | String} id The id of an item
  4340. * {Number[] | String{}} ids An array with ids of items
  4341. * {Object} options An Object with options. Available options:
  4342. * {String} [returnType] Type of data to be
  4343. * returned. Can be 'DataTable' or 'Array' (default)
  4344. * {Object.<String, String>} [type]
  4345. * {String[]} [fields] field names to be returned
  4346. * {function} [filter] filter items
  4347. * {String | function} [order] Order the items by
  4348. * a field name or custom sort function.
  4349. * {Array | DataTable} [data] If provided, items will be appended to this
  4350. * array or table. Required in case of Google
  4351. * DataTable.
  4352. *
  4353. * @throws Error
  4354. */
  4355. DataSet.prototype.get = function (args) {
  4356. var me = this;
  4357. // parse the arguments
  4358. var id, ids, options, data;
  4359. var firstType = util.getType(arguments[0]);
  4360. if (firstType == 'String' || firstType == 'Number') {
  4361. // get(id [, options] [, data])
  4362. id = arguments[0];
  4363. options = arguments[1];
  4364. data = arguments[2];
  4365. }
  4366. else if (firstType == 'Array') {
  4367. // get(ids [, options] [, data])
  4368. ids = arguments[0];
  4369. options = arguments[1];
  4370. data = arguments[2];
  4371. }
  4372. else {
  4373. // get([, options] [, data])
  4374. options = arguments[0];
  4375. data = arguments[1];
  4376. }
  4377. // determine the return type
  4378. var returnType;
  4379. if (options && options.returnType) {
  4380. var allowedValues = ["DataTable", "Array", "Object"];
  4381. returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
  4382. if (data && (returnType != util.getType(data))) {
  4383. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  4384. 'does not correspond with specified options.type (' + options.type + ')');
  4385. }
  4386. if (returnType == 'DataTable' && !util.isDataTable(data)) {
  4387. throw new Error('Parameter "data" must be a DataTable ' +
  4388. 'when options.type is "DataTable"');
  4389. }
  4390. }
  4391. else if (data) {
  4392. returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  4393. }
  4394. else {
  4395. returnType = 'Array';
  4396. }
  4397. // build options
  4398. var type = options && options.type || this._options.type;
  4399. var filter = options && options.filter;
  4400. var items = [], item, itemId, i, len;
  4401. // convert items
  4402. if (id != undefined) {
  4403. // return a single item
  4404. item = me._getItem(id, type);
  4405. if (filter && !filter(item)) {
  4406. item = null;
  4407. }
  4408. }
  4409. else if (ids != undefined) {
  4410. // return a subset of items
  4411. for (i = 0, len = ids.length; i < len; i++) {
  4412. item = me._getItem(ids[i], type);
  4413. if (!filter || filter(item)) {
  4414. items.push(item);
  4415. }
  4416. }
  4417. }
  4418. else {
  4419. // return all items
  4420. for (itemId in this._data) {
  4421. if (this._data.hasOwnProperty(itemId)) {
  4422. item = me._getItem(itemId, type);
  4423. if (!filter || filter(item)) {
  4424. items.push(item);
  4425. }
  4426. }
  4427. }
  4428. }
  4429. // order the results
  4430. if (options && options.order && id == undefined) {
  4431. this._sort(items, options.order);
  4432. }
  4433. // filter fields of the items
  4434. if (options && options.fields) {
  4435. var fields = options.fields;
  4436. if (id != undefined) {
  4437. item = this._filterFields(item, fields);
  4438. }
  4439. else {
  4440. for (i = 0, len = items.length; i < len; i++) {
  4441. items[i] = this._filterFields(items[i], fields);
  4442. }
  4443. }
  4444. }
  4445. // return the results
  4446. if (returnType == 'DataTable') {
  4447. var columns = this._getColumnNames(data);
  4448. if (id != undefined) {
  4449. // append a single item to the data table
  4450. me._appendRow(data, columns, item);
  4451. }
  4452. else {
  4453. // copy the items to the provided data table
  4454. for (i = 0; i < items.length; i++) {
  4455. me._appendRow(data, columns, items[i]);
  4456. }
  4457. }
  4458. return data;
  4459. }
  4460. else if (returnType == "Object") {
  4461. var result = {};
  4462. for (i = 0; i < items.length; i++) {
  4463. result[items[i].id] = items[i];
  4464. }
  4465. return result;
  4466. }
  4467. else {
  4468. // return an array
  4469. if (id != undefined) {
  4470. // a single item
  4471. return item;
  4472. }
  4473. else {
  4474. // multiple items
  4475. if (data) {
  4476. // copy the items to the provided array
  4477. for (i = 0, len = items.length; i < len; i++) {
  4478. data.push(items[i]);
  4479. }
  4480. return data;
  4481. }
  4482. else {
  4483. // just return our array
  4484. return items;
  4485. }
  4486. }
  4487. }
  4488. };
  4489. /**
  4490. * Get ids of all items or from a filtered set of items.
  4491. * @param {Object} [options] An Object with options. Available options:
  4492. * {function} [filter] filter items
  4493. * {String | function} [order] Order the items by
  4494. * a field name or custom sort function.
  4495. * @return {Array} ids
  4496. */
  4497. DataSet.prototype.getIds = function (options) {
  4498. var data = this._data,
  4499. filter = options && options.filter,
  4500. order = options && options.order,
  4501. type = options && options.type || this._options.type,
  4502. i,
  4503. len,
  4504. id,
  4505. item,
  4506. items,
  4507. ids = [];
  4508. if (filter) {
  4509. // get filtered items
  4510. if (order) {
  4511. // create ordered list
  4512. items = [];
  4513. for (id in data) {
  4514. if (data.hasOwnProperty(id)) {
  4515. item = this._getItem(id, type);
  4516. if (filter(item)) {
  4517. items.push(item);
  4518. }
  4519. }
  4520. }
  4521. this._sort(items, order);
  4522. for (i = 0, len = items.length; i < len; i++) {
  4523. ids[i] = items[i][this._fieldId];
  4524. }
  4525. }
  4526. else {
  4527. // create unordered list
  4528. for (id in data) {
  4529. if (data.hasOwnProperty(id)) {
  4530. item = this._getItem(id, type);
  4531. if (filter(item)) {
  4532. ids.push(item[this._fieldId]);
  4533. }
  4534. }
  4535. }
  4536. }
  4537. }
  4538. else {
  4539. // get all items
  4540. if (order) {
  4541. // create an ordered list
  4542. items = [];
  4543. for (id in data) {
  4544. if (data.hasOwnProperty(id)) {
  4545. items.push(data[id]);
  4546. }
  4547. }
  4548. this._sort(items, order);
  4549. for (i = 0, len = items.length; i < len; i++) {
  4550. ids[i] = items[i][this._fieldId];
  4551. }
  4552. }
  4553. else {
  4554. // create unordered list
  4555. for (id in data) {
  4556. if (data.hasOwnProperty(id)) {
  4557. item = data[id];
  4558. ids.push(item[this._fieldId]);
  4559. }
  4560. }
  4561. }
  4562. }
  4563. return ids;
  4564. };
  4565. /**
  4566. * Returns the DataSet itself. Is overwritten for example by the DataView,
  4567. * which returns the DataSet it is connected to instead.
  4568. */
  4569. DataSet.prototype.getDataSet = function () {
  4570. return this;
  4571. };
  4572. /**
  4573. * Execute a callback function for every item in the dataset.
  4574. * @param {function} callback
  4575. * @param {Object} [options] Available options:
  4576. * {Object.<String, String>} [type]
  4577. * {String[]} [fields] filter fields
  4578. * {function} [filter] filter items
  4579. * {String | function} [order] Order the items by
  4580. * a field name or custom sort function.
  4581. */
  4582. DataSet.prototype.forEach = function (callback, options) {
  4583. var filter = options && options.filter,
  4584. type = options && options.type || this._options.type,
  4585. data = this._data,
  4586. item,
  4587. id;
  4588. if (options && options.order) {
  4589. // execute forEach on ordered list
  4590. var items = this.get(options);
  4591. for (var i = 0, len = items.length; i < len; i++) {
  4592. item = items[i];
  4593. id = item[this._fieldId];
  4594. callback(item, id);
  4595. }
  4596. }
  4597. else {
  4598. // unordered
  4599. for (id in data) {
  4600. if (data.hasOwnProperty(id)) {
  4601. item = this._getItem(id, type);
  4602. if (!filter || filter(item)) {
  4603. callback(item, id);
  4604. }
  4605. }
  4606. }
  4607. }
  4608. };
  4609. /**
  4610. * Map every item in the dataset.
  4611. * @param {function} callback
  4612. * @param {Object} [options] Available options:
  4613. * {Object.<String, String>} [type]
  4614. * {String[]} [fields] filter fields
  4615. * {function} [filter] filter items
  4616. * {String | function} [order] Order the items by
  4617. * a field name or custom sort function.
  4618. * @return {Object[]} mappedItems
  4619. */
  4620. DataSet.prototype.map = function (callback, options) {
  4621. var filter = options && options.filter,
  4622. type = options && options.type || this._options.type,
  4623. mappedItems = [],
  4624. data = this._data,
  4625. item;
  4626. // convert and filter items
  4627. for (var id in data) {
  4628. if (data.hasOwnProperty(id)) {
  4629. item = this._getItem(id, type);
  4630. if (!filter || filter(item)) {
  4631. mappedItems.push(callback(item, id));
  4632. }
  4633. }
  4634. }
  4635. // order items
  4636. if (options && options.order) {
  4637. this._sort(mappedItems, options.order);
  4638. }
  4639. return mappedItems;
  4640. };
  4641. /**
  4642. * Filter the fields of an item
  4643. * @param {Object} item
  4644. * @param {String[]} fields Field names
  4645. * @return {Object} filteredItem
  4646. * @private
  4647. */
  4648. DataSet.prototype._filterFields = function (item, fields) {
  4649. var filteredItem = {};
  4650. for (var field in item) {
  4651. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  4652. filteredItem[field] = item[field];
  4653. }
  4654. }
  4655. return filteredItem;
  4656. };
  4657. /**
  4658. * Sort the provided array with items
  4659. * @param {Object[]} items
  4660. * @param {String | function} order A field name or custom sort function.
  4661. * @private
  4662. */
  4663. DataSet.prototype._sort = function (items, order) {
  4664. if (util.isString(order)) {
  4665. // order by provided field name
  4666. var name = order; // field name
  4667. items.sort(function (a, b) {
  4668. var av = a[name];
  4669. var bv = b[name];
  4670. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  4671. });
  4672. }
  4673. else if (typeof order === 'function') {
  4674. // order by sort function
  4675. items.sort(order);
  4676. }
  4677. // TODO: extend order by an Object {field:String, direction:String}
  4678. // where direction can be 'asc' or 'desc'
  4679. else {
  4680. throw new TypeError('Order must be a function or a string');
  4681. }
  4682. };
  4683. /**
  4684. * Remove an object by pointer or by id
  4685. * @param {String | Number | Object | Array} id Object or id, or an array with
  4686. * objects or ids to be removed
  4687. * @param {String} [senderId] Optional sender id
  4688. * @return {Array} removedIds
  4689. */
  4690. DataSet.prototype.remove = function (id, senderId) {
  4691. var removedIds = [],
  4692. i, len, removedId;
  4693. if (Array.isArray(id)) {
  4694. for (i = 0, len = id.length; i < len; i++) {
  4695. removedId = this._remove(id[i]);
  4696. if (removedId != null) {
  4697. removedIds.push(removedId);
  4698. }
  4699. }
  4700. }
  4701. else {
  4702. removedId = this._remove(id);
  4703. if (removedId != null) {
  4704. removedIds.push(removedId);
  4705. }
  4706. }
  4707. if (removedIds.length) {
  4708. this._trigger('remove', {items: removedIds}, senderId);
  4709. }
  4710. return removedIds;
  4711. };
  4712. /**
  4713. * Remove an item by its id
  4714. * @param {Number | String | Object} id id or item
  4715. * @returns {Number | String | null} id
  4716. * @private
  4717. */
  4718. DataSet.prototype._remove = function (id) {
  4719. if (util.isNumber(id) || util.isString(id)) {
  4720. if (this._data[id]) {
  4721. delete this._data[id];
  4722. return id;
  4723. }
  4724. }
  4725. else if (id instanceof Object) {
  4726. var itemId = id[this._fieldId];
  4727. if (itemId && this._data[itemId]) {
  4728. delete this._data[itemId];
  4729. return itemId;
  4730. }
  4731. }
  4732. return null;
  4733. };
  4734. /**
  4735. * Clear the data
  4736. * @param {String} [senderId] Optional sender id
  4737. * @return {Array} removedIds The ids of all removed items
  4738. */
  4739. DataSet.prototype.clear = function (senderId) {
  4740. var ids = Object.keys(this._data);
  4741. this._data = {};
  4742. this._trigger('remove', {items: ids}, senderId);
  4743. return ids;
  4744. };
  4745. /**
  4746. * Find the item with maximum value of a specified field
  4747. * @param {String} field
  4748. * @return {Object | null} item Item containing max value, or null if no items
  4749. */
  4750. DataSet.prototype.max = function (field) {
  4751. var data = this._data,
  4752. max = null,
  4753. maxField = null;
  4754. for (var id in data) {
  4755. if (data.hasOwnProperty(id)) {
  4756. var item = data[id];
  4757. var itemField = item[field];
  4758. if (itemField != null && (!max || itemField > maxField)) {
  4759. max = item;
  4760. maxField = itemField;
  4761. }
  4762. }
  4763. }
  4764. return max;
  4765. };
  4766. /**
  4767. * Find the item with minimum value of a specified field
  4768. * @param {String} field
  4769. * @return {Object | null} item Item containing max value, or null if no items
  4770. */
  4771. DataSet.prototype.min = function (field) {
  4772. var data = this._data,
  4773. min = null,
  4774. minField = null;
  4775. for (var id in data) {
  4776. if (data.hasOwnProperty(id)) {
  4777. var item = data[id];
  4778. var itemField = item[field];
  4779. if (itemField != null && (!min || itemField < minField)) {
  4780. min = item;
  4781. minField = itemField;
  4782. }
  4783. }
  4784. }
  4785. return min;
  4786. };
  4787. /**
  4788. * Find all distinct values of a specified field
  4789. * @param {String} field
  4790. * @return {Array} values Array containing all distinct values. If data items
  4791. * do not contain the specified field are ignored.
  4792. * The returned array is unordered.
  4793. */
  4794. DataSet.prototype.distinct = function (field) {
  4795. var data = this._data;
  4796. var values = [];
  4797. var fieldType = this._options.type && this._options.type[field] || null;
  4798. var count = 0;
  4799. var i;
  4800. for (var prop in data) {
  4801. if (data.hasOwnProperty(prop)) {
  4802. var item = data[prop];
  4803. var value = item[field];
  4804. var exists = false;
  4805. for (i = 0; i < count; i++) {
  4806. if (values[i] == value) {
  4807. exists = true;
  4808. break;
  4809. }
  4810. }
  4811. if (!exists && (value !== undefined)) {
  4812. values[count] = value;
  4813. count++;
  4814. }
  4815. }
  4816. }
  4817. if (fieldType) {
  4818. for (i = 0; i < values.length; i++) {
  4819. values[i] = util.convert(values[i], fieldType);
  4820. }
  4821. }
  4822. return values;
  4823. };
  4824. /**
  4825. * Add a single item. Will fail when an item with the same id already exists.
  4826. * @param {Object} item
  4827. * @return {String} id
  4828. * @private
  4829. */
  4830. DataSet.prototype._addItem = function (item) {
  4831. var id = item[this._fieldId];
  4832. if (id != undefined) {
  4833. // check whether this id is already taken
  4834. if (this._data[id]) {
  4835. // item already exists
  4836. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  4837. }
  4838. }
  4839. else {
  4840. // generate an id
  4841. id = util.randomUUID();
  4842. item[this._fieldId] = id;
  4843. }
  4844. var d = {};
  4845. for (var field in item) {
  4846. if (item.hasOwnProperty(field)) {
  4847. var fieldType = this._type[field]; // type may be undefined
  4848. d[field] = util.convert(item[field], fieldType);
  4849. }
  4850. }
  4851. this._data[id] = d;
  4852. return id;
  4853. };
  4854. /**
  4855. * Get an item. Fields can be converted to a specific type
  4856. * @param {String} id
  4857. * @param {Object.<String, String>} [types] field types to convert
  4858. * @return {Object | null} item
  4859. * @private
  4860. */
  4861. DataSet.prototype._getItem = function (id, types) {
  4862. var field, value;
  4863. // get the item from the dataset
  4864. var raw = this._data[id];
  4865. if (!raw) {
  4866. return null;
  4867. }
  4868. // convert the items field types
  4869. var converted = {};
  4870. if (types) {
  4871. for (field in raw) {
  4872. if (raw.hasOwnProperty(field)) {
  4873. value = raw[field];
  4874. converted[field] = util.convert(value, types[field]);
  4875. }
  4876. }
  4877. }
  4878. else {
  4879. // no field types specified, no converting needed
  4880. for (field in raw) {
  4881. if (raw.hasOwnProperty(field)) {
  4882. value = raw[field];
  4883. converted[field] = value;
  4884. }
  4885. }
  4886. }
  4887. return converted;
  4888. };
  4889. /**
  4890. * Update a single item: merge with existing item.
  4891. * Will fail when the item has no id, or when there does not exist an item
  4892. * with the same id.
  4893. * @param {Object} item
  4894. * @return {String} id
  4895. * @private
  4896. */
  4897. DataSet.prototype._updateItem = function (item) {
  4898. var id = item[this._fieldId];
  4899. if (id == undefined) {
  4900. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  4901. }
  4902. var d = this._data[id];
  4903. if (!d) {
  4904. // item doesn't exist
  4905. throw new Error('Cannot update item: no item with id ' + id + ' found');
  4906. }
  4907. // merge with current item
  4908. for (var field in item) {
  4909. if (item.hasOwnProperty(field)) {
  4910. var fieldType = this._type[field]; // type may be undefined
  4911. d[field] = util.convert(item[field], fieldType);
  4912. }
  4913. }
  4914. return id;
  4915. };
  4916. /**
  4917. * Get an array with the column names of a Google DataTable
  4918. * @param {DataTable} dataTable
  4919. * @return {String[]} columnNames
  4920. * @private
  4921. */
  4922. DataSet.prototype._getColumnNames = function (dataTable) {
  4923. var columns = [];
  4924. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  4925. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  4926. }
  4927. return columns;
  4928. };
  4929. /**
  4930. * Append an item as a row to the dataTable
  4931. * @param dataTable
  4932. * @param columns
  4933. * @param item
  4934. * @private
  4935. */
  4936. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  4937. var row = dataTable.addRow();
  4938. for (var col = 0, cols = columns.length; col < cols; col++) {
  4939. var field = columns[col];
  4940. dataTable.setValue(row, col, item[field]);
  4941. }
  4942. };
  4943. module.exports = DataSet;
  4944. /***/ },
  4945. /* 8 */
  4946. /***/ function(module, exports, __webpack_require__) {
  4947. /**
  4948. * A queue
  4949. * @param {Object} options
  4950. * Available options:
  4951. * - delay: number When provided, the queue will be flushed
  4952. * automatically after an inactivity of this delay
  4953. * in milliseconds.
  4954. * Default value is null.
  4955. * - max: number When the queue exceeds the given maximum number
  4956. * of entries, the queue is flushed automatically.
  4957. * Default value of max is Infinity.
  4958. * @constructor
  4959. */
  4960. function Queue(options) {
  4961. // options
  4962. this.delay = null;
  4963. this.max = Infinity;
  4964. // properties
  4965. this._queue = [];
  4966. this._timeout = null;
  4967. this._extended = null;
  4968. this.setOptions(options);
  4969. }
  4970. /**
  4971. * Update the configuration of the queue
  4972. * @param {Object} options
  4973. * Available options:
  4974. * - delay: number When provided, the queue will be flushed
  4975. * automatically after an inactivity of this delay
  4976. * in milliseconds.
  4977. * Default value is null.
  4978. * - max: number When the queue exceeds the given maximum number
  4979. * of entries, the queue is flushed automatically.
  4980. * Default value of max is Infinity.
  4981. * @param options
  4982. */
  4983. Queue.prototype.setOptions = function (options) {
  4984. if (options && typeof options.delay !== 'undefined') {
  4985. this.delay = options.delay;
  4986. }
  4987. if (options && typeof options.max !== 'undefined') {
  4988. this.max = options.max;
  4989. }
  4990. this._flushIfNeeded();
  4991. };
  4992. /**
  4993. * Extend an object with queuing functionality.
  4994. * The object will be extended with a function flush, and the methods provided
  4995. * in options.replace will be replaced with queued ones.
  4996. * @param {Object} object
  4997. * @param {Object} options
  4998. * Available options:
  4999. * - replace: Array.<string>
  5000. * A list with method names of the methods
  5001. * on the object to be replaced with queued ones.
  5002. * - delay: number When provided, the queue will be flushed
  5003. * automatically after an inactivity of this delay
  5004. * in milliseconds.
  5005. * Default value is null.
  5006. * - max: number When the queue exceeds the given maximum number
  5007. * of entries, the queue is flushed automatically.
  5008. * Default value of max is Infinity.
  5009. * @return {Queue} Returns the created queue
  5010. */
  5011. Queue.extend = function (object, options) {
  5012. var queue = new Queue(options);
  5013. if (object.flush !== undefined) {
  5014. throw new Error('Target object already has a property flush');
  5015. }
  5016. object.flush = function () {
  5017. queue.flush();
  5018. };
  5019. var methods = [{
  5020. name: 'flush',
  5021. original: undefined
  5022. }];
  5023. if (options && options.replace) {
  5024. for (var i = 0; i < options.replace.length; i++) {
  5025. var name = options.replace[i];
  5026. methods.push({
  5027. name: name,
  5028. original: object[name]
  5029. });
  5030. queue.replace(object, name);
  5031. }
  5032. }
  5033. queue._extended = {
  5034. object: object,
  5035. methods: methods
  5036. };
  5037. return queue;
  5038. };
  5039. /**
  5040. * Destroy the queue. The queue will first flush all queued actions, and in
  5041. * case it has extended an object, will restore the original object.
  5042. */
  5043. Queue.prototype.destroy = function () {
  5044. this.flush();
  5045. if (this._extended) {
  5046. var object = this._extended.object;
  5047. var methods = this._extended.methods;
  5048. for (var i = 0; i < methods.length; i++) {
  5049. var method = methods[i];
  5050. if (method.original) {
  5051. object[method.name] = method.original;
  5052. }
  5053. else {
  5054. delete object[method.name];
  5055. }
  5056. }
  5057. this._extended = null;
  5058. }
  5059. };
  5060. /**
  5061. * Replace a method on an object with a queued version
  5062. * @param {Object} object Object having the method
  5063. * @param {string} method The method name
  5064. */
  5065. Queue.prototype.replace = function(object, method) {
  5066. var me = this;
  5067. var original = object[method];
  5068. if (!original) {
  5069. throw new Error('Method ' + method + ' undefined');
  5070. }
  5071. object[method] = function () {
  5072. // create an Array with the arguments
  5073. var args = [];
  5074. for (var i = 0; i < arguments.length; i++) {
  5075. args[i] = arguments[i];
  5076. }
  5077. // add this call to the queue
  5078. me.queue({
  5079. args: args,
  5080. fn: original,
  5081. context: this
  5082. });
  5083. };
  5084. };
  5085. /**
  5086. * Queue a call
  5087. * @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
  5088. */
  5089. Queue.prototype.queue = function(entry) {
  5090. if (typeof entry === 'function') {
  5091. this._queue.push({fn: entry});
  5092. }
  5093. else {
  5094. this._queue.push(entry);
  5095. }
  5096. this._flushIfNeeded();
  5097. };
  5098. /**
  5099. * Check whether the queue needs to be flushed
  5100. * @private
  5101. */
  5102. Queue.prototype._flushIfNeeded = function () {
  5103. // flush when the maximum is exceeded.
  5104. if (this._queue.length > this.max) {
  5105. this.flush();
  5106. }
  5107. // flush after a period of inactivity when a delay is configured
  5108. clearTimeout(this._timeout);
  5109. if (this.queue.length > 0 && typeof this.delay === 'number') {
  5110. var me = this;
  5111. this._timeout = setTimeout(function () {
  5112. me.flush();
  5113. }, this.delay);
  5114. }
  5115. };
  5116. /**
  5117. * Flush all queued calls
  5118. */
  5119. Queue.prototype.flush = function () {
  5120. while (this._queue.length > 0) {
  5121. var entry = this._queue.shift();
  5122. entry.fn.apply(entry.context || entry.fn, entry.args || []);
  5123. }
  5124. };
  5125. module.exports = Queue;
  5126. /***/ },
  5127. /* 9 */
  5128. /***/ function(module, exports, __webpack_require__) {
  5129. var util = __webpack_require__(1);
  5130. var DataSet = __webpack_require__(7);
  5131. /**
  5132. * DataView
  5133. *
  5134. * a dataview offers a filtered view on a dataset or an other dataview.
  5135. *
  5136. * @param {DataSet | DataView} data
  5137. * @param {Object} [options] Available options: see method get
  5138. *
  5139. * @constructor DataView
  5140. */
  5141. function DataView (data, options) {
  5142. this._data = null;
  5143. this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
  5144. this._options = options || {};
  5145. this._fieldId = 'id'; // name of the field containing id
  5146. this._subscribers = {}; // event subscribers
  5147. var me = this;
  5148. this.listener = function () {
  5149. me._onEvent.apply(me, arguments);
  5150. };
  5151. this.setData(data);
  5152. }
  5153. // TODO: implement a function .config() to dynamically update things like configured filter
  5154. // and trigger changes accordingly
  5155. /**
  5156. * Set a data source for the view
  5157. * @param {DataSet | DataView} data
  5158. */
  5159. DataView.prototype.setData = function (data) {
  5160. var ids, i, len;
  5161. if (this._data) {
  5162. // unsubscribe from current dataset
  5163. if (this._data.unsubscribe) {
  5164. this._data.unsubscribe('*', this.listener);
  5165. }
  5166. // trigger a remove of all items in memory
  5167. ids = [];
  5168. for (var id in this._ids) {
  5169. if (this._ids.hasOwnProperty(id)) {
  5170. ids.push(id);
  5171. }
  5172. }
  5173. this._ids = {};
  5174. this._trigger('remove', {items: ids});
  5175. }
  5176. this._data = data;
  5177. if (this._data) {
  5178. // update fieldId
  5179. this._fieldId = this._options.fieldId ||
  5180. (this._data && this._data.options && this._data.options.fieldId) ||
  5181. 'id';
  5182. // trigger an add of all added items
  5183. ids = this._data.getIds({filter: this._options && this._options.filter});
  5184. for (i = 0, len = ids.length; i < len; i++) {
  5185. id = ids[i];
  5186. this._ids[id] = true;
  5187. }
  5188. this._trigger('add', {items: ids});
  5189. // subscribe to new dataset
  5190. if (this._data.on) {
  5191. this._data.on('*', this.listener);
  5192. }
  5193. }
  5194. };
  5195. /**
  5196. * Get data from the data view
  5197. *
  5198. * Usage:
  5199. *
  5200. * get()
  5201. * get(options: Object)
  5202. * get(options: Object, data: Array | DataTable)
  5203. *
  5204. * get(id: Number)
  5205. * get(id: Number, options: Object)
  5206. * get(id: Number, options: Object, data: Array | DataTable)
  5207. *
  5208. * get(ids: Number[])
  5209. * get(ids: Number[], options: Object)
  5210. * get(ids: Number[], options: Object, data: Array | DataTable)
  5211. *
  5212. * Where:
  5213. *
  5214. * {Number | String} id The id of an item
  5215. * {Number[] | String{}} ids An array with ids of items
  5216. * {Object} options An Object with options. Available options:
  5217. * {String} [type] Type of data to be returned. Can
  5218. * be 'DataTable' or 'Array' (default)
  5219. * {Object.<String, String>} [convert]
  5220. * {String[]} [fields] field names to be returned
  5221. * {function} [filter] filter items
  5222. * {String | function} [order] Order the items by
  5223. * a field name or custom sort function.
  5224. * {Array | DataTable} [data] If provided, items will be appended to this
  5225. * array or table. Required in case of Google
  5226. * DataTable.
  5227. * @param args
  5228. */
  5229. DataView.prototype.get = function (args) {
  5230. var me = this;
  5231. // parse the arguments
  5232. var ids, options, data;
  5233. var firstType = util.getType(arguments[0]);
  5234. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  5235. // get(id(s) [, options] [, data])
  5236. ids = arguments[0]; // can be a single id or an array with ids
  5237. options = arguments[1];
  5238. data = arguments[2];
  5239. }
  5240. else {
  5241. // get([, options] [, data])
  5242. options = arguments[0];
  5243. data = arguments[1];
  5244. }
  5245. // extend the options with the default options and provided options
  5246. var viewOptions = util.extend({}, this._options, options);
  5247. // create a combined filter method when needed
  5248. if (this._options.filter && options && options.filter) {
  5249. viewOptions.filter = function (item) {
  5250. return me._options.filter(item) && options.filter(item);
  5251. }
  5252. }
  5253. // build up the call to the linked data set
  5254. var getArguments = [];
  5255. if (ids != undefined) {
  5256. getArguments.push(ids);
  5257. }
  5258. getArguments.push(viewOptions);
  5259. getArguments.push(data);
  5260. return this._data && this._data.get.apply(this._data, getArguments);
  5261. };
  5262. /**
  5263. * Get ids of all items or from a filtered set of items.
  5264. * @param {Object} [options] An Object with options. Available options:
  5265. * {function} [filter] filter items
  5266. * {String | function} [order] Order the items by
  5267. * a field name or custom sort function.
  5268. * @return {Array} ids
  5269. */
  5270. DataView.prototype.getIds = function (options) {
  5271. var ids;
  5272. if (this._data) {
  5273. var defaultFilter = this._options.filter;
  5274. var filter;
  5275. if (options && options.filter) {
  5276. if (defaultFilter) {
  5277. filter = function (item) {
  5278. return defaultFilter(item) && options.filter(item);
  5279. }
  5280. }
  5281. else {
  5282. filter = options.filter;
  5283. }
  5284. }
  5285. else {
  5286. filter = defaultFilter;
  5287. }
  5288. ids = this._data.getIds({
  5289. filter: filter,
  5290. order: options && options.order
  5291. });
  5292. }
  5293. else {
  5294. ids = [];
  5295. }
  5296. return ids;
  5297. };
  5298. /**
  5299. * Get the DataSet to which this DataView is connected. In case there is a chain
  5300. * of multiple DataViews, the root DataSet of this chain is returned.
  5301. * @return {DataSet} dataSet
  5302. */
  5303. DataView.prototype.getDataSet = function () {
  5304. var dataSet = this;
  5305. while (dataSet instanceof DataView) {
  5306. dataSet = dataSet._data;
  5307. }
  5308. return dataSet || null;
  5309. };
  5310. /**
  5311. * Event listener. Will propagate all events from the connected data set to
  5312. * the subscribers of the DataView, but will filter the items and only trigger
  5313. * when there are changes in the filtered data set.
  5314. * @param {String} event
  5315. * @param {Object | null} params
  5316. * @param {String} senderId
  5317. * @private
  5318. */
  5319. DataView.prototype._onEvent = function (event, params, senderId) {
  5320. var i, len, id, item,
  5321. ids = params && params.items,
  5322. data = this._data,
  5323. added = [],
  5324. updated = [],
  5325. removed = [];
  5326. if (ids && data) {
  5327. switch (event) {
  5328. case 'add':
  5329. // filter the ids of the added items
  5330. for (i = 0, len = ids.length; i < len; i++) {
  5331. id = ids[i];
  5332. item = this.get(id);
  5333. if (item) {
  5334. this._ids[id] = true;
  5335. added.push(id);
  5336. }
  5337. }
  5338. break;
  5339. case 'update':
  5340. // determine the event from the views viewpoint: an updated
  5341. // item can be added, updated, or removed from this view.
  5342. for (i = 0, len = ids.length; i < len; i++) {
  5343. id = ids[i];
  5344. item = this.get(id);
  5345. if (item) {
  5346. if (this._ids[id]) {
  5347. updated.push(id);
  5348. }
  5349. else {
  5350. this._ids[id] = true;
  5351. added.push(id);
  5352. }
  5353. }
  5354. else {
  5355. if (this._ids[id]) {
  5356. delete this._ids[id];
  5357. removed.push(id);
  5358. }
  5359. else {
  5360. // nothing interesting for me :-(
  5361. }
  5362. }
  5363. }
  5364. break;
  5365. case 'remove':
  5366. // filter the ids of the removed items
  5367. for (i = 0, len = ids.length; i < len; i++) {
  5368. id = ids[i];
  5369. if (this._ids[id]) {
  5370. delete this._ids[id];
  5371. removed.push(id);
  5372. }
  5373. }
  5374. break;
  5375. }
  5376. if (added.length) {
  5377. this._trigger('add', {items: added}, senderId);
  5378. }
  5379. if (updated.length) {
  5380. this._trigger('update', {items: updated}, senderId);
  5381. }
  5382. if (removed.length) {
  5383. this._trigger('remove', {items: removed}, senderId);
  5384. }
  5385. }
  5386. };
  5387. // copy subscription functionality from DataSet
  5388. DataView.prototype.on = DataSet.prototype.on;
  5389. DataView.prototype.off = DataSet.prototype.off;
  5390. DataView.prototype._trigger = DataSet.prototype._trigger;
  5391. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  5392. DataView.prototype.subscribe = DataView.prototype.on;
  5393. DataView.prototype.unsubscribe = DataView.prototype.off;
  5394. module.exports = DataView;
  5395. /***/ },
  5396. /* 10 */
  5397. /***/ function(module, exports, __webpack_require__) {
  5398. var Emitter = __webpack_require__(11);
  5399. var DataSet = __webpack_require__(7);
  5400. var DataView = __webpack_require__(9);
  5401. var util = __webpack_require__(1);
  5402. var Point3d = __webpack_require__(12);
  5403. var Point2d = __webpack_require__(13);
  5404. var Camera = __webpack_require__(14);
  5405. var Filter = __webpack_require__(15);
  5406. var Slider = __webpack_require__(16);
  5407. var StepNumber = __webpack_require__(17);
  5408. /**
  5409. * @constructor Graph3d
  5410. * Graph3d displays data in 3d.
  5411. *
  5412. * Graph3d is developed in javascript as a Google Visualization Chart.
  5413. *
  5414. * @param {Element} container The DOM element in which the Graph3d will
  5415. * be created. Normally a div element.
  5416. * @param {DataSet | DataView | Array} [data]
  5417. * @param {Object} [options]
  5418. */
  5419. function Graph3d(container, data, options) {
  5420. if (!(this instanceof Graph3d)) {
  5421. throw new SyntaxError('Constructor must be called with the new operator');
  5422. }
  5423. // create variables and set default values
  5424. this.containerElement = container;
  5425. this.width = '400px';
  5426. this.height = '400px';
  5427. this.margin = 10; // px
  5428. this.defaultXCenter = '55%';
  5429. this.defaultYCenter = '50%';
  5430. this.xLabel = 'x';
  5431. this.yLabel = 'y';
  5432. this.zLabel = 'z';
  5433. var passValueFn = function(v) { return v; };
  5434. this.xValueLabel = passValueFn;
  5435. this.yValueLabel = passValueFn;
  5436. this.zValueLabel = passValueFn;
  5437. this.filterLabel = 'time';
  5438. this.legendLabel = 'value';
  5439. this.style = Graph3d.STYLE.DOT;
  5440. this.showPerspective = true;
  5441. this.showGrid = true;
  5442. this.keepAspectRatio = true;
  5443. this.showShadow = false;
  5444. this.showGrayBottom = false; // TODO: this does not work correctly
  5445. this.showTooltip = false;
  5446. this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
  5447. this.animationInterval = 1000; // milliseconds
  5448. this.animationPreload = false;
  5449. this.camera = new Camera();
  5450. this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  5451. this.dataTable = null; // The original data table
  5452. this.dataPoints = null; // The table with point objects
  5453. // the column indexes
  5454. this.colX = undefined;
  5455. this.colY = undefined;
  5456. this.colZ = undefined;
  5457. this.colValue = undefined;
  5458. this.colFilter = undefined;
  5459. this.xMin = 0;
  5460. this.xStep = undefined; // auto by default
  5461. this.xMax = 1;
  5462. this.yMin = 0;
  5463. this.yStep = undefined; // auto by default
  5464. this.yMax = 1;
  5465. this.zMin = 0;
  5466. this.zStep = undefined; // auto by default
  5467. this.zMax = 1;
  5468. this.valueMin = 0;
  5469. this.valueMax = 1;
  5470. this.xBarWidth = 1;
  5471. this.yBarWidth = 1;
  5472. // TODO: customize axis range
  5473. // constants
  5474. this.colorAxis = '#4D4D4D';
  5475. this.colorGrid = '#D3D3D3';
  5476. this.colorDot = '#7DC1FF';
  5477. this.colorDotBorder = '#3267D2';
  5478. // create a frame and canvas
  5479. this.create();
  5480. // apply options (also when undefined)
  5481. this.setOptions(options);
  5482. // apply data
  5483. if (data) {
  5484. this.setData(data);
  5485. }
  5486. }
  5487. // Extend Graph3d with an Emitter mixin
  5488. Emitter(Graph3d.prototype);
  5489. /**
  5490. * Calculate the scaling values, dependent on the range in x, y, and z direction
  5491. */
  5492. Graph3d.prototype._setScale = function() {
  5493. this.scale = new Point3d(1 / (this.xMax - this.xMin),
  5494. 1 / (this.yMax - this.yMin),
  5495. 1 / (this.zMax - this.zMin));
  5496. // keep aspect ration between x and y scale if desired
  5497. if (this.keepAspectRatio) {
  5498. if (this.scale.x < this.scale.y) {
  5499. //noinspection JSSuspiciousNameCombination
  5500. this.scale.y = this.scale.x;
  5501. }
  5502. else {
  5503. //noinspection JSSuspiciousNameCombination
  5504. this.scale.x = this.scale.y;
  5505. }
  5506. }
  5507. // scale the vertical axis
  5508. this.scale.z *= this.verticalRatio;
  5509. // TODO: can this be automated? verticalRatio?
  5510. // determine scale for (optional) value
  5511. this.scale.value = 1 / (this.valueMax - this.valueMin);
  5512. // position the camera arm
  5513. var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
  5514. var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
  5515. var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
  5516. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  5517. };
  5518. /**
  5519. * Convert a 3D location to a 2D location on screen
  5520. * http://en.wikipedia.org/wiki/3D_projection
  5521. * @param {Point3d} point3d A 3D point with parameters x, y, z
  5522. * @return {Point2d} point2d A 2D point with parameters x, y
  5523. */
  5524. Graph3d.prototype._convert3Dto2D = function(point3d) {
  5525. var translation = this._convertPointToTranslation(point3d);
  5526. return this._convertTranslationToScreen(translation);
  5527. };
  5528. /**
  5529. * Convert a 3D location its translation seen from the camera
  5530. * http://en.wikipedia.org/wiki/3D_projection
  5531. * @param {Point3d} point3d A 3D point with parameters x, y, z
  5532. * @return {Point3d} translation A 3D point with parameters x, y, z This is
  5533. * the translation of the point, seen from the
  5534. * camera
  5535. */
  5536. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  5537. var ax = point3d.x * this.scale.x,
  5538. ay = point3d.y * this.scale.y,
  5539. az = point3d.z * this.scale.z,
  5540. cx = this.camera.getCameraLocation().x,
  5541. cy = this.camera.getCameraLocation().y,
  5542. cz = this.camera.getCameraLocation().z,
  5543. // calculate angles
  5544. sinTx = Math.sin(this.camera.getCameraRotation().x),
  5545. cosTx = Math.cos(this.camera.getCameraRotation().x),
  5546. sinTy = Math.sin(this.camera.getCameraRotation().y),
  5547. cosTy = Math.cos(this.camera.getCameraRotation().y),
  5548. sinTz = Math.sin(this.camera.getCameraRotation().z),
  5549. cosTz = Math.cos(this.camera.getCameraRotation().z),
  5550. // calculate translation
  5551. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  5552. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  5553. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  5554. return new Point3d(dx, dy, dz);
  5555. };
  5556. /**
  5557. * Convert a translation point to a point on the screen
  5558. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  5559. * the translation of the point, seen from the
  5560. * camera
  5561. * @return {Point2d} point2d A 2D point with parameters x, y
  5562. */
  5563. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  5564. var ex = this.eye.x,
  5565. ey = this.eye.y,
  5566. ez = this.eye.z,
  5567. dx = translation.x,
  5568. dy = translation.y,
  5569. dz = translation.z;
  5570. // calculate position on screen from translation
  5571. var bx;
  5572. var by;
  5573. if (this.showPerspective) {
  5574. bx = (dx - ex) * (ez / dz);
  5575. by = (dy - ey) * (ez / dz);
  5576. }
  5577. else {
  5578. bx = dx * -(ez / this.camera.getArmLength());
  5579. by = dy * -(ez / this.camera.getArmLength());
  5580. }
  5581. // shift and scale the point to the center of the screen
  5582. // use the width of the graph to scale both horizontally and vertically.
  5583. return new Point2d(
  5584. this.xcenter + bx * this.frame.canvas.clientWidth,
  5585. this.ycenter - by * this.frame.canvas.clientWidth);
  5586. };
  5587. /**
  5588. * Set the background styling for the graph
  5589. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  5590. */
  5591. Graph3d.prototype._setBackgroundColor = function(backgroundColor) {
  5592. var fill = 'white';
  5593. var stroke = 'gray';
  5594. var strokeWidth = 1;
  5595. if (typeof(backgroundColor) === 'string') {
  5596. fill = backgroundColor;
  5597. stroke = 'none';
  5598. strokeWidth = 0;
  5599. }
  5600. else if (typeof(backgroundColor) === 'object') {
  5601. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  5602. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  5603. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  5604. }
  5605. else if (backgroundColor === undefined) {
  5606. // use use defaults
  5607. }
  5608. else {
  5609. throw 'Unsupported type of backgroundColor';
  5610. }
  5611. this.frame.style.backgroundColor = fill;
  5612. this.frame.style.borderColor = stroke;
  5613. this.frame.style.borderWidth = strokeWidth + 'px';
  5614. this.frame.style.borderStyle = 'solid';
  5615. };
  5616. /// enumerate the available styles
  5617. Graph3d.STYLE = {
  5618. BAR: 0,
  5619. BARCOLOR: 1,
  5620. BARSIZE: 2,
  5621. DOT : 3,
  5622. DOTLINE : 4,
  5623. DOTCOLOR: 5,
  5624. DOTSIZE: 6,
  5625. GRID : 7,
  5626. LINE: 8,
  5627. SURFACE : 9
  5628. };
  5629. /**
  5630. * Retrieve the style index from given styleName
  5631. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  5632. * @return {Number} styleNumber Enumeration value representing the style, or -1
  5633. * when not found
  5634. */
  5635. Graph3d.prototype._getStyleNumber = function(styleName) {
  5636. switch (styleName) {
  5637. case 'dot': return Graph3d.STYLE.DOT;
  5638. case 'dot-line': return Graph3d.STYLE.DOTLINE;
  5639. case 'dot-color': return Graph3d.STYLE.DOTCOLOR;
  5640. case 'dot-size': return Graph3d.STYLE.DOTSIZE;
  5641. case 'line': return Graph3d.STYLE.LINE;
  5642. case 'grid': return Graph3d.STYLE.GRID;
  5643. case 'surface': return Graph3d.STYLE.SURFACE;
  5644. case 'bar': return Graph3d.STYLE.BAR;
  5645. case 'bar-color': return Graph3d.STYLE.BARCOLOR;
  5646. case 'bar-size': return Graph3d.STYLE.BARSIZE;
  5647. }
  5648. return -1;
  5649. };
  5650. /**
  5651. * Determine the indexes of the data columns, based on the given style and data
  5652. * @param {DataSet} data
  5653. * @param {Number} style
  5654. */
  5655. Graph3d.prototype._determineColumnIndexes = function(data, style) {
  5656. if (this.style === Graph3d.STYLE.DOT ||
  5657. this.style === Graph3d.STYLE.DOTLINE ||
  5658. this.style === Graph3d.STYLE.LINE ||
  5659. this.style === Graph3d.STYLE.GRID ||
  5660. this.style === Graph3d.STYLE.SURFACE ||
  5661. this.style === Graph3d.STYLE.BAR) {
  5662. // 3 columns expected, and optionally a 4th with filter values
  5663. this.colX = 0;
  5664. this.colY = 1;
  5665. this.colZ = 2;
  5666. this.colValue = undefined;
  5667. if (data.getNumberOfColumns() > 3) {
  5668. this.colFilter = 3;
  5669. }
  5670. }
  5671. else if (this.style === Graph3d.STYLE.DOTCOLOR ||
  5672. this.style === Graph3d.STYLE.DOTSIZE ||
  5673. this.style === Graph3d.STYLE.BARCOLOR ||
  5674. this.style === Graph3d.STYLE.BARSIZE) {
  5675. // 4 columns expected, and optionally a 5th with filter values
  5676. this.colX = 0;
  5677. this.colY = 1;
  5678. this.colZ = 2;
  5679. this.colValue = 3;
  5680. if (data.getNumberOfColumns() > 4) {
  5681. this.colFilter = 4;
  5682. }
  5683. }
  5684. else {
  5685. throw 'Unknown style "' + this.style + '"';
  5686. }
  5687. };
  5688. Graph3d.prototype.getNumberOfRows = function(data) {
  5689. return data.length;
  5690. }
  5691. Graph3d.prototype.getNumberOfColumns = function(data) {
  5692. var counter = 0;
  5693. for (var column in data[0]) {
  5694. if (data[0].hasOwnProperty(column)) {
  5695. counter++;
  5696. }
  5697. }
  5698. return counter;
  5699. }
  5700. Graph3d.prototype.getDistinctValues = function(data, column) {
  5701. var distinctValues = [];
  5702. for (var i = 0; i < data.length; i++) {
  5703. if (distinctValues.indexOf(data[i][column]) == -1) {
  5704. distinctValues.push(data[i][column]);
  5705. }
  5706. }
  5707. return distinctValues;
  5708. }
  5709. Graph3d.prototype.getColumnRange = function(data,column) {
  5710. var minMax = {min:data[0][column],max:data[0][column]};
  5711. for (var i = 0; i < data.length; i++) {
  5712. if (minMax.min > data[i][column]) { minMax.min = data[i][column]; }
  5713. if (minMax.max < data[i][column]) { minMax.max = data[i][column]; }
  5714. }
  5715. return minMax;
  5716. };
  5717. /**
  5718. * Initialize the data from the data table. Calculate minimum and maximum values
  5719. * and column index values
  5720. * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
  5721. * @param {Number} style Style Number
  5722. */
  5723. Graph3d.prototype._dataInitialize = function (rawData, style) {
  5724. var me = this;
  5725. // unsubscribe from the dataTable
  5726. if (this.dataSet) {
  5727. this.dataSet.off('*', this._onChange);
  5728. }
  5729. if (rawData === undefined)
  5730. return;
  5731. if (Array.isArray(rawData)) {
  5732. rawData = new DataSet(rawData);
  5733. }
  5734. var data;
  5735. if (rawData instanceof DataSet || rawData instanceof DataView) {
  5736. data = rawData.get();
  5737. }
  5738. else {
  5739. throw new Error('Array, DataSet, or DataView expected');
  5740. }
  5741. if (data.length == 0)
  5742. return;
  5743. this.dataSet = rawData;
  5744. this.dataTable = data;
  5745. // subscribe to changes in the dataset
  5746. this._onChange = function () {
  5747. me.setData(me.dataSet);
  5748. };
  5749. this.dataSet.on('*', this._onChange);
  5750. // _determineColumnIndexes
  5751. // getNumberOfRows (points)
  5752. // getNumberOfColumns (x,y,z,v,t,t1,t2...)
  5753. // getDistinctValues (unique values?)
  5754. // getColumnRange
  5755. // determine the location of x,y,z,value,filter columns
  5756. this.colX = 'x';
  5757. this.colY = 'y';
  5758. this.colZ = 'z';
  5759. this.colValue = 'style';
  5760. this.colFilter = 'filter';
  5761. // check if a filter column is provided
  5762. if (data[0].hasOwnProperty('filter')) {
  5763. if (this.dataFilter === undefined) {
  5764. this.dataFilter = new Filter(rawData, this.colFilter, this);
  5765. this.dataFilter.setOnLoadCallback(function() {me.redraw();});
  5766. }
  5767. }
  5768. var withBars = this.style == Graph3d.STYLE.BAR ||
  5769. this.style == Graph3d.STYLE.BARCOLOR ||
  5770. this.style == Graph3d.STYLE.BARSIZE;
  5771. // determine barWidth from data
  5772. if (withBars) {
  5773. if (this.defaultXBarWidth !== undefined) {
  5774. this.xBarWidth = this.defaultXBarWidth;
  5775. }
  5776. else {
  5777. var dataX = this.getDistinctValues(data,this.colX);
  5778. this.xBarWidth = (dataX[1] - dataX[0]) || 1;
  5779. }
  5780. if (this.defaultYBarWidth !== undefined) {
  5781. this.yBarWidth = this.defaultYBarWidth;
  5782. }
  5783. else {
  5784. var dataY = this.getDistinctValues(data,this.colY);
  5785. this.yBarWidth = (dataY[1] - dataY[0]) || 1;
  5786. }
  5787. }
  5788. // calculate minimums and maximums
  5789. var xRange = this.getColumnRange(data,this.colX);
  5790. if (withBars) {
  5791. xRange.min -= this.xBarWidth / 2;
  5792. xRange.max += this.xBarWidth / 2;
  5793. }
  5794. this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min;
  5795. this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max;
  5796. if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
  5797. this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5;
  5798. var yRange = this.getColumnRange(data,this.colY);
  5799. if (withBars) {
  5800. yRange.min -= this.yBarWidth / 2;
  5801. yRange.max += this.yBarWidth / 2;
  5802. }
  5803. this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min;
  5804. this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max;
  5805. if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
  5806. this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5;
  5807. var zRange = this.getColumnRange(data,this.colZ);
  5808. this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min;
  5809. this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max;
  5810. if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
  5811. this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5;
  5812. if (this.colValue !== undefined) {
  5813. var valueRange = this.getColumnRange(data,this.colValue);
  5814. this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min;
  5815. this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max;
  5816. if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
  5817. }
  5818. // set the scale dependent on the ranges.
  5819. this._setScale();
  5820. };
  5821. /**
  5822. * Filter the data based on the current filter
  5823. * @param {Array} data
  5824. * @return {Array} dataPoints Array with point objects which can be drawn on screen
  5825. */
  5826. Graph3d.prototype._getDataPoints = function (data) {
  5827. // TODO: store the created matrix dataPoints in the filters instead of reloading each time
  5828. var x, y, i, z, obj, point;
  5829. var dataPoints = [];
  5830. if (this.style === Graph3d.STYLE.GRID ||
  5831. this.style === Graph3d.STYLE.SURFACE) {
  5832. // copy all values from the google data table to a matrix
  5833. // the provided values are supposed to form a grid of (x,y) positions
  5834. // create two lists with all present x and y values
  5835. var dataX = [];
  5836. var dataY = [];
  5837. for (i = 0; i < this.getNumberOfRows(data); i++) {
  5838. x = data[i][this.colX] || 0;
  5839. y = data[i][this.colY] || 0;
  5840. if (dataX.indexOf(x) === -1) {
  5841. dataX.push(x);
  5842. }
  5843. if (dataY.indexOf(y) === -1) {
  5844. dataY.push(y);
  5845. }
  5846. }
  5847. var sortNumber = function (a, b) {
  5848. return a - b;
  5849. };
  5850. dataX.sort(sortNumber);
  5851. dataY.sort(sortNumber);
  5852. // create a grid, a 2d matrix, with all values.
  5853. var dataMatrix = []; // temporary data matrix
  5854. for (i = 0; i < data.length; i++) {
  5855. x = data[i][this.colX] || 0;
  5856. y = data[i][this.colY] || 0;
  5857. z = data[i][this.colZ] || 0;
  5858. var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
  5859. var yIndex = dataY.indexOf(y);
  5860. if (dataMatrix[xIndex] === undefined) {
  5861. dataMatrix[xIndex] = [];
  5862. }
  5863. var point3d = new Point3d();
  5864. point3d.x = x;
  5865. point3d.y = y;
  5866. point3d.z = z;
  5867. obj = {};
  5868. obj.point = point3d;
  5869. obj.trans = undefined;
  5870. obj.screen = undefined;
  5871. obj.bottom = new Point3d(x, y, this.zMin);
  5872. dataMatrix[xIndex][yIndex] = obj;
  5873. dataPoints.push(obj);
  5874. }
  5875. // fill in the pointers to the neighbors.
  5876. for (x = 0; x < dataMatrix.length; x++) {
  5877. for (y = 0; y < dataMatrix[x].length; y++) {
  5878. if (dataMatrix[x][y]) {
  5879. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  5880. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  5881. dataMatrix[x][y].pointCross =
  5882. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  5883. dataMatrix[x+1][y+1] :
  5884. undefined;
  5885. }
  5886. }
  5887. }
  5888. }
  5889. else { // 'dot', 'dot-line', etc.
  5890. // copy all values from the google data table to a list with Point3d objects
  5891. for (i = 0; i < data.length; i++) {
  5892. point = new Point3d();
  5893. point.x = data[i][this.colX] || 0;
  5894. point.y = data[i][this.colY] || 0;
  5895. point.z = data[i][this.colZ] || 0;
  5896. if (this.colValue !== undefined) {
  5897. point.value = data[i][this.colValue] || 0;
  5898. }
  5899. obj = {};
  5900. obj.point = point;
  5901. obj.bottom = new Point3d(point.x, point.y, this.zMin);
  5902. obj.trans = undefined;
  5903. obj.screen = undefined;
  5904. dataPoints.push(obj);
  5905. }
  5906. }
  5907. return dataPoints;
  5908. };
  5909. /**
  5910. * Create the main frame for the Graph3d.
  5911. * This function is executed once when a Graph3d object is created. The frame
  5912. * contains a canvas, and this canvas contains all objects like the axis and
  5913. * nodes.
  5914. */
  5915. Graph3d.prototype.create = function () {
  5916. // remove all elements from the container element.
  5917. while (this.containerElement.hasChildNodes()) {
  5918. this.containerElement.removeChild(this.containerElement.firstChild);
  5919. }
  5920. this.frame = document.createElement('div');
  5921. this.frame.style.position = 'relative';
  5922. this.frame.style.overflow = 'hidden';
  5923. // create the graph canvas (HTML canvas element)
  5924. this.frame.canvas = document.createElement( 'canvas' );
  5925. this.frame.canvas.style.position = 'relative';
  5926. this.frame.appendChild(this.frame.canvas);
  5927. //if (!this.frame.canvas.getContext) {
  5928. {
  5929. var noCanvas = document.createElement( 'DIV' );
  5930. noCanvas.style.color = 'red';
  5931. noCanvas.style.fontWeight = 'bold' ;
  5932. noCanvas.style.padding = '10px';
  5933. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  5934. this.frame.canvas.appendChild(noCanvas);
  5935. }
  5936. this.frame.filter = document.createElement( 'div' );
  5937. this.frame.filter.style.position = 'absolute';
  5938. this.frame.filter.style.bottom = '0px';
  5939. this.frame.filter.style.left = '0px';
  5940. this.frame.filter.style.width = '100%';
  5941. this.frame.appendChild(this.frame.filter);
  5942. // add event listeners to handle moving and zooming the contents
  5943. var me = this;
  5944. var onmousedown = function (event) {me._onMouseDown(event);};
  5945. var ontouchstart = function (event) {me._onTouchStart(event);};
  5946. var onmousewheel = function (event) {me._onWheel(event);};
  5947. var ontooltip = function (event) {me._onTooltip(event);};
  5948. // TODO: these events are never cleaned up... can give a 'memory leakage'
  5949. util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
  5950. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  5951. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  5952. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  5953. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  5954. // add the new graph to the container element
  5955. this.containerElement.appendChild(this.frame);
  5956. };
  5957. /**
  5958. * Set a new size for the graph
  5959. * @param {string} width Width in pixels or percentage (for example '800px'
  5960. * or '50%')
  5961. * @param {string} height Height in pixels or percentage (for example '400px'
  5962. * or '30%')
  5963. */
  5964. Graph3d.prototype.setSize = function(width, height) {
  5965. this.frame.style.width = width;
  5966. this.frame.style.height = height;
  5967. this._resizeCanvas();
  5968. };
  5969. /**
  5970. * Resize the canvas to the current size of the frame
  5971. */
  5972. Graph3d.prototype._resizeCanvas = function() {
  5973. this.frame.canvas.style.width = '100%';
  5974. this.frame.canvas.style.height = '100%';
  5975. this.frame.canvas.width = this.frame.canvas.clientWidth;
  5976. this.frame.canvas.height = this.frame.canvas.clientHeight;
  5977. // adjust with for margin
  5978. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  5979. };
  5980. /**
  5981. * Start animation
  5982. */
  5983. Graph3d.prototype.animationStart = function() {
  5984. if (!this.frame.filter || !this.frame.filter.slider)
  5985. throw 'No animation available';
  5986. this.frame.filter.slider.play();
  5987. };
  5988. /**
  5989. * Stop animation
  5990. */
  5991. Graph3d.prototype.animationStop = function() {
  5992. if (!this.frame.filter || !this.frame.filter.slider) return;
  5993. this.frame.filter.slider.stop();
  5994. };
  5995. /**
  5996. * Resize the center position based on the current values in this.defaultXCenter
  5997. * and this.defaultYCenter (which are strings with a percentage or a value
  5998. * in pixels). The center positions are the variables this.xCenter
  5999. * and this.yCenter
  6000. */
  6001. Graph3d.prototype._resizeCenter = function() {
  6002. // calculate the horizontal center position
  6003. if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') {
  6004. this.xcenter =
  6005. parseFloat(this.defaultXCenter) / 100 *
  6006. this.frame.canvas.clientWidth;
  6007. }
  6008. else {
  6009. this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
  6010. }
  6011. // calculate the vertical center position
  6012. if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') {
  6013. this.ycenter =
  6014. parseFloat(this.defaultYCenter) / 100 *
  6015. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  6016. }
  6017. else {
  6018. this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
  6019. }
  6020. };
  6021. /**
  6022. * Set the rotation and distance of the camera
  6023. * @param {Object} pos An object with the camera position. The object
  6024. * contains three parameters:
  6025. * - horizontal {Number}
  6026. * The horizontal rotation, between 0 and 2*PI.
  6027. * Optional, can be left undefined.
  6028. * - vertical {Number}
  6029. * The vertical rotation, between 0 and 0.5*PI
  6030. * if vertical=0.5*PI, the graph is shown from the
  6031. * top. Optional, can be left undefined.
  6032. * - distance {Number}
  6033. * The (normalized) distance of the camera to the
  6034. * center of the graph, a value between 0.71 and 5.0.
  6035. * Optional, can be left undefined.
  6036. */
  6037. Graph3d.prototype.setCameraPosition = function(pos) {
  6038. if (pos === undefined) {
  6039. return;
  6040. }
  6041. if (pos.horizontal !== undefined && pos.vertical !== undefined) {
  6042. this.camera.setArmRotation(pos.horizontal, pos.vertical);
  6043. }
  6044. if (pos.distance !== undefined) {
  6045. this.camera.setArmLength(pos.distance);
  6046. }
  6047. this.redraw();
  6048. };
  6049. /**
  6050. * Retrieve the current camera rotation
  6051. * @return {object} An object with parameters horizontal, vertical, and
  6052. * distance
  6053. */
  6054. Graph3d.prototype.getCameraPosition = function() {
  6055. var pos = this.camera.getArmRotation();
  6056. pos.distance = this.camera.getArmLength();
  6057. return pos;
  6058. };
  6059. /**
  6060. * Load data into the 3D Graph
  6061. */
  6062. Graph3d.prototype._readData = function(data) {
  6063. // read the data
  6064. this._dataInitialize(data, this.style);
  6065. if (this.dataFilter) {
  6066. // apply filtering
  6067. this.dataPoints = this.dataFilter._getDataPoints();
  6068. }
  6069. else {
  6070. // no filtering. load all data
  6071. this.dataPoints = this._getDataPoints(this.dataTable);
  6072. }
  6073. // draw the filter
  6074. this._redrawFilter();
  6075. };
  6076. /**
  6077. * Replace the dataset of the Graph3d
  6078. * @param {Array | DataSet | DataView} data
  6079. */
  6080. Graph3d.prototype.setData = function (data) {
  6081. this._readData(data);
  6082. this.redraw();
  6083. // start animation when option is true
  6084. if (this.animationAutoStart && this.dataFilter) {
  6085. this.animationStart();
  6086. }
  6087. };
  6088. /**
  6089. * Update the options. Options will be merged with current options
  6090. * @param {Object} options
  6091. */
  6092. Graph3d.prototype.setOptions = function (options) {
  6093. var cameraPosition = undefined;
  6094. this.animationStop();
  6095. if (options !== undefined) {
  6096. // retrieve parameter values
  6097. if (options.width !== undefined) this.width = options.width;
  6098. if (options.height !== undefined) this.height = options.height;
  6099. if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
  6100. if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
  6101. if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
  6102. if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
  6103. if (options.xLabel !== undefined) this.xLabel = options.xLabel;
  6104. if (options.yLabel !== undefined) this.yLabel = options.yLabel;
  6105. if (options.zLabel !== undefined) this.zLabel = options.zLabel;
  6106. if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel;
  6107. if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel;
  6108. if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel;
  6109. if (options.style !== undefined) {
  6110. var styleNumber = this._getStyleNumber(options.style);
  6111. if (styleNumber !== -1) {
  6112. this.style = styleNumber;
  6113. }
  6114. }
  6115. if (options.showGrid !== undefined) this.showGrid = options.showGrid;
  6116. if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
  6117. if (options.showShadow !== undefined) this.showShadow = options.showShadow;
  6118. if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
  6119. if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
  6120. if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
  6121. if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
  6122. if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
  6123. if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
  6124. if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart;
  6125. if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
  6126. if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
  6127. if (options.xMin !== undefined) this.defaultXMin = options.xMin;
  6128. if (options.xStep !== undefined) this.defaultXStep = options.xStep;
  6129. if (options.xMax !== undefined) this.defaultXMax = options.xMax;
  6130. if (options.yMin !== undefined) this.defaultYMin = options.yMin;
  6131. if (options.yStep !== undefined) this.defaultYStep = options.yStep;
  6132. if (options.yMax !== undefined) this.defaultYMax = options.yMax;
  6133. if (options.zMin !== undefined) this.defaultZMin = options.zMin;
  6134. if (options.zStep !== undefined) this.defaultZStep = options.zStep;
  6135. if (options.zMax !== undefined) this.defaultZMax = options.zMax;
  6136. if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
  6137. if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
  6138. if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
  6139. if (cameraPosition !== undefined) {
  6140. this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
  6141. this.camera.setArmLength(cameraPosition.distance);
  6142. }
  6143. else {
  6144. this.camera.setArmRotation(1.0, 0.5);
  6145. this.camera.setArmLength(1.7);
  6146. }
  6147. }
  6148. this._setBackgroundColor(options && options.backgroundColor);
  6149. this.setSize(this.width, this.height);
  6150. // re-load the data
  6151. if (this.dataTable) {
  6152. this.setData(this.dataTable);
  6153. }
  6154. // start animation when option is true
  6155. if (this.animationAutoStart && this.dataFilter) {
  6156. this.animationStart();
  6157. }
  6158. };
  6159. /**
  6160. * Redraw the Graph.
  6161. */
  6162. Graph3d.prototype.redraw = function() {
  6163. if (this.dataPoints === undefined) {
  6164. throw 'Error: graph data not initialized';
  6165. }
  6166. this._resizeCanvas();
  6167. this._resizeCenter();
  6168. this._redrawSlider();
  6169. this._redrawClear();
  6170. this._redrawAxis();
  6171. if (this.style === Graph3d.STYLE.GRID ||
  6172. this.style === Graph3d.STYLE.SURFACE) {
  6173. this._redrawDataGrid();
  6174. }
  6175. else if (this.style === Graph3d.STYLE.LINE) {
  6176. this._redrawDataLine();
  6177. }
  6178. else if (this.style === Graph3d.STYLE.BAR ||
  6179. this.style === Graph3d.STYLE.BARCOLOR ||
  6180. this.style === Graph3d.STYLE.BARSIZE) {
  6181. this._redrawDataBar();
  6182. }
  6183. else {
  6184. // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
  6185. this._redrawDataDot();
  6186. }
  6187. this._redrawInfo();
  6188. this._redrawLegend();
  6189. };
  6190. /**
  6191. * Clear the canvas before redrawing
  6192. */
  6193. Graph3d.prototype._redrawClear = function() {
  6194. var canvas = this.frame.canvas;
  6195. var ctx = canvas.getContext('2d');
  6196. ctx.clearRect(0, 0, canvas.width, canvas.height);
  6197. };
  6198. /**
  6199. * Redraw the legend showing the colors
  6200. */
  6201. Graph3d.prototype._redrawLegend = function() {
  6202. var y;
  6203. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  6204. this.style === Graph3d.STYLE.DOTSIZE) {
  6205. var dotSize = this.frame.clientWidth * 0.02;
  6206. var widthMin, widthMax;
  6207. if (this.style === Graph3d.STYLE.DOTSIZE) {
  6208. widthMin = dotSize / 2; // px
  6209. widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
  6210. }
  6211. else {
  6212. widthMin = 20; // px
  6213. widthMax = 20; // px
  6214. }
  6215. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  6216. var top = this.margin;
  6217. var right = this.frame.clientWidth - this.margin;
  6218. var left = right - widthMax;
  6219. var bottom = top + height;
  6220. }
  6221. var canvas = this.frame.canvas;
  6222. var ctx = canvas.getContext('2d');
  6223. ctx.lineWidth = 1;
  6224. ctx.font = '14px arial'; // TODO: put in options
  6225. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  6226. // draw the color bar
  6227. var ymin = 0;
  6228. var ymax = height; // Todo: make height customizable
  6229. for (y = ymin; y < ymax; y++) {
  6230. var f = (y - ymin) / (ymax - ymin);
  6231. //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
  6232. var hue = f * 240;
  6233. var color = this._hsv2rgb(hue, 1, 1);
  6234. ctx.strokeStyle = color;
  6235. ctx.beginPath();
  6236. ctx.moveTo(left, top + y);
  6237. ctx.lineTo(right, top + y);
  6238. ctx.stroke();
  6239. }
  6240. ctx.strokeStyle = this.colorAxis;
  6241. ctx.strokeRect(left, top, widthMax, height);
  6242. }
  6243. if (this.style === Graph3d.STYLE.DOTSIZE) {
  6244. // draw border around color bar
  6245. ctx.strokeStyle = this.colorAxis;
  6246. ctx.fillStyle = this.colorDot;
  6247. ctx.beginPath();
  6248. ctx.moveTo(left, top);
  6249. ctx.lineTo(right, top);
  6250. ctx.lineTo(right - widthMax + widthMin, bottom);
  6251. ctx.lineTo(left, bottom);
  6252. ctx.closePath();
  6253. ctx.fill();
  6254. ctx.stroke();
  6255. }
  6256. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  6257. this.style === Graph3d.STYLE.DOTSIZE) {
  6258. // print values along the color bar
  6259. var gridLineLen = 5; // px
  6260. var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true);
  6261. step.start();
  6262. if (step.getCurrent() < this.valueMin) {
  6263. step.next();
  6264. }
  6265. while (!step.end()) {
  6266. y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
  6267. ctx.beginPath();
  6268. ctx.moveTo(left - gridLineLen, y);
  6269. ctx.lineTo(left, y);
  6270. ctx.stroke();
  6271. ctx.textAlign = 'right';
  6272. ctx.textBaseline = 'middle';
  6273. ctx.fillStyle = this.colorAxis;
  6274. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  6275. step.next();
  6276. }
  6277. ctx.textAlign = 'right';
  6278. ctx.textBaseline = 'top';
  6279. var label = this.legendLabel;
  6280. ctx.fillText(label, right, bottom + this.margin);
  6281. }
  6282. };
  6283. /**
  6284. * Redraw the filter
  6285. */
  6286. Graph3d.prototype._redrawFilter = function() {
  6287. this.frame.filter.innerHTML = '';
  6288. if (this.dataFilter) {
  6289. var options = {
  6290. 'visible': this.showAnimationControls
  6291. };
  6292. var slider = new Slider(this.frame.filter, options);
  6293. this.frame.filter.slider = slider;
  6294. // TODO: css here is not nice here...
  6295. this.frame.filter.style.padding = '10px';
  6296. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  6297. slider.setValues(this.dataFilter.values);
  6298. slider.setPlayInterval(this.animationInterval);
  6299. // create an event handler
  6300. var me = this;
  6301. var onchange = function () {
  6302. var index = slider.getIndex();
  6303. me.dataFilter.selectValue(index);
  6304. me.dataPoints = me.dataFilter._getDataPoints();
  6305. me.redraw();
  6306. };
  6307. slider.setOnChangeCallback(onchange);
  6308. }
  6309. else {
  6310. this.frame.filter.slider = undefined;
  6311. }
  6312. };
  6313. /**
  6314. * Redraw the slider
  6315. */
  6316. Graph3d.prototype._redrawSlider = function() {
  6317. if ( this.frame.filter.slider !== undefined) {
  6318. this.frame.filter.slider.redraw();
  6319. }
  6320. };
  6321. /**
  6322. * Redraw common information
  6323. */
  6324. Graph3d.prototype._redrawInfo = function() {
  6325. if (this.dataFilter) {
  6326. var canvas = this.frame.canvas;
  6327. var ctx = canvas.getContext('2d');
  6328. ctx.font = '14px arial'; // TODO: put in options
  6329. ctx.lineStyle = 'gray';
  6330. ctx.fillStyle = 'gray';
  6331. ctx.textAlign = 'left';
  6332. ctx.textBaseline = 'top';
  6333. var x = this.margin;
  6334. var y = this.margin;
  6335. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  6336. }
  6337. };
  6338. /**
  6339. * Redraw the axis
  6340. */
  6341. Graph3d.prototype._redrawAxis = function() {
  6342. var canvas = this.frame.canvas,
  6343. ctx = canvas.getContext('2d'),
  6344. from, to, step, prettyStep,
  6345. text, xText, yText, zText,
  6346. offset, xOffset, yOffset,
  6347. xMin2d, xMax2d;
  6348. // TODO: get the actual rendered style of the containerElement
  6349. //ctx.font = this.containerElement.style.font;
  6350. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  6351. // calculate the length for the short grid lines
  6352. var gridLenX = 0.025 / this.scale.x;
  6353. var gridLenY = 0.025 / this.scale.y;
  6354. var textMargin = 5 / this.camera.getArmLength(); // px
  6355. var armAngle = this.camera.getArmRotation().horizontal;
  6356. // draw x-grid lines
  6357. ctx.lineWidth = 1;
  6358. prettyStep = (this.defaultXStep === undefined);
  6359. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  6360. step.start();
  6361. if (step.getCurrent() < this.xMin) {
  6362. step.next();
  6363. }
  6364. while (!step.end()) {
  6365. var x = step.getCurrent();
  6366. if (this.showGrid) {
  6367. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  6368. to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  6369. ctx.strokeStyle = this.colorGrid;
  6370. ctx.beginPath();
  6371. ctx.moveTo(from.x, from.y);
  6372. ctx.lineTo(to.x, to.y);
  6373. ctx.stroke();
  6374. }
  6375. else {
  6376. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  6377. to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin));
  6378. ctx.strokeStyle = this.colorAxis;
  6379. ctx.beginPath();
  6380. ctx.moveTo(from.x, from.y);
  6381. ctx.lineTo(to.x, to.y);
  6382. ctx.stroke();
  6383. from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  6384. to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin));
  6385. ctx.strokeStyle = this.colorAxis;
  6386. ctx.beginPath();
  6387. ctx.moveTo(from.x, from.y);
  6388. ctx.lineTo(to.x, to.y);
  6389. ctx.stroke();
  6390. }
  6391. yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax;
  6392. text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
  6393. if (Math.cos(armAngle * 2) > 0) {
  6394. ctx.textAlign = 'center';
  6395. ctx.textBaseline = 'top';
  6396. text.y += textMargin;
  6397. }
  6398. else if (Math.sin(armAngle * 2) < 0){
  6399. ctx.textAlign = 'right';
  6400. ctx.textBaseline = 'middle';
  6401. }
  6402. else {
  6403. ctx.textAlign = 'left';
  6404. ctx.textBaseline = 'middle';
  6405. }
  6406. ctx.fillStyle = this.colorAxis;
  6407. ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  6408. step.next();
  6409. }
  6410. // draw y-grid lines
  6411. ctx.lineWidth = 1;
  6412. prettyStep = (this.defaultYStep === undefined);
  6413. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  6414. step.start();
  6415. if (step.getCurrent() < this.yMin) {
  6416. step.next();
  6417. }
  6418. while (!step.end()) {
  6419. if (this.showGrid) {
  6420. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  6421. to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  6422. ctx.strokeStyle = this.colorGrid;
  6423. ctx.beginPath();
  6424. ctx.moveTo(from.x, from.y);
  6425. ctx.lineTo(to.x, to.y);
  6426. ctx.stroke();
  6427. }
  6428. else {
  6429. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  6430. to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin));
  6431. ctx.strokeStyle = this.colorAxis;
  6432. ctx.beginPath();
  6433. ctx.moveTo(from.x, from.y);
  6434. ctx.lineTo(to.x, to.y);
  6435. ctx.stroke();
  6436. from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  6437. to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin));
  6438. ctx.strokeStyle = this.colorAxis;
  6439. ctx.beginPath();
  6440. ctx.moveTo(from.x, from.y);
  6441. ctx.lineTo(to.x, to.y);
  6442. ctx.stroke();
  6443. }
  6444. xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax;
  6445. text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
  6446. if (Math.cos(armAngle * 2) < 0) {
  6447. ctx.textAlign = 'center';
  6448. ctx.textBaseline = 'top';
  6449. text.y += textMargin;
  6450. }
  6451. else if (Math.sin(armAngle * 2) > 0){
  6452. ctx.textAlign = 'right';
  6453. ctx.textBaseline = 'middle';
  6454. }
  6455. else {
  6456. ctx.textAlign = 'left';
  6457. ctx.textBaseline = 'middle';
  6458. }
  6459. ctx.fillStyle = this.colorAxis;
  6460. ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  6461. step.next();
  6462. }
  6463. // draw z-grid lines and axis
  6464. ctx.lineWidth = 1;
  6465. prettyStep = (this.defaultZStep === undefined);
  6466. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  6467. step.start();
  6468. if (step.getCurrent() < this.zMin) {
  6469. step.next();
  6470. }
  6471. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  6472. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  6473. while (!step.end()) {
  6474. // TODO: make z-grid lines really 3d?
  6475. from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
  6476. ctx.strokeStyle = this.colorAxis;
  6477. ctx.beginPath();
  6478. ctx.moveTo(from.x, from.y);
  6479. ctx.lineTo(from.x - textMargin, from.y);
  6480. ctx.stroke();
  6481. ctx.textAlign = 'right';
  6482. ctx.textBaseline = 'middle';
  6483. ctx.fillStyle = this.colorAxis;
  6484. ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y);
  6485. step.next();
  6486. }
  6487. ctx.lineWidth = 1;
  6488. from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  6489. to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
  6490. ctx.strokeStyle = this.colorAxis;
  6491. ctx.beginPath();
  6492. ctx.moveTo(from.x, from.y);
  6493. ctx.lineTo(to.x, to.y);
  6494. ctx.stroke();
  6495. // draw x-axis
  6496. ctx.lineWidth = 1;
  6497. // line at yMin
  6498. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  6499. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  6500. ctx.strokeStyle = this.colorAxis;
  6501. ctx.beginPath();
  6502. ctx.moveTo(xMin2d.x, xMin2d.y);
  6503. ctx.lineTo(xMax2d.x, xMax2d.y);
  6504. ctx.stroke();
  6505. // line at ymax
  6506. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  6507. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  6508. ctx.strokeStyle = this.colorAxis;
  6509. ctx.beginPath();
  6510. ctx.moveTo(xMin2d.x, xMin2d.y);
  6511. ctx.lineTo(xMax2d.x, xMax2d.y);
  6512. ctx.stroke();
  6513. // draw y-axis
  6514. ctx.lineWidth = 1;
  6515. // line at xMin
  6516. from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  6517. to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  6518. ctx.strokeStyle = this.colorAxis;
  6519. ctx.beginPath();
  6520. ctx.moveTo(from.x, from.y);
  6521. ctx.lineTo(to.x, to.y);
  6522. ctx.stroke();
  6523. // line at xMax
  6524. from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  6525. to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  6526. ctx.strokeStyle = this.colorAxis;
  6527. ctx.beginPath();
  6528. ctx.moveTo(from.x, from.y);
  6529. ctx.lineTo(to.x, to.y);
  6530. ctx.stroke();
  6531. // draw x-label
  6532. var xLabel = this.xLabel;
  6533. if (xLabel.length > 0) {
  6534. yOffset = 0.1 / this.scale.y;
  6535. xText = (this.xMin + this.xMax) / 2;
  6536. yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset;
  6537. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  6538. if (Math.cos(armAngle * 2) > 0) {
  6539. ctx.textAlign = 'center';
  6540. ctx.textBaseline = 'top';
  6541. }
  6542. else if (Math.sin(armAngle * 2) < 0){
  6543. ctx.textAlign = 'right';
  6544. ctx.textBaseline = 'middle';
  6545. }
  6546. else {
  6547. ctx.textAlign = 'left';
  6548. ctx.textBaseline = 'middle';
  6549. }
  6550. ctx.fillStyle = this.colorAxis;
  6551. ctx.fillText(xLabel, text.x, text.y);
  6552. }
  6553. // draw y-label
  6554. var yLabel = this.yLabel;
  6555. if (yLabel.length > 0) {
  6556. xOffset = 0.1 / this.scale.x;
  6557. xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset;
  6558. yText = (this.yMin + this.yMax) / 2;
  6559. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  6560. if (Math.cos(armAngle * 2) < 0) {
  6561. ctx.textAlign = 'center';
  6562. ctx.textBaseline = 'top';
  6563. }
  6564. else if (Math.sin(armAngle * 2) > 0){
  6565. ctx.textAlign = 'right';
  6566. ctx.textBaseline = 'middle';
  6567. }
  6568. else {
  6569. ctx.textAlign = 'left';
  6570. ctx.textBaseline = 'middle';
  6571. }
  6572. ctx.fillStyle = this.colorAxis;
  6573. ctx.fillText(yLabel, text.x, text.y);
  6574. }
  6575. // draw z-label
  6576. var zLabel = this.zLabel;
  6577. if (zLabel.length > 0) {
  6578. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  6579. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  6580. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  6581. zText = (this.zMin + this.zMax) / 2;
  6582. text = this._convert3Dto2D(new Point3d(xText, yText, zText));
  6583. ctx.textAlign = 'right';
  6584. ctx.textBaseline = 'middle';
  6585. ctx.fillStyle = this.colorAxis;
  6586. ctx.fillText(zLabel, text.x - offset, text.y);
  6587. }
  6588. };
  6589. /**
  6590. * Calculate the color based on the given value.
  6591. * @param {Number} H Hue, a value be between 0 and 360
  6592. * @param {Number} S Saturation, a value between 0 and 1
  6593. * @param {Number} V Value, a value between 0 and 1
  6594. */
  6595. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  6596. var R, G, B, C, Hi, X;
  6597. C = V * S;
  6598. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  6599. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  6600. switch (Hi) {
  6601. case 0: R = C; G = X; B = 0; break;
  6602. case 1: R = X; G = C; B = 0; break;
  6603. case 2: R = 0; G = C; B = X; break;
  6604. case 3: R = 0; G = X; B = C; break;
  6605. case 4: R = X; G = 0; B = C; break;
  6606. case 5: R = C; G = 0; B = X; break;
  6607. default: R = 0; G = 0; B = 0; break;
  6608. }
  6609. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  6610. };
  6611. /**
  6612. * Draw all datapoints as a grid
  6613. * This function can be used when the style is 'grid'
  6614. */
  6615. Graph3d.prototype._redrawDataGrid = function() {
  6616. var canvas = this.frame.canvas,
  6617. ctx = canvas.getContext('2d'),
  6618. point, right, top, cross,
  6619. i,
  6620. topSideVisible, fillStyle, strokeStyle, lineWidth,
  6621. h, s, v, zAvg;
  6622. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  6623. return; // TODO: throw exception?
  6624. // calculate the translations and screen position of all points
  6625. for (i = 0; i < this.dataPoints.length; i++) {
  6626. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  6627. var screen = this._convertTranslationToScreen(trans);
  6628. this.dataPoints[i].trans = trans;
  6629. this.dataPoints[i].screen = screen;
  6630. // calculate the translation of the point at the bottom (needed for sorting)
  6631. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  6632. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  6633. }
  6634. // sort the points on depth of their (x,y) position (not on z)
  6635. var sortDepth = function (a, b) {
  6636. return b.dist - a.dist;
  6637. };
  6638. this.dataPoints.sort(sortDepth);
  6639. if (this.style === Graph3d.STYLE.SURFACE) {
  6640. for (i = 0; i < this.dataPoints.length; i++) {
  6641. point = this.dataPoints[i];
  6642. right = this.dataPoints[i].pointRight;
  6643. top = this.dataPoints[i].pointTop;
  6644. cross = this.dataPoints[i].pointCross;
  6645. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  6646. if (this.showGrayBottom || this.showShadow) {
  6647. // calculate the cross product of the two vectors from center
  6648. // to left and right, in order to know whether we are looking at the
  6649. // bottom or at the top side. We can also use the cross product
  6650. // for calculating light intensity
  6651. var aDiff = Point3d.subtract(cross.trans, point.trans);
  6652. var bDiff = Point3d.subtract(top.trans, right.trans);
  6653. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  6654. var len = crossproduct.length();
  6655. // FIXME: there is a bug with determining the surface side (shadow or colored)
  6656. topSideVisible = (crossproduct.z > 0);
  6657. }
  6658. else {
  6659. topSideVisible = true;
  6660. }
  6661. if (topSideVisible) {
  6662. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  6663. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  6664. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  6665. s = 1; // saturation
  6666. if (this.showShadow) {
  6667. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  6668. fillStyle = this._hsv2rgb(h, s, v);
  6669. strokeStyle = fillStyle;
  6670. }
  6671. else {
  6672. v = 1;
  6673. fillStyle = this._hsv2rgb(h, s, v);
  6674. strokeStyle = this.colorAxis;
  6675. }
  6676. }
  6677. else {
  6678. fillStyle = 'gray';
  6679. strokeStyle = this.colorAxis;
  6680. }
  6681. lineWidth = 0.5;
  6682. ctx.lineWidth = lineWidth;
  6683. ctx.fillStyle = fillStyle;
  6684. ctx.strokeStyle = strokeStyle;
  6685. ctx.beginPath();
  6686. ctx.moveTo(point.screen.x, point.screen.y);
  6687. ctx.lineTo(right.screen.x, right.screen.y);
  6688. ctx.lineTo(cross.screen.x, cross.screen.y);
  6689. ctx.lineTo(top.screen.x, top.screen.y);
  6690. ctx.closePath();
  6691. ctx.fill();
  6692. ctx.stroke();
  6693. }
  6694. }
  6695. }
  6696. else { // grid style
  6697. for (i = 0; i < this.dataPoints.length; i++) {
  6698. point = this.dataPoints[i];
  6699. right = this.dataPoints[i].pointRight;
  6700. top = this.dataPoints[i].pointTop;
  6701. if (point !== undefined) {
  6702. if (this.showPerspective) {
  6703. lineWidth = 2 / -point.trans.z;
  6704. }
  6705. else {
  6706. lineWidth = 2 * -(this.eye.z / this.camera.getArmLength());
  6707. }
  6708. }
  6709. if (point !== undefined && right !== undefined) {
  6710. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  6711. zAvg = (point.point.z + right.point.z) / 2;
  6712. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  6713. ctx.lineWidth = lineWidth;
  6714. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  6715. ctx.beginPath();
  6716. ctx.moveTo(point.screen.x, point.screen.y);
  6717. ctx.lineTo(right.screen.x, right.screen.y);
  6718. ctx.stroke();
  6719. }
  6720. if (point !== undefined && top !== undefined) {
  6721. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  6722. zAvg = (point.point.z + top.point.z) / 2;
  6723. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  6724. ctx.lineWidth = lineWidth;
  6725. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  6726. ctx.beginPath();
  6727. ctx.moveTo(point.screen.x, point.screen.y);
  6728. ctx.lineTo(top.screen.x, top.screen.y);
  6729. ctx.stroke();
  6730. }
  6731. }
  6732. }
  6733. };
  6734. /**
  6735. * Draw all datapoints as dots.
  6736. * This function can be used when the style is 'dot' or 'dot-line'
  6737. */
  6738. Graph3d.prototype._redrawDataDot = function() {
  6739. var canvas = this.frame.canvas;
  6740. var ctx = canvas.getContext('2d');
  6741. var i;
  6742. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  6743. return; // TODO: throw exception?
  6744. // calculate the translations of all points
  6745. for (i = 0; i < this.dataPoints.length; i++) {
  6746. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  6747. var screen = this._convertTranslationToScreen(trans);
  6748. this.dataPoints[i].trans = trans;
  6749. this.dataPoints[i].screen = screen;
  6750. // calculate the distance from the point at the bottom to the camera
  6751. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  6752. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  6753. }
  6754. // order the translated points by depth
  6755. var sortDepth = function (a, b) {
  6756. return b.dist - a.dist;
  6757. };
  6758. this.dataPoints.sort(sortDepth);
  6759. // draw the datapoints as colored circles
  6760. var dotSize = this.frame.clientWidth * 0.02; // px
  6761. for (i = 0; i < this.dataPoints.length; i++) {
  6762. var point = this.dataPoints[i];
  6763. if (this.style === Graph3d.STYLE.DOTLINE) {
  6764. // draw a vertical line from the bottom to the graph value
  6765. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  6766. var from = this._convert3Dto2D(point.bottom);
  6767. ctx.lineWidth = 1;
  6768. ctx.strokeStyle = this.colorGrid;
  6769. ctx.beginPath();
  6770. ctx.moveTo(from.x, from.y);
  6771. ctx.lineTo(point.screen.x, point.screen.y);
  6772. ctx.stroke();
  6773. }
  6774. // calculate radius for the circle
  6775. var size;
  6776. if (this.style === Graph3d.STYLE.DOTSIZE) {
  6777. size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  6778. }
  6779. else {
  6780. size = dotSize;
  6781. }
  6782. var radius;
  6783. if (this.showPerspective) {
  6784. radius = size / -point.trans.z;
  6785. }
  6786. else {
  6787. radius = size * -(this.eye.z / this.camera.getArmLength());
  6788. }
  6789. if (radius < 0) {
  6790. radius = 0;
  6791. }
  6792. var hue, color, borderColor;
  6793. if (this.style === Graph3d.STYLE.DOTCOLOR ) {
  6794. // calculate the color based on the value
  6795. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  6796. color = this._hsv2rgb(hue, 1, 1);
  6797. borderColor = this._hsv2rgb(hue, 1, 0.8);
  6798. }
  6799. else if (this.style === Graph3d.STYLE.DOTSIZE) {
  6800. color = this.colorDot;
  6801. borderColor = this.colorDotBorder;
  6802. }
  6803. else {
  6804. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  6805. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  6806. color = this._hsv2rgb(hue, 1, 1);
  6807. borderColor = this._hsv2rgb(hue, 1, 0.8);
  6808. }
  6809. // draw the circle
  6810. ctx.lineWidth = 1.0;
  6811. ctx.strokeStyle = borderColor;
  6812. ctx.fillStyle = color;
  6813. ctx.beginPath();
  6814. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  6815. ctx.fill();
  6816. ctx.stroke();
  6817. }
  6818. };
  6819. /**
  6820. * Draw all datapoints as bars.
  6821. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  6822. */
  6823. Graph3d.prototype._redrawDataBar = function() {
  6824. var canvas = this.frame.canvas;
  6825. var ctx = canvas.getContext('2d');
  6826. var i, j, surface, corners;
  6827. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  6828. return; // TODO: throw exception?
  6829. // calculate the translations of all points
  6830. for (i = 0; i < this.dataPoints.length; i++) {
  6831. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  6832. var screen = this._convertTranslationToScreen(trans);
  6833. this.dataPoints[i].trans = trans;
  6834. this.dataPoints[i].screen = screen;
  6835. // calculate the distance from the point at the bottom to the camera
  6836. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  6837. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  6838. }
  6839. // order the translated points by depth
  6840. var sortDepth = function (a, b) {
  6841. return b.dist - a.dist;
  6842. };
  6843. this.dataPoints.sort(sortDepth);
  6844. // draw the datapoints as bars
  6845. var xWidth = this.xBarWidth / 2;
  6846. var yWidth = this.yBarWidth / 2;
  6847. for (i = 0; i < this.dataPoints.length; i++) {
  6848. var point = this.dataPoints[i];
  6849. // determine color
  6850. var hue, color, borderColor;
  6851. if (this.style === Graph3d.STYLE.BARCOLOR ) {
  6852. // calculate the color based on the value
  6853. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  6854. color = this._hsv2rgb(hue, 1, 1);
  6855. borderColor = this._hsv2rgb(hue, 1, 0.8);
  6856. }
  6857. else if (this.style === Graph3d.STYLE.BARSIZE) {
  6858. color = this.colorDot;
  6859. borderColor = this.colorDotBorder;
  6860. }
  6861. else {
  6862. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  6863. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  6864. color = this._hsv2rgb(hue, 1, 1);
  6865. borderColor = this._hsv2rgb(hue, 1, 0.8);
  6866. }
  6867. // calculate size for the bar
  6868. if (this.style === Graph3d.STYLE.BARSIZE) {
  6869. xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  6870. yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  6871. }
  6872. // calculate all corner points
  6873. var me = this;
  6874. var point3d = point.point;
  6875. var top = [
  6876. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  6877. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  6878. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  6879. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  6880. ];
  6881. var bottom = [
  6882. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)},
  6883. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)},
  6884. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
  6885. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
  6886. ];
  6887. // calculate screen location of the points
  6888. top.forEach(function (obj) {
  6889. obj.screen = me._convert3Dto2D(obj.point);
  6890. });
  6891. bottom.forEach(function (obj) {
  6892. obj.screen = me._convert3Dto2D(obj.point);
  6893. });
  6894. // create five sides, calculate both corner points and center points
  6895. var surfaces = [
  6896. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  6897. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  6898. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  6899. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  6900. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  6901. ];
  6902. point.surfaces = surfaces;
  6903. // calculate the distance of each of the surface centers to the camera
  6904. for (j = 0; j < surfaces.length; j++) {
  6905. surface = surfaces[j];
  6906. var transCenter = this._convertPointToTranslation(surface.center);
  6907. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  6908. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  6909. // but the current solution is fast/simple and works in 99.9% of all cases
  6910. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  6911. }
  6912. // order the surfaces by their (translated) depth
  6913. surfaces.sort(function (a, b) {
  6914. var diff = b.dist - a.dist;
  6915. if (diff) return diff;
  6916. // if equal depth, sort the top surface last
  6917. if (a.corners === top) return 1;
  6918. if (b.corners === top) return -1;
  6919. // both are equal
  6920. return 0;
  6921. });
  6922. // draw the ordered surfaces
  6923. ctx.lineWidth = 1;
  6924. ctx.strokeStyle = borderColor;
  6925. ctx.fillStyle = color;
  6926. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  6927. for (j = 2; j < surfaces.length; j++) {
  6928. surface = surfaces[j];
  6929. corners = surface.corners;
  6930. ctx.beginPath();
  6931. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  6932. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  6933. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  6934. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  6935. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  6936. ctx.fill();
  6937. ctx.stroke();
  6938. }
  6939. }
  6940. };
  6941. /**
  6942. * Draw a line through all datapoints.
  6943. * This function can be used when the style is 'line'
  6944. */
  6945. Graph3d.prototype._redrawDataLine = function() {
  6946. var canvas = this.frame.canvas,
  6947. ctx = canvas.getContext('2d'),
  6948. point, i;
  6949. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  6950. return; // TODO: throw exception?
  6951. // calculate the translations of all points
  6952. for (i = 0; i < this.dataPoints.length; i++) {
  6953. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  6954. var screen = this._convertTranslationToScreen(trans);
  6955. this.dataPoints[i].trans = trans;
  6956. this.dataPoints[i].screen = screen;
  6957. }
  6958. // start the line
  6959. if (this.dataPoints.length > 0) {
  6960. point = this.dataPoints[0];
  6961. ctx.lineWidth = 1; // TODO: make customizable
  6962. ctx.strokeStyle = 'blue'; // TODO: make customizable
  6963. ctx.beginPath();
  6964. ctx.moveTo(point.screen.x, point.screen.y);
  6965. }
  6966. // draw the datapoints as colored circles
  6967. for (i = 1; i < this.dataPoints.length; i++) {
  6968. point = this.dataPoints[i];
  6969. ctx.lineTo(point.screen.x, point.screen.y);
  6970. }
  6971. // finish the line
  6972. if (this.dataPoints.length > 0) {
  6973. ctx.stroke();
  6974. }
  6975. };
  6976. /**
  6977. * Start a moving operation inside the provided parent element
  6978. * @param {Event} event The event that occurred (required for
  6979. * retrieving the mouse position)
  6980. */
  6981. Graph3d.prototype._onMouseDown = function(event) {
  6982. event = event || window.event;
  6983. // check if mouse is still down (may be up when focus is lost for example
  6984. // in an iframe)
  6985. if (this.leftButtonDown) {
  6986. this._onMouseUp(event);
  6987. }
  6988. // only react on left mouse button down
  6989. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  6990. if (!this.leftButtonDown && !this.touchDown) return;
  6991. // get mouse position (different code for IE and all other browsers)
  6992. this.startMouseX = getMouseX(event);
  6993. this.startMouseY = getMouseY(event);
  6994. this.startStart = new Date(this.start);
  6995. this.startEnd = new Date(this.end);
  6996. this.startArmRotation = this.camera.getArmRotation();
  6997. this.frame.style.cursor = 'move';
  6998. // add event listeners to handle moving the contents
  6999. // we store the function onmousemove and onmouseup in the graph, so we can
  7000. // remove the eventlisteners lateron in the function mouseUp()
  7001. var me = this;
  7002. this.onmousemove = function (event) {me._onMouseMove(event);};
  7003. this.onmouseup = function (event) {me._onMouseUp(event);};
  7004. util.addEventListener(document, 'mousemove', me.onmousemove);
  7005. util.addEventListener(document, 'mouseup', me.onmouseup);
  7006. util.preventDefault(event);
  7007. };
  7008. /**
  7009. * Perform moving operating.
  7010. * This function activated from within the funcion Graph.mouseDown().
  7011. * @param {Event} event Well, eehh, the event
  7012. */
  7013. Graph3d.prototype._onMouseMove = function (event) {
  7014. event = event || window.event;
  7015. // calculate change in mouse position
  7016. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  7017. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  7018. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  7019. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  7020. var snapAngle = 4; // degrees
  7021. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  7022. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  7023. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  7024. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  7025. horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
  7026. }
  7027. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  7028. horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
  7029. }
  7030. // snap vertically to nice angles
  7031. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  7032. verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
  7033. }
  7034. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  7035. verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
  7036. }
  7037. this.camera.setArmRotation(horizontalNew, verticalNew);
  7038. this.redraw();
  7039. // fire a cameraPositionChange event
  7040. var parameters = this.getCameraPosition();
  7041. this.emit('cameraPositionChange', parameters);
  7042. util.preventDefault(event);
  7043. };
  7044. /**
  7045. * Stop moving operating.
  7046. * This function activated from within the funcion Graph.mouseDown().
  7047. * @param {event} event The event
  7048. */
  7049. Graph3d.prototype._onMouseUp = function (event) {
  7050. this.frame.style.cursor = 'auto';
  7051. this.leftButtonDown = false;
  7052. // remove event listeners here
  7053. util.removeEventListener(document, 'mousemove', this.onmousemove);
  7054. util.removeEventListener(document, 'mouseup', this.onmouseup);
  7055. util.preventDefault(event);
  7056. };
  7057. /**
  7058. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  7059. * @param {Event} event A mouse move event
  7060. */
  7061. Graph3d.prototype._onTooltip = function (event) {
  7062. var delay = 300; // ms
  7063. var mouseX = getMouseX(event) - util.getAbsoluteLeft(this.frame);
  7064. var mouseY = getMouseY(event) - util.getAbsoluteTop(this.frame);
  7065. if (!this.showTooltip) {
  7066. return;
  7067. }
  7068. if (this.tooltipTimeout) {
  7069. clearTimeout(this.tooltipTimeout);
  7070. }
  7071. // (delayed) display of a tooltip only if no mouse button is down
  7072. if (this.leftButtonDown) {
  7073. this._hideTooltip();
  7074. return;
  7075. }
  7076. if (this.tooltip && this.tooltip.dataPoint) {
  7077. // tooltip is currently visible
  7078. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  7079. if (dataPoint !== this.tooltip.dataPoint) {
  7080. // datapoint changed
  7081. if (dataPoint) {
  7082. this._showTooltip(dataPoint);
  7083. }
  7084. else {
  7085. this._hideTooltip();
  7086. }
  7087. }
  7088. }
  7089. else {
  7090. // tooltip is currently not visible
  7091. var me = this;
  7092. this.tooltipTimeout = setTimeout(function () {
  7093. me.tooltipTimeout = null;
  7094. // show a tooltip if we have a data point
  7095. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  7096. if (dataPoint) {
  7097. me._showTooltip(dataPoint);
  7098. }
  7099. }, delay);
  7100. }
  7101. };
  7102. /**
  7103. * Event handler for touchstart event on mobile devices
  7104. */
  7105. Graph3d.prototype._onTouchStart = function(event) {
  7106. this.touchDown = true;
  7107. var me = this;
  7108. this.ontouchmove = function (event) {me._onTouchMove(event);};
  7109. this.ontouchend = function (event) {me._onTouchEnd(event);};
  7110. util.addEventListener(document, 'touchmove', me.ontouchmove);
  7111. util.addEventListener(document, 'touchend', me.ontouchend);
  7112. this._onMouseDown(event);
  7113. };
  7114. /**
  7115. * Event handler for touchmove event on mobile devices
  7116. */
  7117. Graph3d.prototype._onTouchMove = function(event) {
  7118. this._onMouseMove(event);
  7119. };
  7120. /**
  7121. * Event handler for touchend event on mobile devices
  7122. */
  7123. Graph3d.prototype._onTouchEnd = function(event) {
  7124. this.touchDown = false;
  7125. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  7126. util.removeEventListener(document, 'touchend', this.ontouchend);
  7127. this._onMouseUp(event);
  7128. };
  7129. /**
  7130. * Event handler for mouse wheel event, used to zoom the graph
  7131. * Code from http://adomas.org/javascript-mouse-wheel/
  7132. * @param {event} event The event
  7133. */
  7134. Graph3d.prototype._onWheel = function(event) {
  7135. if (!event) /* For IE. */
  7136. event = window.event;
  7137. // retrieve delta
  7138. var delta = 0;
  7139. if (event.wheelDelta) { /* IE/Opera. */
  7140. delta = event.wheelDelta/120;
  7141. } else if (event.detail) { /* Mozilla case. */
  7142. // In Mozilla, sign of delta is different than in IE.
  7143. // Also, delta is multiple of 3.
  7144. delta = -event.detail/3;
  7145. }
  7146. // If delta is nonzero, handle it.
  7147. // Basically, delta is now positive if wheel was scrolled up,
  7148. // and negative, if wheel was scrolled down.
  7149. if (delta) {
  7150. var oldLength = this.camera.getArmLength();
  7151. var newLength = oldLength * (1 - delta / 10);
  7152. this.camera.setArmLength(newLength);
  7153. this.redraw();
  7154. this._hideTooltip();
  7155. }
  7156. // fire a cameraPositionChange event
  7157. var parameters = this.getCameraPosition();
  7158. this.emit('cameraPositionChange', parameters);
  7159. // Prevent default actions caused by mouse wheel.
  7160. // That might be ugly, but we handle scrolls somehow
  7161. // anyway, so don't bother here..
  7162. util.preventDefault(event);
  7163. };
  7164. /**
  7165. * Test whether a point lies inside given 2D triangle
  7166. * @param {Point2d} point
  7167. * @param {Point2d[]} triangle
  7168. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  7169. * @private
  7170. */
  7171. Graph3d.prototype._insideTriangle = function (point, triangle) {
  7172. var a = triangle[0],
  7173. b = triangle[1],
  7174. c = triangle[2];
  7175. function sign (x) {
  7176. return x > 0 ? 1 : x < 0 ? -1 : 0;
  7177. }
  7178. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  7179. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  7180. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  7181. // each of the three signs must be either equal to each other or zero
  7182. return (as == 0 || bs == 0 || as == bs) &&
  7183. (bs == 0 || cs == 0 || bs == cs) &&
  7184. (as == 0 || cs == 0 || as == cs);
  7185. };
  7186. /**
  7187. * Find a data point close to given screen position (x, y)
  7188. * @param {Number} x
  7189. * @param {Number} y
  7190. * @return {Object | null} The closest data point or null if not close to any data point
  7191. * @private
  7192. */
  7193. Graph3d.prototype._dataPointFromXY = function (x, y) {
  7194. var i,
  7195. distMax = 100, // px
  7196. dataPoint = null,
  7197. closestDataPoint = null,
  7198. closestDist = null,
  7199. center = new Point2d(x, y);
  7200. if (this.style === Graph3d.STYLE.BAR ||
  7201. this.style === Graph3d.STYLE.BARCOLOR ||
  7202. this.style === Graph3d.STYLE.BARSIZE) {
  7203. // the data points are ordered from far away to closest
  7204. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  7205. dataPoint = this.dataPoints[i];
  7206. var surfaces = dataPoint.surfaces;
  7207. if (surfaces) {
  7208. for (var s = surfaces.length - 1; s >= 0; s--) {
  7209. // split each surface in two triangles, and see if the center point is inside one of these
  7210. var surface = surfaces[s];
  7211. var corners = surface.corners;
  7212. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  7213. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  7214. if (this._insideTriangle(center, triangle1) ||
  7215. this._insideTriangle(center, triangle2)) {
  7216. // return immediately at the first hit
  7217. return dataPoint;
  7218. }
  7219. }
  7220. }
  7221. }
  7222. }
  7223. else {
  7224. // find the closest data point, using distance to the center of the point on 2d screen
  7225. for (i = 0; i < this.dataPoints.length; i++) {
  7226. dataPoint = this.dataPoints[i];
  7227. var point = dataPoint.screen;
  7228. if (point) {
  7229. var distX = Math.abs(x - point.x);
  7230. var distY = Math.abs(y - point.y);
  7231. var dist = Math.sqrt(distX * distX + distY * distY);
  7232. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  7233. closestDist = dist;
  7234. closestDataPoint = dataPoint;
  7235. }
  7236. }
  7237. }
  7238. }
  7239. return closestDataPoint;
  7240. };
  7241. /**
  7242. * Display a tooltip for given data point
  7243. * @param {Object} dataPoint
  7244. * @private
  7245. */
  7246. Graph3d.prototype._showTooltip = function (dataPoint) {
  7247. var content, line, dot;
  7248. if (!this.tooltip) {
  7249. content = document.createElement('div');
  7250. content.style.position = 'absolute';
  7251. content.style.padding = '10px';
  7252. content.style.border = '1px solid #4d4d4d';
  7253. content.style.color = '#1a1a1a';
  7254. content.style.background = 'rgba(255,255,255,0.7)';
  7255. content.style.borderRadius = '2px';
  7256. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  7257. line = document.createElement('div');
  7258. line.style.position = 'absolute';
  7259. line.style.height = '40px';
  7260. line.style.width = '0';
  7261. line.style.borderLeft = '1px solid #4d4d4d';
  7262. dot = document.createElement('div');
  7263. dot.style.position = 'absolute';
  7264. dot.style.height = '0';
  7265. dot.style.width = '0';
  7266. dot.style.border = '5px solid #4d4d4d';
  7267. dot.style.borderRadius = '5px';
  7268. this.tooltip = {
  7269. dataPoint: null,
  7270. dom: {
  7271. content: content,
  7272. line: line,
  7273. dot: dot
  7274. }
  7275. };
  7276. }
  7277. else {
  7278. content = this.tooltip.dom.content;
  7279. line = this.tooltip.dom.line;
  7280. dot = this.tooltip.dom.dot;
  7281. }
  7282. this._hideTooltip();
  7283. this.tooltip.dataPoint = dataPoint;
  7284. if (typeof this.showTooltip === 'function') {
  7285. content.innerHTML = this.showTooltip(dataPoint.point);
  7286. }
  7287. else {
  7288. content.innerHTML = '<table>' +
  7289. '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' +
  7290. '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' +
  7291. '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' +
  7292. '</table>';
  7293. }
  7294. content.style.left = '0';
  7295. content.style.top = '0';
  7296. this.frame.appendChild(content);
  7297. this.frame.appendChild(line);
  7298. this.frame.appendChild(dot);
  7299. // calculate sizes
  7300. var contentWidth = content.offsetWidth;
  7301. var contentHeight = content.offsetHeight;
  7302. var lineHeight = line.offsetHeight;
  7303. var dotWidth = dot.offsetWidth;
  7304. var dotHeight = dot.offsetHeight;
  7305. var left = dataPoint.screen.x - contentWidth / 2;
  7306. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  7307. line.style.left = dataPoint.screen.x + 'px';
  7308. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  7309. content.style.left = left + 'px';
  7310. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  7311. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  7312. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  7313. };
  7314. /**
  7315. * Hide the tooltip when displayed
  7316. * @private
  7317. */
  7318. Graph3d.prototype._hideTooltip = function () {
  7319. if (this.tooltip) {
  7320. this.tooltip.dataPoint = null;
  7321. for (var prop in this.tooltip.dom) {
  7322. if (this.tooltip.dom.hasOwnProperty(prop)) {
  7323. var elem = this.tooltip.dom[prop];
  7324. if (elem && elem.parentNode) {
  7325. elem.parentNode.removeChild(elem);
  7326. }
  7327. }
  7328. }
  7329. }
  7330. };
  7331. /**--------------------------------------------------------------------------**/
  7332. /**
  7333. * Get the horizontal mouse position from a mouse event
  7334. * @param {Event} event
  7335. * @return {Number} mouse x
  7336. */
  7337. function getMouseX (event) {
  7338. if ('clientX' in event) return event.clientX;
  7339. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  7340. }
  7341. /**
  7342. * Get the vertical mouse position from a mouse event
  7343. * @param {Event} event
  7344. * @return {Number} mouse y
  7345. */
  7346. function getMouseY (event) {
  7347. if ('clientY' in event) return event.clientY;
  7348. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  7349. }
  7350. module.exports = Graph3d;
  7351. /***/ },
  7352. /* 11 */
  7353. /***/ function(module, exports, __webpack_require__) {
  7354. /**
  7355. * Expose `Emitter`.
  7356. */
  7357. module.exports = Emitter;
  7358. /**
  7359. * Initialize a new `Emitter`.
  7360. *
  7361. * @api public
  7362. */
  7363. function Emitter(obj) {
  7364. if (obj) return mixin(obj);
  7365. };
  7366. /**
  7367. * Mixin the emitter properties.
  7368. *
  7369. * @param {Object} obj
  7370. * @return {Object}
  7371. * @api private
  7372. */
  7373. function mixin(obj) {
  7374. for (var key in Emitter.prototype) {
  7375. obj[key] = Emitter.prototype[key];
  7376. }
  7377. return obj;
  7378. }
  7379. /**
  7380. * Listen on the given `event` with `fn`.
  7381. *
  7382. * @param {String} event
  7383. * @param {Function} fn
  7384. * @return {Emitter}
  7385. * @api public
  7386. */
  7387. Emitter.prototype.on =
  7388. Emitter.prototype.addEventListener = function(event, fn){
  7389. this._callbacks = this._callbacks || {};
  7390. (this._callbacks[event] = this._callbacks[event] || [])
  7391. .push(fn);
  7392. return this;
  7393. };
  7394. /**
  7395. * Adds an `event` listener that will be invoked a single
  7396. * time then automatically removed.
  7397. *
  7398. * @param {String} event
  7399. * @param {Function} fn
  7400. * @return {Emitter}
  7401. * @api public
  7402. */
  7403. Emitter.prototype.once = function(event, fn){
  7404. var self = this;
  7405. this._callbacks = this._callbacks || {};
  7406. function on() {
  7407. self.off(event, on);
  7408. fn.apply(this, arguments);
  7409. }
  7410. on.fn = fn;
  7411. this.on(event, on);
  7412. return this;
  7413. };
  7414. /**
  7415. * Remove the given callback for `event` or all
  7416. * registered callbacks.
  7417. *
  7418. * @param {String} event
  7419. * @param {Function} fn
  7420. * @return {Emitter}
  7421. * @api public
  7422. */
  7423. Emitter.prototype.off =
  7424. Emitter.prototype.removeListener =
  7425. Emitter.prototype.removeAllListeners =
  7426. Emitter.prototype.removeEventListener = function(event, fn){
  7427. this._callbacks = this._callbacks || {};
  7428. // all
  7429. if (0 == arguments.length) {
  7430. this._callbacks = {};
  7431. return this;
  7432. }
  7433. // specific event
  7434. var callbacks = this._callbacks[event];
  7435. if (!callbacks) return this;
  7436. // remove all handlers
  7437. if (1 == arguments.length) {
  7438. delete this._callbacks[event];
  7439. return this;
  7440. }
  7441. // remove specific handler
  7442. var cb;
  7443. for (var i = 0; i < callbacks.length; i++) {
  7444. cb = callbacks[i];
  7445. if (cb === fn || cb.fn === fn) {
  7446. callbacks.splice(i, 1);
  7447. break;
  7448. }
  7449. }
  7450. return this;
  7451. };
  7452. /**
  7453. * Emit `event` with the given args.
  7454. *
  7455. * @param {String} event
  7456. * @param {Mixed} ...
  7457. * @return {Emitter}
  7458. */
  7459. Emitter.prototype.emit = function(event){
  7460. this._callbacks = this._callbacks || {};
  7461. var args = [].slice.call(arguments, 1)
  7462. , callbacks = this._callbacks[event];
  7463. if (callbacks) {
  7464. callbacks = callbacks.slice(0);
  7465. for (var i = 0, len = callbacks.length; i < len; ++i) {
  7466. callbacks[i].apply(this, args);
  7467. }
  7468. }
  7469. return this;
  7470. };
  7471. /**
  7472. * Return array of callbacks for `event`.
  7473. *
  7474. * @param {String} event
  7475. * @return {Array}
  7476. * @api public
  7477. */
  7478. Emitter.prototype.listeners = function(event){
  7479. this._callbacks = this._callbacks || {};
  7480. return this._callbacks[event] || [];
  7481. };
  7482. /**
  7483. * Check if this emitter has `event` handlers.
  7484. *
  7485. * @param {String} event
  7486. * @return {Boolean}
  7487. * @api public
  7488. */
  7489. Emitter.prototype.hasListeners = function(event){
  7490. return !! this.listeners(event).length;
  7491. };
  7492. /***/ },
  7493. /* 12 */
  7494. /***/ function(module, exports, __webpack_require__) {
  7495. /**
  7496. * @prototype Point3d
  7497. * @param {Number} [x]
  7498. * @param {Number} [y]
  7499. * @param {Number} [z]
  7500. */
  7501. function Point3d(x, y, z) {
  7502. this.x = x !== undefined ? x : 0;
  7503. this.y = y !== undefined ? y : 0;
  7504. this.z = z !== undefined ? z : 0;
  7505. };
  7506. /**
  7507. * Subtract the two provided points, returns a-b
  7508. * @param {Point3d} a
  7509. * @param {Point3d} b
  7510. * @return {Point3d} a-b
  7511. */
  7512. Point3d.subtract = function(a, b) {
  7513. var sub = new Point3d();
  7514. sub.x = a.x - b.x;
  7515. sub.y = a.y - b.y;
  7516. sub.z = a.z - b.z;
  7517. return sub;
  7518. };
  7519. /**
  7520. * Add the two provided points, returns a+b
  7521. * @param {Point3d} a
  7522. * @param {Point3d} b
  7523. * @return {Point3d} a+b
  7524. */
  7525. Point3d.add = function(a, b) {
  7526. var sum = new Point3d();
  7527. sum.x = a.x + b.x;
  7528. sum.y = a.y + b.y;
  7529. sum.z = a.z + b.z;
  7530. return sum;
  7531. };
  7532. /**
  7533. * Calculate the average of two 3d points
  7534. * @param {Point3d} a
  7535. * @param {Point3d} b
  7536. * @return {Point3d} The average, (a+b)/2
  7537. */
  7538. Point3d.avg = function(a, b) {
  7539. return new Point3d(
  7540. (a.x + b.x) / 2,
  7541. (a.y + b.y) / 2,
  7542. (a.z + b.z) / 2
  7543. );
  7544. };
  7545. /**
  7546. * Calculate the cross product of the two provided points, returns axb
  7547. * Documentation: http://en.wikipedia.org/wiki/Cross_product
  7548. * @param {Point3d} a
  7549. * @param {Point3d} b
  7550. * @return {Point3d} cross product axb
  7551. */
  7552. Point3d.crossProduct = function(a, b) {
  7553. var crossproduct = new Point3d();
  7554. crossproduct.x = a.y * b.z - a.z * b.y;
  7555. crossproduct.y = a.z * b.x - a.x * b.z;
  7556. crossproduct.z = a.x * b.y - a.y * b.x;
  7557. return crossproduct;
  7558. };
  7559. /**
  7560. * Rtrieve the length of the vector (or the distance from this point to the origin
  7561. * @return {Number} length
  7562. */
  7563. Point3d.prototype.length = function() {
  7564. return Math.sqrt(
  7565. this.x * this.x +
  7566. this.y * this.y +
  7567. this.z * this.z
  7568. );
  7569. };
  7570. module.exports = Point3d;
  7571. /***/ },
  7572. /* 13 */
  7573. /***/ function(module, exports, __webpack_require__) {
  7574. /**
  7575. * @prototype Point2d
  7576. * @param {Number} [x]
  7577. * @param {Number} [y]
  7578. */
  7579. function Point2d (x, y) {
  7580. this.x = x !== undefined ? x : 0;
  7581. this.y = y !== undefined ? y : 0;
  7582. }
  7583. module.exports = Point2d;
  7584. /***/ },
  7585. /* 14 */
  7586. /***/ function(module, exports, __webpack_require__) {
  7587. var Point3d = __webpack_require__(12);
  7588. /**
  7589. * @class Camera
  7590. * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
  7591. * The camera is always looking in the direction of the origin of the arm.
  7592. * This way, the camera always rotates around one fixed point, the location
  7593. * of the camera arm.
  7594. *
  7595. * Documentation:
  7596. * http://en.wikipedia.org/wiki/3D_projection
  7597. */
  7598. function Camera() {
  7599. this.armLocation = new Point3d();
  7600. this.armRotation = {};
  7601. this.armRotation.horizontal = 0;
  7602. this.armRotation.vertical = 0;
  7603. this.armLength = 1.7;
  7604. this.cameraLocation = new Point3d();
  7605. this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0);
  7606. this.calculateCameraOrientation();
  7607. }
  7608. /**
  7609. * Set the location (origin) of the arm
  7610. * @param {Number} x Normalized value of x
  7611. * @param {Number} y Normalized value of y
  7612. * @param {Number} z Normalized value of z
  7613. */
  7614. Camera.prototype.setArmLocation = function(x, y, z) {
  7615. this.armLocation.x = x;
  7616. this.armLocation.y = y;
  7617. this.armLocation.z = z;
  7618. this.calculateCameraOrientation();
  7619. };
  7620. /**
  7621. * Set the rotation of the camera arm
  7622. * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
  7623. * Optional, can be left undefined.
  7624. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
  7625. * if vertical=0.5*PI, the graph is shown from the
  7626. * top. Optional, can be left undefined.
  7627. */
  7628. Camera.prototype.setArmRotation = function(horizontal, vertical) {
  7629. if (horizontal !== undefined) {
  7630. this.armRotation.horizontal = horizontal;
  7631. }
  7632. if (vertical !== undefined) {
  7633. this.armRotation.vertical = vertical;
  7634. if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
  7635. if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI;
  7636. }
  7637. if (horizontal !== undefined || vertical !== undefined) {
  7638. this.calculateCameraOrientation();
  7639. }
  7640. };
  7641. /**
  7642. * Retrieve the current arm rotation
  7643. * @return {object} An object with parameters horizontal and vertical
  7644. */
  7645. Camera.prototype.getArmRotation = function() {
  7646. var rot = {};
  7647. rot.horizontal = this.armRotation.horizontal;
  7648. rot.vertical = this.armRotation.vertical;
  7649. return rot;
  7650. };
  7651. /**
  7652. * Set the (normalized) length of the camera arm.
  7653. * @param {Number} length A length between 0.71 and 5.0
  7654. */
  7655. Camera.prototype.setArmLength = function(length) {
  7656. if (length === undefined)
  7657. return;
  7658. this.armLength = length;
  7659. // Radius must be larger than the corner of the graph,
  7660. // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
  7661. // graph
  7662. if (this.armLength < 0.71) this.armLength = 0.71;
  7663. if (this.armLength > 5.0) this.armLength = 5.0;
  7664. this.calculateCameraOrientation();
  7665. };
  7666. /**
  7667. * Retrieve the arm length
  7668. * @return {Number} length
  7669. */
  7670. Camera.prototype.getArmLength = function() {
  7671. return this.armLength;
  7672. };
  7673. /**
  7674. * Retrieve the camera location
  7675. * @return {Point3d} cameraLocation
  7676. */
  7677. Camera.prototype.getCameraLocation = function() {
  7678. return this.cameraLocation;
  7679. };
  7680. /**
  7681. * Retrieve the camera rotation
  7682. * @return {Point3d} cameraRotation
  7683. */
  7684. Camera.prototype.getCameraRotation = function() {
  7685. return this.cameraRotation;
  7686. };
  7687. /**
  7688. * Calculate the location and rotation of the camera based on the
  7689. * position and orientation of the camera arm
  7690. */
  7691. Camera.prototype.calculateCameraOrientation = function() {
  7692. // calculate location of the camera
  7693. this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  7694. this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  7695. this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
  7696. // calculate rotation of the camera
  7697. this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical;
  7698. this.cameraRotation.y = 0;
  7699. this.cameraRotation.z = -this.armRotation.horizontal;
  7700. };
  7701. module.exports = Camera;
  7702. /***/ },
  7703. /* 15 */
  7704. /***/ function(module, exports, __webpack_require__) {
  7705. var DataView = __webpack_require__(9);
  7706. /**
  7707. * @class Filter
  7708. *
  7709. * @param {DataSet} data The google data table
  7710. * @param {Number} column The index of the column to be filtered
  7711. * @param {Graph} graph The graph
  7712. */
  7713. function Filter (data, column, graph) {
  7714. this.data = data;
  7715. this.column = column;
  7716. this.graph = graph; // the parent graph
  7717. this.index = undefined;
  7718. this.value = undefined;
  7719. // read all distinct values and select the first one
  7720. this.values = graph.getDistinctValues(data.get(), this.column);
  7721. // sort both numeric and string values correctly
  7722. this.values.sort(function (a, b) {
  7723. return a > b ? 1 : a < b ? -1 : 0;
  7724. });
  7725. if (this.values.length > 0) {
  7726. this.selectValue(0);
  7727. }
  7728. // create an array with the filtered datapoints. this will be loaded afterwards
  7729. this.dataPoints = [];
  7730. this.loaded = false;
  7731. this.onLoadCallback = undefined;
  7732. if (graph.animationPreload) {
  7733. this.loaded = false;
  7734. this.loadInBackground();
  7735. }
  7736. else {
  7737. this.loaded = true;
  7738. }
  7739. };
  7740. /**
  7741. * Return the label
  7742. * @return {string} label
  7743. */
  7744. Filter.prototype.isLoaded = function() {
  7745. return this.loaded;
  7746. };
  7747. /**
  7748. * Return the loaded progress
  7749. * @return {Number} percentage between 0 and 100
  7750. */
  7751. Filter.prototype.getLoadedProgress = function() {
  7752. var len = this.values.length;
  7753. var i = 0;
  7754. while (this.dataPoints[i]) {
  7755. i++;
  7756. }
  7757. return Math.round(i / len * 100);
  7758. };
  7759. /**
  7760. * Return the label
  7761. * @return {string} label
  7762. */
  7763. Filter.prototype.getLabel = function() {
  7764. return this.graph.filterLabel;
  7765. };
  7766. /**
  7767. * Return the columnIndex of the filter
  7768. * @return {Number} columnIndex
  7769. */
  7770. Filter.prototype.getColumn = function() {
  7771. return this.column;
  7772. };
  7773. /**
  7774. * Return the currently selected value. Returns undefined if there is no selection
  7775. * @return {*} value
  7776. */
  7777. Filter.prototype.getSelectedValue = function() {
  7778. if (this.index === undefined)
  7779. return undefined;
  7780. return this.values[this.index];
  7781. };
  7782. /**
  7783. * Retrieve all values of the filter
  7784. * @return {Array} values
  7785. */
  7786. Filter.prototype.getValues = function() {
  7787. return this.values;
  7788. };
  7789. /**
  7790. * Retrieve one value of the filter
  7791. * @param {Number} index
  7792. * @return {*} value
  7793. */
  7794. Filter.prototype.getValue = function(index) {
  7795. if (index >= this.values.length)
  7796. throw 'Error: index out of range';
  7797. return this.values[index];
  7798. };
  7799. /**
  7800. * Retrieve the (filtered) dataPoints for the currently selected filter index
  7801. * @param {Number} [index] (optional)
  7802. * @return {Array} dataPoints
  7803. */
  7804. Filter.prototype._getDataPoints = function(index) {
  7805. if (index === undefined)
  7806. index = this.index;
  7807. if (index === undefined)
  7808. return [];
  7809. var dataPoints;
  7810. if (this.dataPoints[index]) {
  7811. dataPoints = this.dataPoints[index];
  7812. }
  7813. else {
  7814. var f = {};
  7815. f.column = this.column;
  7816. f.value = this.values[index];
  7817. var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get();
  7818. dataPoints = this.graph._getDataPoints(dataView);
  7819. this.dataPoints[index] = dataPoints;
  7820. }
  7821. return dataPoints;
  7822. };
  7823. /**
  7824. * Set a callback function when the filter is fully loaded.
  7825. */
  7826. Filter.prototype.setOnLoadCallback = function(callback) {
  7827. this.onLoadCallback = callback;
  7828. };
  7829. /**
  7830. * Add a value to the list with available values for this filter
  7831. * No double entries will be created.
  7832. * @param {Number} index
  7833. */
  7834. Filter.prototype.selectValue = function(index) {
  7835. if (index >= this.values.length)
  7836. throw 'Error: index out of range';
  7837. this.index = index;
  7838. this.value = this.values[index];
  7839. };
  7840. /**
  7841. * Load all filtered rows in the background one by one
  7842. * Start this method without providing an index!
  7843. */
  7844. Filter.prototype.loadInBackground = function(index) {
  7845. if (index === undefined)
  7846. index = 0;
  7847. var frame = this.graph.frame;
  7848. if (index < this.values.length) {
  7849. var dataPointsTemp = this._getDataPoints(index);
  7850. //this.graph.redrawInfo(); // TODO: not neat
  7851. // create a progress box
  7852. if (frame.progress === undefined) {
  7853. frame.progress = document.createElement('DIV');
  7854. frame.progress.style.position = 'absolute';
  7855. frame.progress.style.color = 'gray';
  7856. frame.appendChild(frame.progress);
  7857. }
  7858. var progress = this.getLoadedProgress();
  7859. frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
  7860. // TODO: this is no nice solution...
  7861. frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
  7862. frame.progress.style.left = 10 + 'px';
  7863. var me = this;
  7864. setTimeout(function() {me.loadInBackground(index+1);}, 10);
  7865. this.loaded = false;
  7866. }
  7867. else {
  7868. this.loaded = true;
  7869. // remove the progress box
  7870. if (frame.progress !== undefined) {
  7871. frame.removeChild(frame.progress);
  7872. frame.progress = undefined;
  7873. }
  7874. if (this.onLoadCallback)
  7875. this.onLoadCallback();
  7876. }
  7877. };
  7878. module.exports = Filter;
  7879. /***/ },
  7880. /* 16 */
  7881. /***/ function(module, exports, __webpack_require__) {
  7882. var util = __webpack_require__(1);
  7883. /**
  7884. * @constructor Slider
  7885. *
  7886. * An html slider control with start/stop/prev/next buttons
  7887. * @param {Element} container The element where the slider will be created
  7888. * @param {Object} options Available options:
  7889. * {boolean} visible If true (default) the
  7890. * slider is visible.
  7891. */
  7892. function Slider(container, options) {
  7893. if (container === undefined) {
  7894. throw 'Error: No container element defined';
  7895. }
  7896. this.container = container;
  7897. this.visible = (options && options.visible != undefined) ? options.visible : true;
  7898. if (this.visible) {
  7899. this.frame = document.createElement('DIV');
  7900. //this.frame.style.backgroundColor = '#E5E5E5';
  7901. this.frame.style.width = '100%';
  7902. this.frame.style.position = 'relative';
  7903. this.container.appendChild(this.frame);
  7904. this.frame.prev = document.createElement('INPUT');
  7905. this.frame.prev.type = 'BUTTON';
  7906. this.frame.prev.value = 'Prev';
  7907. this.frame.appendChild(this.frame.prev);
  7908. this.frame.play = document.createElement('INPUT');
  7909. this.frame.play.type = 'BUTTON';
  7910. this.frame.play.value = 'Play';
  7911. this.frame.appendChild(this.frame.play);
  7912. this.frame.next = document.createElement('INPUT');
  7913. this.frame.next.type = 'BUTTON';
  7914. this.frame.next.value = 'Next';
  7915. this.frame.appendChild(this.frame.next);
  7916. this.frame.bar = document.createElement('INPUT');
  7917. this.frame.bar.type = 'BUTTON';
  7918. this.frame.bar.style.position = 'absolute';
  7919. this.frame.bar.style.border = '1px solid red';
  7920. this.frame.bar.style.width = '100px';
  7921. this.frame.bar.style.height = '6px';
  7922. this.frame.bar.style.borderRadius = '2px';
  7923. this.frame.bar.style.MozBorderRadius = '2px';
  7924. this.frame.bar.style.border = '1px solid #7F7F7F';
  7925. this.frame.bar.style.backgroundColor = '#E5E5E5';
  7926. this.frame.appendChild(this.frame.bar);
  7927. this.frame.slide = document.createElement('INPUT');
  7928. this.frame.slide.type = 'BUTTON';
  7929. this.frame.slide.style.margin = '0px';
  7930. this.frame.slide.value = ' ';
  7931. this.frame.slide.style.position = 'relative';
  7932. this.frame.slide.style.left = '-100px';
  7933. this.frame.appendChild(this.frame.slide);
  7934. // create events
  7935. var me = this;
  7936. this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);};
  7937. this.frame.prev.onclick = function (event) {me.prev(event);};
  7938. this.frame.play.onclick = function (event) {me.togglePlay(event);};
  7939. this.frame.next.onclick = function (event) {me.next(event);};
  7940. }
  7941. this.onChangeCallback = undefined;
  7942. this.values = [];
  7943. this.index = undefined;
  7944. this.playTimeout = undefined;
  7945. this.playInterval = 1000; // milliseconds
  7946. this.playLoop = true;
  7947. }
  7948. /**
  7949. * Select the previous index
  7950. */
  7951. Slider.prototype.prev = function() {
  7952. var index = this.getIndex();
  7953. if (index > 0) {
  7954. index--;
  7955. this.setIndex(index);
  7956. }
  7957. };
  7958. /**
  7959. * Select the next index
  7960. */
  7961. Slider.prototype.next = function() {
  7962. var index = this.getIndex();
  7963. if (index < this.values.length - 1) {
  7964. index++;
  7965. this.setIndex(index);
  7966. }
  7967. };
  7968. /**
  7969. * Select the next index
  7970. */
  7971. Slider.prototype.playNext = function() {
  7972. var start = new Date();
  7973. var index = this.getIndex();
  7974. if (index < this.values.length - 1) {
  7975. index++;
  7976. this.setIndex(index);
  7977. }
  7978. else if (this.playLoop) {
  7979. // jump to the start
  7980. index = 0;
  7981. this.setIndex(index);
  7982. }
  7983. var end = new Date();
  7984. var diff = (end - start);
  7985. // calculate how much time it to to set the index and to execute the callback
  7986. // function.
  7987. var interval = Math.max(this.playInterval - diff, 0);
  7988. // document.title = diff // TODO: cleanup
  7989. var me = this;
  7990. this.playTimeout = setTimeout(function() {me.playNext();}, interval);
  7991. };
  7992. /**
  7993. * Toggle start or stop playing
  7994. */
  7995. Slider.prototype.togglePlay = function() {
  7996. if (this.playTimeout === undefined) {
  7997. this.play();
  7998. } else {
  7999. this.stop();
  8000. }
  8001. };
  8002. /**
  8003. * Start playing
  8004. */
  8005. Slider.prototype.play = function() {
  8006. // Test whether already playing
  8007. if (this.playTimeout) return;
  8008. this.playNext();
  8009. if (this.frame) {
  8010. this.frame.play.value = 'Stop';
  8011. }
  8012. };
  8013. /**
  8014. * Stop playing
  8015. */
  8016. Slider.prototype.stop = function() {
  8017. clearInterval(this.playTimeout);
  8018. this.playTimeout = undefined;
  8019. if (this.frame) {
  8020. this.frame.play.value = 'Play';
  8021. }
  8022. };
  8023. /**
  8024. * Set a callback function which will be triggered when the value of the
  8025. * slider bar has changed.
  8026. */
  8027. Slider.prototype.setOnChangeCallback = function(callback) {
  8028. this.onChangeCallback = callback;
  8029. };
  8030. /**
  8031. * Set the interval for playing the list
  8032. * @param {Number} interval The interval in milliseconds
  8033. */
  8034. Slider.prototype.setPlayInterval = function(interval) {
  8035. this.playInterval = interval;
  8036. };
  8037. /**
  8038. * Retrieve the current play interval
  8039. * @return {Number} interval The interval in milliseconds
  8040. */
  8041. Slider.prototype.getPlayInterval = function(interval) {
  8042. return this.playInterval;
  8043. };
  8044. /**
  8045. * Set looping on or off
  8046. * @pararm {boolean} doLoop If true, the slider will jump to the start when
  8047. * the end is passed, and will jump to the end
  8048. * when the start is passed.
  8049. */
  8050. Slider.prototype.setPlayLoop = function(doLoop) {
  8051. this.playLoop = doLoop;
  8052. };
  8053. /**
  8054. * Execute the onchange callback function
  8055. */
  8056. Slider.prototype.onChange = function() {
  8057. if (this.onChangeCallback !== undefined) {
  8058. this.onChangeCallback();
  8059. }
  8060. };
  8061. /**
  8062. * redraw the slider on the correct place
  8063. */
  8064. Slider.prototype.redraw = function() {
  8065. if (this.frame) {
  8066. // resize the bar
  8067. this.frame.bar.style.top = (this.frame.clientHeight/2 -
  8068. this.frame.bar.offsetHeight/2) + 'px';
  8069. this.frame.bar.style.width = (this.frame.clientWidth -
  8070. this.frame.prev.clientWidth -
  8071. this.frame.play.clientWidth -
  8072. this.frame.next.clientWidth - 30) + 'px';
  8073. // position the slider button
  8074. var left = this.indexToLeft(this.index);
  8075. this.frame.slide.style.left = (left) + 'px';
  8076. }
  8077. };
  8078. /**
  8079. * Set the list with values for the slider
  8080. * @param {Array} values A javascript array with values (any type)
  8081. */
  8082. Slider.prototype.setValues = function(values) {
  8083. this.values = values;
  8084. if (this.values.length > 0)
  8085. this.setIndex(0);
  8086. else
  8087. this.index = undefined;
  8088. };
  8089. /**
  8090. * Select a value by its index
  8091. * @param {Number} index
  8092. */
  8093. Slider.prototype.setIndex = function(index) {
  8094. if (index < this.values.length) {
  8095. this.index = index;
  8096. this.redraw();
  8097. this.onChange();
  8098. }
  8099. else {
  8100. throw 'Error: index out of range';
  8101. }
  8102. };
  8103. /**
  8104. * retrieve the index of the currently selected vaue
  8105. * @return {Number} index
  8106. */
  8107. Slider.prototype.getIndex = function() {
  8108. return this.index;
  8109. };
  8110. /**
  8111. * retrieve the currently selected value
  8112. * @return {*} value
  8113. */
  8114. Slider.prototype.get = function() {
  8115. return this.values[this.index];
  8116. };
  8117. Slider.prototype._onMouseDown = function(event) {
  8118. // only react on left mouse button down
  8119. var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  8120. if (!leftButtonDown) return;
  8121. this.startClientX = event.clientX;
  8122. this.startSlideX = parseFloat(this.frame.slide.style.left);
  8123. this.frame.style.cursor = 'move';
  8124. // add event listeners to handle moving the contents
  8125. // we store the function onmousemove and onmouseup in the graph, so we can
  8126. // remove the eventlisteners lateron in the function mouseUp()
  8127. var me = this;
  8128. this.onmousemove = function (event) {me._onMouseMove(event);};
  8129. this.onmouseup = function (event) {me._onMouseUp(event);};
  8130. util.addEventListener(document, 'mousemove', this.onmousemove);
  8131. util.addEventListener(document, 'mouseup', this.onmouseup);
  8132. util.preventDefault(event);
  8133. };
  8134. Slider.prototype.leftToIndex = function (left) {
  8135. var width = parseFloat(this.frame.bar.style.width) -
  8136. this.frame.slide.clientWidth - 10;
  8137. var x = left - 3;
  8138. var index = Math.round(x / width * (this.values.length-1));
  8139. if (index < 0) index = 0;
  8140. if (index > this.values.length-1) index = this.values.length-1;
  8141. return index;
  8142. };
  8143. Slider.prototype.indexToLeft = function (index) {
  8144. var width = parseFloat(this.frame.bar.style.width) -
  8145. this.frame.slide.clientWidth - 10;
  8146. var x = index / (this.values.length-1) * width;
  8147. var left = x + 3;
  8148. return left;
  8149. };
  8150. Slider.prototype._onMouseMove = function (event) {
  8151. var diff = event.clientX - this.startClientX;
  8152. var x = this.startSlideX + diff;
  8153. var index = this.leftToIndex(x);
  8154. this.setIndex(index);
  8155. util.preventDefault();
  8156. };
  8157. Slider.prototype._onMouseUp = function (event) {
  8158. this.frame.style.cursor = 'auto';
  8159. // remove event listeners
  8160. util.removeEventListener(document, 'mousemove', this.onmousemove);
  8161. util.removeEventListener(document, 'mouseup', this.onmouseup);
  8162. util.preventDefault();
  8163. };
  8164. module.exports = Slider;
  8165. /***/ },
  8166. /* 17 */
  8167. /***/ function(module, exports, __webpack_require__) {
  8168. /**
  8169. * @prototype StepNumber
  8170. * The class StepNumber is an iterator for Numbers. You provide a start and end
  8171. * value, and a best step size. StepNumber itself rounds to fixed values and
  8172. * a finds the step that best fits the provided step.
  8173. *
  8174. * If prettyStep is true, the step size is chosen as close as possible to the
  8175. * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
  8176. *
  8177. * Example usage:
  8178. * var step = new StepNumber(0, 10, 2.5, true);
  8179. * step.start();
  8180. * while (!step.end()) {
  8181. * alert(step.getCurrent());
  8182. * step.next();
  8183. * }
  8184. *
  8185. * Version: 1.0
  8186. *
  8187. * @param {Number} start The start value
  8188. * @param {Number} end The end value
  8189. * @param {Number} step Optional. Step size. Must be a positive value.
  8190. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  8191. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  8192. */
  8193. function StepNumber(start, end, step, prettyStep) {
  8194. // set default values
  8195. this._start = 0;
  8196. this._end = 0;
  8197. this._step = 1;
  8198. this.prettyStep = true;
  8199. this.precision = 5;
  8200. this._current = 0;
  8201. this.setRange(start, end, step, prettyStep);
  8202. };
  8203. /**
  8204. * Set a new range: start, end and step.
  8205. *
  8206. * @param {Number} start The start value
  8207. * @param {Number} end The end value
  8208. * @param {Number} step Optional. Step size. Must be a positive value.
  8209. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  8210. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  8211. */
  8212. StepNumber.prototype.setRange = function(start, end, step, prettyStep) {
  8213. this._start = start ? start : 0;
  8214. this._end = end ? end : 0;
  8215. this.setStep(step, prettyStep);
  8216. };
  8217. /**
  8218. * Set a new step size
  8219. * @param {Number} step New step size. Must be a positive value
  8220. * @param {boolean} prettyStep Optional. If true, the provided step is rounded
  8221. * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  8222. */
  8223. StepNumber.prototype.setStep = function(step, prettyStep) {
  8224. if (step === undefined || step <= 0)
  8225. return;
  8226. if (prettyStep !== undefined)
  8227. this.prettyStep = prettyStep;
  8228. if (this.prettyStep === true)
  8229. this._step = StepNumber.calculatePrettyStep(step);
  8230. else
  8231. this._step = step;
  8232. };
  8233. /**
  8234. * Calculate a nice step size, closest to the desired step size.
  8235. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
  8236. * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
  8237. * @param {Number} step Desired step size
  8238. * @return {Number} Nice step size
  8239. */
  8240. StepNumber.calculatePrettyStep = function (step) {
  8241. var log10 = function (x) {return Math.log(x) / Math.LN10;};
  8242. // try three steps (multiple of 1, 2, or 5
  8243. var step1 = Math.pow(10, Math.round(log10(step))),
  8244. step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
  8245. step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
  8246. // choose the best step (closest to minimum step)
  8247. var prettyStep = step1;
  8248. if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
  8249. if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
  8250. // for safety
  8251. if (prettyStep <= 0) {
  8252. prettyStep = 1;
  8253. }
  8254. return prettyStep;
  8255. };
  8256. /**
  8257. * returns the current value of the step
  8258. * @return {Number} current value
  8259. */
  8260. StepNumber.prototype.getCurrent = function () {
  8261. return parseFloat(this._current.toPrecision(this.precision));
  8262. };
  8263. /**
  8264. * returns the current step size
  8265. * @return {Number} current step size
  8266. */
  8267. StepNumber.prototype.getStep = function () {
  8268. return this._step;
  8269. };
  8270. /**
  8271. * Set the current value to the largest value smaller than start, which
  8272. * is a multiple of the step size
  8273. */
  8274. StepNumber.prototype.start = function() {
  8275. this._current = this._start - this._start % this._step;
  8276. };
  8277. /**
  8278. * Do a step, add the step size to the current value
  8279. */
  8280. StepNumber.prototype.next = function () {
  8281. this._current += this._step;
  8282. };
  8283. /**
  8284. * Returns true whether the end is reached
  8285. * @return {boolean} True if the current value has passed the end value.
  8286. */
  8287. StepNumber.prototype.end = function () {
  8288. return (this._current > this._end);
  8289. };
  8290. module.exports = StepNumber;
  8291. /***/ },
  8292. /* 18 */
  8293. /***/ function(module, exports, __webpack_require__) {
  8294. var Emitter = __webpack_require__(11);
  8295. var Hammer = __webpack_require__(19);
  8296. var util = __webpack_require__(1);
  8297. var DataSet = __webpack_require__(7);
  8298. var DataView = __webpack_require__(9);
  8299. var Range = __webpack_require__(21);
  8300. var Core = __webpack_require__(25);
  8301. var TimeAxis = __webpack_require__(37);
  8302. var CurrentTime = __webpack_require__(39);
  8303. var CustomTime = __webpack_require__(41);
  8304. var ItemSet = __webpack_require__(26);
  8305. /**
  8306. * Create a timeline visualization
  8307. * @param {HTMLElement} container
  8308. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  8309. * @param {vis.DataSet | Array | google.visualization.DataTable} [groups]
  8310. * @param {Object} [options] See Timeline.setOptions for the available options.
  8311. * @constructor
  8312. * @extends Core
  8313. */
  8314. function Timeline (container, items, groups, options) {
  8315. if (!(this instanceof Timeline)) {
  8316. throw new SyntaxError('Constructor must be called with the new operator');
  8317. }
  8318. // if the third element is options, the forth is groups (optionally);
  8319. if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) {
  8320. var forthArgument = options;
  8321. options = groups;
  8322. groups = forthArgument;
  8323. }
  8324. var me = this;
  8325. this.defaultOptions = {
  8326. start: null,
  8327. end: null,
  8328. autoResize: true,
  8329. orientation: 'bottom',
  8330. width: null,
  8331. height: null,
  8332. maxHeight: null,
  8333. minHeight: null
  8334. };
  8335. this.options = util.deepExtend({}, this.defaultOptions);
  8336. // Create the DOM, props, and emitter
  8337. this._create(container);
  8338. // all components listed here will be repainted automatically
  8339. this.components = [];
  8340. this.body = {
  8341. dom: this.dom,
  8342. domProps: this.props,
  8343. emitter: {
  8344. on: this.on.bind(this),
  8345. off: this.off.bind(this),
  8346. emit: this.emit.bind(this)
  8347. },
  8348. hiddenDates: [],
  8349. util: {
  8350. snap: null, // will be specified after TimeAxis is created
  8351. toScreen: me._toScreen.bind(me),
  8352. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  8353. toTime: me._toTime.bind(me),
  8354. toGlobalTime : me._toGlobalTime.bind(me)
  8355. }
  8356. };
  8357. // range
  8358. this.range = new Range(this.body);
  8359. this.components.push(this.range);
  8360. this.body.range = this.range;
  8361. // time axis
  8362. this.timeAxis = new TimeAxis(this.body);
  8363. this.components.push(this.timeAxis);
  8364. this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  8365. // current time bar
  8366. this.currentTime = new CurrentTime(this.body);
  8367. this.components.push(this.currentTime);
  8368. // custom time bar
  8369. // Note: time bar will be attached in this.setOptions when selected
  8370. this.customTime = new CustomTime(this.body);
  8371. this.components.push(this.customTime);
  8372. // item set
  8373. this.itemSet = new ItemSet(this.body);
  8374. this.components.push(this.itemSet);
  8375. this.itemsData = null; // DataSet
  8376. this.groupsData = null; // DataSet
  8377. // apply options
  8378. if (options) {
  8379. this.setOptions(options);
  8380. }
  8381. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  8382. if (groups) {
  8383. this.setGroups(groups);
  8384. }
  8385. // create itemset
  8386. if (items) {
  8387. this.setItems(items);
  8388. }
  8389. else {
  8390. this.redraw();
  8391. }
  8392. }
  8393. // Extend the functionality from Core
  8394. Timeline.prototype = new Core();
  8395. /**
  8396. * Set items
  8397. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  8398. */
  8399. Timeline.prototype.setItems = function(items) {
  8400. var initialLoad = (this.itemsData == null);
  8401. // convert to type DataSet when needed
  8402. var newDataSet;
  8403. if (!items) {
  8404. newDataSet = null;
  8405. }
  8406. else if (items instanceof DataSet || items instanceof DataView) {
  8407. newDataSet = items;
  8408. }
  8409. else {
  8410. // turn an array into a dataset
  8411. newDataSet = new DataSet(items, {
  8412. type: {
  8413. start: 'Date',
  8414. end: 'Date'
  8415. }
  8416. });
  8417. }
  8418. // set items
  8419. this.itemsData = newDataSet;
  8420. this.itemSet && this.itemSet.setItems(newDataSet);
  8421. if (initialLoad) {
  8422. if (this.options.start != undefined || this.options.end != undefined) {
  8423. if (this.options.start == undefined || this.options.end == undefined) {
  8424. var dataRange = this._getDataRange();
  8425. }
  8426. var start = this.options.start != undefined ? this.options.start : dataRange.start;
  8427. var end = this.options.end != undefined ? this.options.end : dataRange.end;
  8428. this.setWindow(start, end, {animate: false});
  8429. }
  8430. else {
  8431. this.fit({animate: false});
  8432. }
  8433. }
  8434. };
  8435. /**
  8436. * Set groups
  8437. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  8438. */
  8439. Timeline.prototype.setGroups = function(groups) {
  8440. // convert to type DataSet when needed
  8441. var newDataSet;
  8442. if (!groups) {
  8443. newDataSet = null;
  8444. }
  8445. else if (groups instanceof DataSet || groups instanceof DataView) {
  8446. newDataSet = groups;
  8447. }
  8448. else {
  8449. // turn an array into a dataset
  8450. newDataSet = new DataSet(groups);
  8451. }
  8452. this.groupsData = newDataSet;
  8453. this.itemSet.setGroups(newDataSet);
  8454. };
  8455. /**
  8456. * Set selected items by their id. Replaces the current selection
  8457. * Unknown id's are silently ignored.
  8458. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  8459. * selected. If ids is an empty array, all items will be
  8460. * unselected.
  8461. * @param {Object} [options] Available options:
  8462. * `focus: boolean`
  8463. * If true, focus will be set to the selected item(s)
  8464. * `animate: boolean | number`
  8465. * If true (default), the range is animated
  8466. * smoothly to the new window.
  8467. * If a number, the number is taken as duration
  8468. * for the animation. Default duration is 500 ms.
  8469. * Only applicable when option focus is true.
  8470. */
  8471. Timeline.prototype.setSelection = function(ids, options) {
  8472. this.itemSet && this.itemSet.setSelection(ids);
  8473. if (options && options.focus) {
  8474. this.focus(ids, options);
  8475. }
  8476. };
  8477. /**
  8478. * Get the selected items by their id
  8479. * @return {Array} ids The ids of the selected items
  8480. */
  8481. Timeline.prototype.getSelection = function() {
  8482. return this.itemSet && this.itemSet.getSelection() || [];
  8483. };
  8484. /**
  8485. * Adjust the visible window such that the selected item (or multiple items)
  8486. * are centered on screen.
  8487. * @param {String | String[]} id An item id or array with item ids
  8488. * @param {Object} [options] Available options:
  8489. * `animate: boolean | number`
  8490. * If true (default), the range is animated
  8491. * smoothly to the new window.
  8492. * If a number, the number is taken as duration
  8493. * for the animation. Default duration is 500 ms.
  8494. * Only applicable when option focus is true
  8495. */
  8496. Timeline.prototype.focus = function(id, options) {
  8497. if (!this.itemsData || id == undefined) return;
  8498. var ids = Array.isArray(id) ? id : [id];
  8499. // get the specified item(s)
  8500. var itemsData = this.itemsData.getDataSet().get(ids, {
  8501. type: {
  8502. start: 'Date',
  8503. end: 'Date'
  8504. }
  8505. });
  8506. // calculate minimum start and maximum end of specified items
  8507. var start = null;
  8508. var end = null;
  8509. itemsData.forEach(function (itemData) {
  8510. var s = itemData.start.valueOf();
  8511. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  8512. if (start === null || s < start) {
  8513. start = s;
  8514. }
  8515. if (end === null || e > end) {
  8516. end = e;
  8517. }
  8518. });
  8519. if (start !== null && end !== null) {
  8520. // calculate the new middle and interval for the window
  8521. var middle = (start + end) / 2;
  8522. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  8523. var animate = (options && options.animate !== undefined) ? options.animate : true;
  8524. this.range.setRange(middle - interval / 2, middle + interval / 2, animate);
  8525. }
  8526. };
  8527. /**
  8528. * Get the data range of the item set.
  8529. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  8530. * When no minimum is found, min==null
  8531. * When no maximum is found, max==null
  8532. */
  8533. Timeline.prototype.getItemRange = function() {
  8534. // calculate min from start filed
  8535. var dataset = this.itemsData.getDataSet(),
  8536. min = null,
  8537. max = null;
  8538. if (dataset) {
  8539. // calculate the minimum value of the field 'start'
  8540. var minItem = dataset.min('start');
  8541. min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
  8542. // Note: we convert first to Date and then to number because else
  8543. // a conversion from ISODate to Number will fail
  8544. // calculate maximum value of fields 'start' and 'end'
  8545. var maxStartItem = dataset.max('start');
  8546. if (maxStartItem) {
  8547. max = util.convert(maxStartItem.start, 'Date').valueOf();
  8548. }
  8549. var maxEndItem = dataset.max('end');
  8550. if (maxEndItem) {
  8551. if (max == null) {
  8552. max = util.convert(maxEndItem.end, 'Date').valueOf();
  8553. }
  8554. else {
  8555. max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
  8556. }
  8557. }
  8558. }
  8559. return {
  8560. min: (min != null) ? new Date(min) : null,
  8561. max: (max != null) ? new Date(max) : null
  8562. };
  8563. };
  8564. module.exports = Timeline;
  8565. /***/ },
  8566. /* 19 */
  8567. /***/ function(module, exports, __webpack_require__) {
  8568. // Only load hammer.js when in a browser environment
  8569. // (loading hammer.js in a node.js environment gives errors)
  8570. if (typeof window !== 'undefined') {
  8571. module.exports = window['Hammer'] || __webpack_require__(20);
  8572. }
  8573. else {
  8574. module.exports = function () {
  8575. throw Error('hammer.js is only available in a browser, not in node.js.');
  8576. }
  8577. }
  8578. /***/ },
  8579. /* 20 */
  8580. /***/ function(module, exports, __webpack_require__) {
  8581. var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20
  8582. * http://eightmedia.github.io/hammer.js
  8583. *
  8584. * Copyright (c) 2014 Jorik Tangelder <j.tangelder@gmail.com>;
  8585. * Licensed under the MIT license */
  8586. (function(window, undefined) {
  8587. 'use strict';
  8588. /**
  8589. * @main
  8590. * @module hammer
  8591. *
  8592. * @class Hammer
  8593. * @static
  8594. */
  8595. /**
  8596. * Hammer, use this to create instances
  8597. * ````
  8598. * var hammertime = new Hammer(myElement);
  8599. * ````
  8600. *
  8601. * @method Hammer
  8602. * @param {HTMLElement} element
  8603. * @param {Object} [options={}]
  8604. * @return {Hammer.Instance}
  8605. */
  8606. var Hammer = function Hammer(element, options) {
  8607. return new Hammer.Instance(element, options || {});
  8608. };
  8609. /**
  8610. * version, as defined in package.json
  8611. * the value will be set at each build
  8612. * @property VERSION
  8613. * @final
  8614. * @type {String}
  8615. */
  8616. Hammer.VERSION = '1.1.3';
  8617. /**
  8618. * default settings.
  8619. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled
  8620. * by setting it's name (like `swipe`) to false.
  8621. * You can set the defaults for all instances by changing this object before creating an instance.
  8622. * @example
  8623. * ````
  8624. * Hammer.defaults.drag = false;
  8625. * Hammer.defaults.behavior.touchAction = 'pan-y';
  8626. * delete Hammer.defaults.behavior.userSelect;
  8627. * ````
  8628. * @property defaults
  8629. * @type {Object}
  8630. */
  8631. Hammer.defaults = {
  8632. /**
  8633. * this setting object adds styles and attributes to the element to prevent the browser from doing
  8634. * its native behavior. The css properties are auto prefixed for the browsers when needed.
  8635. * @property defaults.behavior
  8636. * @type {Object}
  8637. */
  8638. behavior: {
  8639. /**
  8640. * Disables text selection to improve the dragging gesture. When the value is `none` it also sets
  8641. * `onselectstart=false` for IE on the element. Mainly for desktop browsers.
  8642. * @property defaults.behavior.userSelect
  8643. * @type {String}
  8644. * @default 'none'
  8645. */
  8646. userSelect: 'none',
  8647. /**
  8648. * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming).
  8649. * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event.
  8650. * @property defaults.behavior.touchAction
  8651. * @type {String}
  8652. * @default: 'pan-y'
  8653. */
  8654. touchAction: 'pan-y',
  8655. /**
  8656. * Disables the default callout shown when you touch and hold a touch target.
  8657. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  8658. * a callout containing information about the link. This property allows you to disable that callout.
  8659. * @property defaults.behavior.touchCallout
  8660. * @type {String}
  8661. * @default 'none'
  8662. */
  8663. touchCallout: 'none',
  8664. /**
  8665. * Specifies whether zooming is enabled. Used by IE10>
  8666. * @property defaults.behavior.contentZooming
  8667. * @type {String}
  8668. * @default 'none'
  8669. */
  8670. contentZooming: 'none',
  8671. /**
  8672. * Specifies that an entire element should be draggable instead of its contents.
  8673. * Mainly for desktop browsers.
  8674. * @property defaults.behavior.userDrag
  8675. * @type {String}
  8676. * @default 'none'
  8677. */
  8678. userDrag: 'none',
  8679. /**
  8680. * Overrides the highlight color shown when the user taps a link or a JavaScript
  8681. * clickable element in Safari on iPhone. This property obeys the alpha value, if specified.
  8682. *
  8683. * If you don't specify an alpha value, Safari on iPhone applies a default alpha value
  8684. * to the color. To disable tap highlighting, set the alpha value to 0 (invisible).
  8685. * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped.
  8686. * @property defaults.behavior.tapHighlightColor
  8687. * @type {String}
  8688. * @default 'rgba(0,0,0,0)'
  8689. */
  8690. tapHighlightColor: 'rgba(0,0,0,0)'
  8691. }
  8692. };
  8693. /**
  8694. * hammer document where the base events are added at
  8695. * @property DOCUMENT
  8696. * @type {HTMLElement}
  8697. * @default window.document
  8698. */
  8699. Hammer.DOCUMENT = document;
  8700. /**
  8701. * detect support for pointer events
  8702. * @property HAS_POINTEREVENTS
  8703. * @type {Boolean}
  8704. */
  8705. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  8706. /**
  8707. * detect support for touch events
  8708. * @property HAS_TOUCHEVENTS
  8709. * @type {Boolean}
  8710. */
  8711. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  8712. /**
  8713. * detect mobile browsers
  8714. * @property IS_MOBILE
  8715. * @type {Boolean}
  8716. */
  8717. Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent);
  8718. /**
  8719. * detect if we want to support mouseevents at all
  8720. * @property NO_MOUSEEVENTS
  8721. * @type {Boolean}
  8722. */
  8723. Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS;
  8724. /**
  8725. * interval in which Hammer recalculates current velocity/direction/angle in ms
  8726. * @property CALCULATE_INTERVAL
  8727. * @type {Number}
  8728. * @default 25
  8729. */
  8730. Hammer.CALCULATE_INTERVAL = 25;
  8731. /**
  8732. * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup`
  8733. * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`)
  8734. * @property EVENT_TYPES
  8735. * @private
  8736. * @writeOnce
  8737. * @type {Object}
  8738. */
  8739. var EVENT_TYPES = {};
  8740. /**
  8741. * direction strings, for safe comparisons
  8742. * @property DIRECTION_DOWN|LEFT|UP|RIGHT
  8743. * @final
  8744. * @type {String}
  8745. * @default 'down' 'left' 'up' 'right'
  8746. */
  8747. var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down';
  8748. var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left';
  8749. var DIRECTION_UP = Hammer.DIRECTION_UP = 'up';
  8750. var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right';
  8751. /**
  8752. * pointertype strings, for safe comparisons
  8753. * @property POINTER_MOUSE|TOUCH|PEN
  8754. * @final
  8755. * @type {String}
  8756. * @default 'mouse' 'touch' 'pen'
  8757. */
  8758. var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse';
  8759. var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch';
  8760. var POINTER_PEN = Hammer.POINTER_PEN = 'pen';
  8761. /**
  8762. * eventtypes
  8763. * @property EVENT_START|MOVE|END|RELEASE|TOUCH
  8764. * @final
  8765. * @type {String}
  8766. * @default 'start' 'change' 'move' 'end' 'release' 'touch'
  8767. */
  8768. var EVENT_START = Hammer.EVENT_START = 'start';
  8769. var EVENT_MOVE = Hammer.EVENT_MOVE = 'move';
  8770. var EVENT_END = Hammer.EVENT_END = 'end';
  8771. var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release';
  8772. var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch';
  8773. /**
  8774. * if the window events are set...
  8775. * @property READY
  8776. * @writeOnce
  8777. * @type {Boolean}
  8778. * @default false
  8779. */
  8780. Hammer.READY = false;
  8781. /**
  8782. * plugins namespace
  8783. * @property plugins
  8784. * @type {Object}
  8785. */
  8786. Hammer.plugins = Hammer.plugins || {};
  8787. /**
  8788. * gestures namespace
  8789. * see `/gestures` for the definitions
  8790. * @property gestures
  8791. * @type {Object}
  8792. */
  8793. Hammer.gestures = Hammer.gestures || {};
  8794. /**
  8795. * setup events to detect gestures on the document
  8796. * this function is called when creating an new instance
  8797. * @private
  8798. */
  8799. function setup() {
  8800. if(Hammer.READY) {
  8801. return;
  8802. }
  8803. // find what eventtypes we add listeners to
  8804. Event.determineEventTypes();
  8805. // Register all gestures inside Hammer.gestures
  8806. Utils.each(Hammer.gestures, function(gesture) {
  8807. Detection.register(gesture);
  8808. });
  8809. // Add touch events on the document
  8810. Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect);
  8811. Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect);
  8812. // Hammer is ready...!
  8813. Hammer.READY = true;
  8814. }
  8815. /**
  8816. * @module hammer
  8817. *
  8818. * @class Utils
  8819. * @static
  8820. */
  8821. var Utils = Hammer.utils = {
  8822. /**
  8823. * extend method, could also be used for cloning when `dest` is an empty object.
  8824. * changes the dest object
  8825. * @method extend
  8826. * @param {Object} dest
  8827. * @param {Object} src
  8828. * @param {Boolean} [merge=false] do a merge
  8829. * @return {Object} dest
  8830. */
  8831. extend: function extend(dest, src, merge) {
  8832. for(var key in src) {
  8833. if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) {
  8834. continue;
  8835. }
  8836. dest[key] = src[key];
  8837. }
  8838. return dest;
  8839. },
  8840. /**
  8841. * simple addEventListener wrapper
  8842. * @method on
  8843. * @param {HTMLElement} element
  8844. * @param {String} type
  8845. * @param {Function} handler
  8846. */
  8847. on: function on(element, type, handler) {
  8848. element.addEventListener(type, handler, false);
  8849. },
  8850. /**
  8851. * simple removeEventListener wrapper
  8852. * @method off
  8853. * @param {HTMLElement} element
  8854. * @param {String} type
  8855. * @param {Function} handler
  8856. */
  8857. off: function off(element, type, handler) {
  8858. element.removeEventListener(type, handler, false);
  8859. },
  8860. /**
  8861. * forEach over arrays and objects
  8862. * @method each
  8863. * @param {Object|Array} obj
  8864. * @param {Function} iterator
  8865. * @param {any} iterator.item
  8866. * @param {Number} iterator.index
  8867. * @param {Object|Array} iterator.obj the source object
  8868. * @param {Object} context value to use as `this` in the iterator
  8869. */
  8870. each: function each(obj, iterator, context) {
  8871. var i, len;
  8872. // native forEach on arrays
  8873. if('forEach' in obj) {
  8874. obj.forEach(iterator, context);
  8875. // arrays
  8876. } else if(obj.length !== undefined) {
  8877. for(i = 0, len = obj.length; i < len; i++) {
  8878. if(iterator.call(context, obj[i], i, obj) === false) {
  8879. return;
  8880. }
  8881. }
  8882. // objects
  8883. } else {
  8884. for(i in obj) {
  8885. if(obj.hasOwnProperty(i) &&
  8886. iterator.call(context, obj[i], i, obj) === false) {
  8887. return;
  8888. }
  8889. }
  8890. }
  8891. },
  8892. /**
  8893. * find if a string contains the string using indexOf
  8894. * @method inStr
  8895. * @param {String} src
  8896. * @param {String} find
  8897. * @return {Boolean} found
  8898. */
  8899. inStr: function inStr(src, find) {
  8900. return src.indexOf(find) > -1;
  8901. },
  8902. /**
  8903. * find if a array contains the object using indexOf or a simple polyfill
  8904. * @method inArray
  8905. * @param {String} src
  8906. * @param {String} find
  8907. * @return {Boolean|Number} false when not found, or the index
  8908. */
  8909. inArray: function inArray(src, find) {
  8910. if(src.indexOf) {
  8911. var index = src.indexOf(find);
  8912. return (index === -1) ? false : index;
  8913. } else {
  8914. for(var i = 0, len = src.length; i < len; i++) {
  8915. if(src[i] === find) {
  8916. return i;
  8917. }
  8918. }
  8919. return false;
  8920. }
  8921. },
  8922. /**
  8923. * convert an array-like object (`arguments`, `touchlist`) to an array
  8924. * @method toArray
  8925. * @param {Object} obj
  8926. * @return {Array}
  8927. */
  8928. toArray: function toArray(obj) {
  8929. return Array.prototype.slice.call(obj, 0);
  8930. },
  8931. /**
  8932. * find if a node is in the given parent
  8933. * @method hasParent
  8934. * @param {HTMLElement} node
  8935. * @param {HTMLElement} parent
  8936. * @return {Boolean} found
  8937. */
  8938. hasParent: function hasParent(node, parent) {
  8939. while(node) {
  8940. if(node == parent) {
  8941. return true;
  8942. }
  8943. node = node.parentNode;
  8944. }
  8945. return false;
  8946. },
  8947. /**
  8948. * get the center of all the touches
  8949. * @method getCenter
  8950. * @param {Array} touches
  8951. * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties
  8952. */
  8953. getCenter: function getCenter(touches) {
  8954. var pageX = [],
  8955. pageY = [],
  8956. clientX = [],
  8957. clientY = [],
  8958. min = Math.min,
  8959. max = Math.max;
  8960. // no need to loop when only one touch
  8961. if(touches.length === 1) {
  8962. return {
  8963. pageX: touches[0].pageX,
  8964. pageY: touches[0].pageY,
  8965. clientX: touches[0].clientX,
  8966. clientY: touches[0].clientY
  8967. };
  8968. }
  8969. Utils.each(touches, function(touch) {
  8970. pageX.push(touch.pageX);
  8971. pageY.push(touch.pageY);
  8972. clientX.push(touch.clientX);
  8973. clientY.push(touch.clientY);
  8974. });
  8975. return {
  8976. pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2,
  8977. pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2,
  8978. clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2,
  8979. clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2
  8980. };
  8981. },
  8982. /**
  8983. * calculate the velocity between two points. unit is in px per ms.
  8984. * @method getVelocity
  8985. * @param {Number} deltaTime
  8986. * @param {Number} deltaX
  8987. * @param {Number} deltaY
  8988. * @return {Object} velocity `x` and `y`
  8989. */
  8990. getVelocity: function getVelocity(deltaTime, deltaX, deltaY) {
  8991. return {
  8992. x: Math.abs(deltaX / deltaTime) || 0,
  8993. y: Math.abs(deltaY / deltaTime) || 0
  8994. };
  8995. },
  8996. /**
  8997. * calculate the angle between two coordinates
  8998. * @method getAngle
  8999. * @param {Touch} touch1
  9000. * @param {Touch} touch2
  9001. * @return {Number} angle
  9002. */
  9003. getAngle: function getAngle(touch1, touch2) {
  9004. var x = touch2.clientX - touch1.clientX,
  9005. y = touch2.clientY - touch1.clientY;
  9006. return Math.atan2(y, x) * 180 / Math.PI;
  9007. },
  9008. /**
  9009. * do a small comparision to get the direction between two touches.
  9010. * @method getDirection
  9011. * @param {Touch} touch1
  9012. * @param {Touch} touch2
  9013. * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN`
  9014. */
  9015. getDirection: function getDirection(touch1, touch2) {
  9016. var x = Math.abs(touch1.clientX - touch2.clientX),
  9017. y = Math.abs(touch1.clientY - touch2.clientY);
  9018. if(x >= y) {
  9019. return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  9020. }
  9021. return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  9022. },
  9023. /**
  9024. * calculate the distance between two touches
  9025. * @method getDistance
  9026. * @param {Touch}touch1
  9027. * @param {Touch} touch2
  9028. * @return {Number} distance
  9029. */
  9030. getDistance: function getDistance(touch1, touch2) {
  9031. var x = touch2.clientX - touch1.clientX,
  9032. y = touch2.clientY - touch1.clientY;
  9033. return Math.sqrt((x * x) + (y * y));
  9034. },
  9035. /**
  9036. * calculate the scale factor between two touchLists
  9037. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  9038. * @method getScale
  9039. * @param {Array} start array of touches
  9040. * @param {Array} end array of touches
  9041. * @return {Number} scale
  9042. */
  9043. getScale: function getScale(start, end) {
  9044. // need two fingers...
  9045. if(start.length >= 2 && end.length >= 2) {
  9046. return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]);
  9047. }
  9048. return 1;
  9049. },
  9050. /**
  9051. * calculate the rotation degrees between two touchLists
  9052. * @method getRotation
  9053. * @param {Array} start array of touches
  9054. * @param {Array} end array of touches
  9055. * @return {Number} rotation
  9056. */
  9057. getRotation: function getRotation(start, end) {
  9058. // need two fingers
  9059. if(start.length >= 2 && end.length >= 2) {
  9060. return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]);
  9061. }
  9062. return 0;
  9063. },
  9064. /**
  9065. * find out if the direction is vertical *
  9066. * @method isVertical
  9067. * @param {String} direction matches `DIRECTION_UP|DOWN`
  9068. * @return {Boolean} is_vertical
  9069. */
  9070. isVertical: function isVertical(direction) {
  9071. return direction == DIRECTION_UP || direction == DIRECTION_DOWN;
  9072. },
  9073. /**
  9074. * set css properties with their prefixes
  9075. * @param {HTMLElement} element
  9076. * @param {String} prop
  9077. * @param {String} value
  9078. * @param {Boolean} [toggle=true]
  9079. * @return {Boolean}
  9080. */
  9081. setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) {
  9082. var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms'];
  9083. prop = Utils.toCamelCase(prop);
  9084. for(var i = 0; i < prefixes.length; i++) {
  9085. var p = prop;
  9086. // prefixes
  9087. if(prefixes[i]) {
  9088. p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1);
  9089. }
  9090. // test the style
  9091. if(p in element.style) {
  9092. element.style[p] = (toggle == null || toggle) && value || '';
  9093. break;
  9094. }
  9095. }
  9096. },
  9097. /**
  9098. * toggle browser default behavior by setting css properties.
  9099. * `userSelect='none'` also sets `element.onselectstart` to false
  9100. * `userDrag='none'` also sets `element.ondragstart` to false
  9101. *
  9102. * @method toggleBehavior
  9103. * @param {HtmlElement} element
  9104. * @param {Object} props
  9105. * @param {Boolean} [toggle=true]
  9106. */
  9107. toggleBehavior: function toggleBehavior(element, props, toggle) {
  9108. if(!props || !element || !element.style) {
  9109. return;
  9110. }
  9111. // set the css properties
  9112. Utils.each(props, function(value, prop) {
  9113. Utils.setPrefixedCss(element, prop, value, toggle);
  9114. });
  9115. var falseFn = toggle && function() {
  9116. return false;
  9117. };
  9118. // also the disable onselectstart
  9119. if(props.userSelect == 'none') {
  9120. element.onselectstart = falseFn;
  9121. }
  9122. // and disable ondragstart
  9123. if(props.userDrag == 'none') {
  9124. element.ondragstart = falseFn;
  9125. }
  9126. },
  9127. /**
  9128. * convert a string with underscores to camelCase
  9129. * so prevent_default becomes preventDefault
  9130. * @param {String} str
  9131. * @return {String} camelCaseStr
  9132. */
  9133. toCamelCase: function toCamelCase(str) {
  9134. return str.replace(/[_-]([a-z])/g, function(s) {
  9135. return s[1].toUpperCase();
  9136. });
  9137. }
  9138. };
  9139. /**
  9140. * @module hammer
  9141. */
  9142. /**
  9143. * @class Event
  9144. * @static
  9145. */
  9146. var Event = Hammer.event = {
  9147. /**
  9148. * when touch events have been fired, this is true
  9149. * this is used to stop mouse events
  9150. * @property prevent_mouseevents
  9151. * @private
  9152. * @type {Boolean}
  9153. */
  9154. preventMouseEvents: false,
  9155. /**
  9156. * if EVENT_START has been fired
  9157. * @property started
  9158. * @private
  9159. * @type {Boolean}
  9160. */
  9161. started: false,
  9162. /**
  9163. * when the mouse is hold down, this is true
  9164. * @property should_detect
  9165. * @private
  9166. * @type {Boolean}
  9167. */
  9168. shouldDetect: false,
  9169. /**
  9170. * simple event binder with a hook and support for multiple types
  9171. * @method on
  9172. * @param {HTMLElement} element
  9173. * @param {String} type
  9174. * @param {Function} handler
  9175. * @param {Function} [hook]
  9176. * @param {Object} hook.type
  9177. */
  9178. on: function on(element, type, handler, hook) {
  9179. var types = type.split(' ');
  9180. Utils.each(types, function(type) {
  9181. Utils.on(element, type, handler);
  9182. hook && hook(type);
  9183. });
  9184. },
  9185. /**
  9186. * simple event unbinder with a hook and support for multiple types
  9187. * @method off
  9188. * @param {HTMLElement} element
  9189. * @param {String} type
  9190. * @param {Function} handler
  9191. * @param {Function} [hook]
  9192. * @param {Object} hook.type
  9193. */
  9194. off: function off(element, type, handler, hook) {
  9195. var types = type.split(' ');
  9196. Utils.each(types, function(type) {
  9197. Utils.off(element, type, handler);
  9198. hook && hook(type);
  9199. });
  9200. },
  9201. /**
  9202. * the core touch event handler.
  9203. * this finds out if we should to detect gestures
  9204. * @method onTouch
  9205. * @param {HTMLElement} element
  9206. * @param {String} eventType matches `EVENT_START|MOVE|END`
  9207. * @param {Function} handler
  9208. * @return onTouchHandler {Function} the core event handler
  9209. */
  9210. onTouch: function onTouch(element, eventType, handler) {
  9211. var self = this;
  9212. var onTouchHandler = function onTouchHandler(ev) {
  9213. var srcType = ev.type.toLowerCase(),
  9214. isPointer = Hammer.HAS_POINTEREVENTS,
  9215. isMouse = Utils.inStr(srcType, 'mouse'),
  9216. triggerType;
  9217. // if we are in a mouseevent, but there has been a touchevent triggered in this session
  9218. // we want to do nothing. simply break out of the event.
  9219. if(isMouse && self.preventMouseEvents) {
  9220. return;
  9221. // mousebutton must be down
  9222. } else if(isMouse && eventType == EVENT_START && ev.button === 0) {
  9223. self.preventMouseEvents = false;
  9224. self.shouldDetect = true;
  9225. } else if(isPointer && eventType == EVENT_START) {
  9226. self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev));
  9227. // just a valid start event, but no mouse
  9228. } else if(!isMouse && eventType == EVENT_START) {
  9229. self.preventMouseEvents = true;
  9230. self.shouldDetect = true;
  9231. }
  9232. // update the pointer event before entering the detection
  9233. if(isPointer && eventType != EVENT_END) {
  9234. PointerEvent.updatePointer(eventType, ev);
  9235. }
  9236. // we are in a touch/down state, so allowed detection of gestures
  9237. if(self.shouldDetect) {
  9238. triggerType = self.doDetect.call(self, ev, eventType, element, handler);
  9239. }
  9240. // ...and we are done with the detection
  9241. // so reset everything to start each detection totally fresh
  9242. if(triggerType == EVENT_END) {
  9243. self.preventMouseEvents = false;
  9244. self.shouldDetect = false;
  9245. PointerEvent.reset();
  9246. // update the pointerevent object after the detection
  9247. }
  9248. if(isPointer && eventType == EVENT_END) {
  9249. PointerEvent.updatePointer(eventType, ev);
  9250. }
  9251. };
  9252. this.on(element, EVENT_TYPES[eventType], onTouchHandler);
  9253. return onTouchHandler;
  9254. },
  9255. /**
  9256. * the core detection method
  9257. * this finds out what hammer-touch-events to trigger
  9258. * @method doDetect
  9259. * @param {Object} ev
  9260. * @param {String} eventType matches `EVENT_START|MOVE|END`
  9261. * @param {HTMLElement} element
  9262. * @param {Function} handler
  9263. * @return {String} triggerType matches `EVENT_START|MOVE|END`
  9264. */
  9265. doDetect: function doDetect(ev, eventType, element, handler) {
  9266. var touchList = this.getTouchList(ev, eventType);
  9267. var touchListLength = touchList.length;
  9268. var triggerType = eventType;
  9269. var triggerChange = touchList.trigger; // used by fakeMultitouch plugin
  9270. var changedLength = touchListLength;
  9271. // at each touchstart-like event we want also want to trigger a TOUCH event...
  9272. if(eventType == EVENT_START) {
  9273. triggerChange = EVENT_TOUCH;
  9274. // ...the same for a touchend-like event
  9275. } else if(eventType == EVENT_END) {
  9276. triggerChange = EVENT_RELEASE;
  9277. // keep track of how many touches have been removed
  9278. changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1);
  9279. }
  9280. // after there are still touches on the screen,
  9281. // we just want to trigger a MOVE event. so change the START or END to a MOVE
  9282. // but only after detection has been started, the first time we actualy want a START
  9283. if(changedLength > 0 && this.started) {
  9284. triggerType = EVENT_MOVE;
  9285. }
  9286. // detection has been started, we keep track of this, see above
  9287. this.started = true;
  9288. // generate some event data, some basic information
  9289. var evData = this.collectEventData(element, triggerType, touchList, ev);
  9290. // trigger the triggerType event before the change (TOUCH, RELEASE) events
  9291. // but the END event should be at last
  9292. if(eventType != EVENT_END) {
  9293. handler.call(Detection, evData);
  9294. }
  9295. // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed
  9296. if(triggerChange) {
  9297. evData.changedLength = changedLength;
  9298. evData.eventType = triggerChange;
  9299. handler.call(Detection, evData);
  9300. evData.eventType = triggerType;
  9301. delete evData.changedLength;
  9302. }
  9303. // trigger the END event
  9304. if(triggerType == EVENT_END) {
  9305. handler.call(Detection, evData);
  9306. // ...and we are done with the detection
  9307. // so reset everything to start each detection totally fresh
  9308. this.started = false;
  9309. }
  9310. return triggerType;
  9311. },
  9312. /**
  9313. * we have different events for each device/browser
  9314. * determine what we need and set them in the EVENT_TYPES constant
  9315. * the `onTouch` method is bind to these properties.
  9316. * @method determineEventTypes
  9317. * @return {Object} events
  9318. */
  9319. determineEventTypes: function determineEventTypes() {
  9320. var types;
  9321. if(Hammer.HAS_POINTEREVENTS) {
  9322. if(window.PointerEvent) {
  9323. types = [
  9324. 'pointerdown',
  9325. 'pointermove',
  9326. 'pointerup pointercancel lostpointercapture'
  9327. ];
  9328. } else {
  9329. types = [
  9330. 'MSPointerDown',
  9331. 'MSPointerMove',
  9332. 'MSPointerUp MSPointerCancel MSLostPointerCapture'
  9333. ];
  9334. }
  9335. } else if(Hammer.NO_MOUSEEVENTS) {
  9336. types = [
  9337. 'touchstart',
  9338. 'touchmove',
  9339. 'touchend touchcancel'
  9340. ];
  9341. } else {
  9342. types = [
  9343. 'touchstart mousedown',
  9344. 'touchmove mousemove',
  9345. 'touchend touchcancel mouseup'
  9346. ];
  9347. }
  9348. EVENT_TYPES[EVENT_START] = types[0];
  9349. EVENT_TYPES[EVENT_MOVE] = types[1];
  9350. EVENT_TYPES[EVENT_END] = types[2];
  9351. return EVENT_TYPES;
  9352. },
  9353. /**
  9354. * create touchList depending on the event
  9355. * @method getTouchList
  9356. * @param {Object} ev
  9357. * @param {String} eventType
  9358. * @return {Array} touches
  9359. */
  9360. getTouchList: function getTouchList(ev, eventType) {
  9361. // get the fake pointerEvent touchlist
  9362. if(Hammer.HAS_POINTEREVENTS) {
  9363. return PointerEvent.getTouchList();
  9364. }
  9365. // get the touchlist
  9366. if(ev.touches) {
  9367. if(eventType == EVENT_MOVE) {
  9368. return ev.touches;
  9369. }
  9370. var identifiers = [];
  9371. var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches));
  9372. var touchList = [];
  9373. Utils.each(concat, function(touch) {
  9374. if(Utils.inArray(identifiers, touch.identifier) === false) {
  9375. touchList.push(touch);
  9376. }
  9377. identifiers.push(touch.identifier);
  9378. });
  9379. return touchList;
  9380. }
  9381. // make fake touchList from mouse position
  9382. ev.identifier = 1;
  9383. return [ev];
  9384. },
  9385. /**
  9386. * collect basic event data
  9387. * @method collectEventData
  9388. * @param {HTMLElement} element
  9389. * @param {String} eventType matches `EVENT_START|MOVE|END`
  9390. * @param {Array} touches
  9391. * @param {Object} ev
  9392. * @return {Object} ev
  9393. */
  9394. collectEventData: function collectEventData(element, eventType, touches, ev) {
  9395. // find out pointerType
  9396. var pointerType = POINTER_TOUCH;
  9397. if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
  9398. pointerType = POINTER_MOUSE;
  9399. } else if(PointerEvent.matchType(POINTER_PEN, ev)) {
  9400. pointerType = POINTER_PEN;
  9401. }
  9402. return {
  9403. center: Utils.getCenter(touches),
  9404. timeStamp: Date.now(),
  9405. target: ev.target,
  9406. touches: touches,
  9407. eventType: eventType,
  9408. pointerType: pointerType,
  9409. srcEvent: ev,
  9410. /**
  9411. * prevent the browser default actions
  9412. * mostly used to disable scrolling of the browser
  9413. */
  9414. preventDefault: function() {
  9415. var srcEvent = this.srcEvent;
  9416. srcEvent.preventManipulation && srcEvent.preventManipulation();
  9417. srcEvent.preventDefault && srcEvent.preventDefault();
  9418. },
  9419. /**
  9420. * stop bubbling the event up to its parents
  9421. */
  9422. stopPropagation: function() {
  9423. this.srcEvent.stopPropagation();
  9424. },
  9425. /**
  9426. * immediately stop gesture detection
  9427. * might be useful after a swipe was detected
  9428. * @return {*}
  9429. */
  9430. stopDetect: function() {
  9431. return Detection.stopDetect();
  9432. }
  9433. };
  9434. }
  9435. };
  9436. /**
  9437. * @module hammer
  9438. *
  9439. * @class PointerEvent
  9440. * @static
  9441. */
  9442. var PointerEvent = Hammer.PointerEvent = {
  9443. /**
  9444. * holds all pointers, by `identifier`
  9445. * @property pointers
  9446. * @type {Object}
  9447. */
  9448. pointers: {},
  9449. /**
  9450. * get the pointers as an array
  9451. * @method getTouchList
  9452. * @return {Array} touchlist
  9453. */
  9454. getTouchList: function getTouchList() {
  9455. var touchlist = [];
  9456. // we can use forEach since pointerEvents only is in IE10
  9457. Utils.each(this.pointers, function(pointer) {
  9458. touchlist.push(pointer);
  9459. });
  9460. return touchlist;
  9461. },
  9462. /**
  9463. * update the position of a pointer
  9464. * @method updatePointer
  9465. * @param {String} eventType matches `EVENT_START|MOVE|END`
  9466. * @param {Object} pointerEvent
  9467. */
  9468. updatePointer: function updatePointer(eventType, pointerEvent) {
  9469. if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) {
  9470. delete this.pointers[pointerEvent.pointerId];
  9471. } else {
  9472. pointerEvent.identifier = pointerEvent.pointerId;
  9473. this.pointers[pointerEvent.pointerId] = pointerEvent;
  9474. }
  9475. },
  9476. /**
  9477. * check if ev matches pointertype
  9478. * @method matchType
  9479. * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN`
  9480. * @param {PointerEvent} ev
  9481. */
  9482. matchType: function matchType(pointerType, ev) {
  9483. if(!ev.pointerType) {
  9484. return false;
  9485. }
  9486. var pt = ev.pointerType,
  9487. types = {};
  9488. types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE));
  9489. types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH));
  9490. types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN));
  9491. return types[pointerType];
  9492. },
  9493. /**
  9494. * reset the stored pointers
  9495. * @method reset
  9496. */
  9497. reset: function resetList() {
  9498. this.pointers = {};
  9499. }
  9500. };
  9501. /**
  9502. * @module hammer
  9503. *
  9504. * @class Detection
  9505. * @static
  9506. */
  9507. var Detection = Hammer.detection = {
  9508. // contains all registred Hammer.gestures in the correct order
  9509. gestures: [],
  9510. // data of the current Hammer.gesture detection session
  9511. current: null,
  9512. // the previous Hammer.gesture session data
  9513. // is a full clone of the previous gesture.current object
  9514. previous: null,
  9515. // when this becomes true, no gestures are fired
  9516. stopped: false,
  9517. /**
  9518. * start Hammer.gesture detection
  9519. * @method startDetect
  9520. * @param {Hammer.Instance} inst
  9521. * @param {Object} eventData
  9522. */
  9523. startDetect: function startDetect(inst, eventData) {
  9524. // already busy with a Hammer.gesture detection on an element
  9525. if(this.current) {
  9526. return;
  9527. }
  9528. this.stopped = false;
  9529. // holds current session
  9530. this.current = {
  9531. inst: inst, // reference to HammerInstance we're working for
  9532. startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc
  9533. lastEvent: false, // last eventData
  9534. lastCalcEvent: false, // last eventData for calculations.
  9535. futureCalcEvent: false, // last eventData for calculations.
  9536. lastCalcData: {}, // last lastCalcData
  9537. name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  9538. };
  9539. this.detect(eventData);
  9540. },
  9541. /**
  9542. * Hammer.gesture detection
  9543. * @method detect
  9544. * @param {Object} eventData
  9545. * @return {any}
  9546. */
  9547. detect: function detect(eventData) {
  9548. if(!this.current || this.stopped) {
  9549. return;
  9550. }
  9551. // extend event data with calculations about scale, distance etc
  9552. eventData = this.extendEventData(eventData);
  9553. // hammer instance and instance options
  9554. var inst = this.current.inst,
  9555. instOptions = inst.options;
  9556. // call Hammer.gesture handlers
  9557. Utils.each(this.gestures, function triggerGesture(gesture) {
  9558. // only when the instance options have enabled this gesture
  9559. if(!this.stopped && inst.enabled && instOptions[gesture.name]) {
  9560. gesture.handler.call(gesture, eventData, inst);
  9561. }
  9562. }, this);
  9563. // store as previous event event
  9564. if(this.current) {
  9565. this.current.lastEvent = eventData;
  9566. }
  9567. if(eventData.eventType == EVENT_END) {
  9568. this.stopDetect();
  9569. }
  9570. return eventData;
  9571. },
  9572. /**
  9573. * clear the Hammer.gesture vars
  9574. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  9575. * to stop other Hammer.gestures from being fired
  9576. * @method stopDetect
  9577. */
  9578. stopDetect: function stopDetect() {
  9579. // clone current data to the store as the previous gesture
  9580. // used for the double tap gesture, since this is an other gesture detect session
  9581. this.previous = Utils.extend({}, this.current);
  9582. // reset the current
  9583. this.current = null;
  9584. this.stopped = true;
  9585. },
  9586. /**
  9587. * calculate velocity, angle and direction
  9588. * @method getVelocityData
  9589. * @param {Object} ev
  9590. * @param {Object} center
  9591. * @param {Number} deltaTime
  9592. * @param {Number} deltaX
  9593. * @param {Number} deltaY
  9594. */
  9595. getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) {
  9596. var cur = this.current,
  9597. recalc = false,
  9598. calcEv = cur.lastCalcEvent,
  9599. calcData = cur.lastCalcData;
  9600. if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) {
  9601. center = calcEv.center;
  9602. deltaTime = ev.timeStamp - calcEv.timeStamp;
  9603. deltaX = ev.center.clientX - calcEv.center.clientX;
  9604. deltaY = ev.center.clientY - calcEv.center.clientY;
  9605. recalc = true;
  9606. }
  9607. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  9608. cur.futureCalcEvent = ev;
  9609. }
  9610. if(!cur.lastCalcEvent || recalc) {
  9611. calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY);
  9612. calcData.angle = Utils.getAngle(center, ev.center);
  9613. calcData.direction = Utils.getDirection(center, ev.center);
  9614. cur.lastCalcEvent = cur.futureCalcEvent || ev;
  9615. cur.futureCalcEvent = ev;
  9616. }
  9617. ev.velocityX = calcData.velocity.x;
  9618. ev.velocityY = calcData.velocity.y;
  9619. ev.interimAngle = calcData.angle;
  9620. ev.interimDirection = calcData.direction;
  9621. },
  9622. /**
  9623. * extend eventData for Hammer.gestures
  9624. * @method extendEventData
  9625. * @param {Object} ev
  9626. * @return {Object} ev
  9627. */
  9628. extendEventData: function extendEventData(ev) {
  9629. var cur = this.current,
  9630. startEv = cur.startEvent,
  9631. lastEv = cur.lastEvent || startEv;
  9632. // update the start touchlist to calculate the scale/rotation
  9633. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  9634. startEv.touches = [];
  9635. Utils.each(ev.touches, function(touch) {
  9636. startEv.touches.push({
  9637. clientX: touch.clientX,
  9638. clientY: touch.clientY
  9639. });
  9640. });
  9641. }
  9642. var deltaTime = ev.timeStamp - startEv.timeStamp,
  9643. deltaX = ev.center.clientX - startEv.center.clientX,
  9644. deltaY = ev.center.clientY - startEv.center.clientY;
  9645. this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY);
  9646. Utils.extend(ev, {
  9647. startEvent: startEv,
  9648. deltaTime: deltaTime,
  9649. deltaX: deltaX,
  9650. deltaY: deltaY,
  9651. distance: Utils.getDistance(startEv.center, ev.center),
  9652. angle: Utils.getAngle(startEv.center, ev.center),
  9653. direction: Utils.getDirection(startEv.center, ev.center),
  9654. scale: Utils.getScale(startEv.touches, ev.touches),
  9655. rotation: Utils.getRotation(startEv.touches, ev.touches)
  9656. });
  9657. return ev;
  9658. },
  9659. /**
  9660. * register new gesture
  9661. * @method register
  9662. * @param {Object} gesture object, see `gestures/` for documentation
  9663. * @return {Array} gestures
  9664. */
  9665. register: function register(gesture) {
  9666. // add an enable gesture options if there is no given
  9667. var options = gesture.defaults || {};
  9668. if(options[gesture.name] === undefined) {
  9669. options[gesture.name] = true;
  9670. }
  9671. // extend Hammer default options with the Hammer.gesture options
  9672. Utils.extend(Hammer.defaults, options, true);
  9673. // set its index
  9674. gesture.index = gesture.index || 1000;
  9675. // add Hammer.gesture to the list
  9676. this.gestures.push(gesture);
  9677. // sort the list by index
  9678. this.gestures.sort(function(a, b) {
  9679. if(a.index < b.index) {
  9680. return -1;
  9681. }
  9682. if(a.index > b.index) {
  9683. return 1;
  9684. }
  9685. return 0;
  9686. });
  9687. return this.gestures;
  9688. }
  9689. };
  9690. /**
  9691. * @module hammer
  9692. */
  9693. /**
  9694. * create new hammer instance
  9695. * all methods should return the instance itself, so it is chainable.
  9696. *
  9697. * @class Instance
  9698. * @constructor
  9699. * @param {HTMLElement} element
  9700. * @param {Object} [options={}] options are merged with `Hammer.defaults`
  9701. * @return {Hammer.Instance}
  9702. */
  9703. Hammer.Instance = function(element, options) {
  9704. var self = this;
  9705. // setup HammerJS window events and register all gestures
  9706. // this also sets up the default options
  9707. setup();
  9708. /**
  9709. * @property element
  9710. * @type {HTMLElement}
  9711. */
  9712. this.element = element;
  9713. /**
  9714. * @property enabled
  9715. * @type {Boolean}
  9716. * @protected
  9717. */
  9718. this.enabled = true;
  9719. /**
  9720. * options, merged with the defaults
  9721. * options with an _ are converted to camelCase
  9722. * @property options
  9723. * @type {Object}
  9724. */
  9725. Utils.each(options, function(value, name) {
  9726. delete options[name];
  9727. options[Utils.toCamelCase(name)] = value;
  9728. });
  9729. this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {});
  9730. // add some css to the element to prevent the browser from doing its native behavoir
  9731. if(this.options.behavior) {
  9732. Utils.toggleBehavior(this.element, this.options.behavior, true);
  9733. }
  9734. /**
  9735. * event start handler on the element to start the detection
  9736. * @property eventStartHandler
  9737. * @type {Object}
  9738. */
  9739. this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) {
  9740. if(self.enabled && ev.eventType == EVENT_START) {
  9741. Detection.startDetect(self, ev);
  9742. } else if(ev.eventType == EVENT_TOUCH) {
  9743. Detection.detect(ev);
  9744. }
  9745. });
  9746. /**
  9747. * keep a list of user event handlers which needs to be removed when calling 'dispose'
  9748. * @property eventHandlers
  9749. * @type {Array}
  9750. */
  9751. this.eventHandlers = [];
  9752. };
  9753. Hammer.Instance.prototype = {
  9754. /**
  9755. * bind events to the instance
  9756. * @method on
  9757. * @chainable
  9758. * @param {String} gestures multiple gestures by splitting with a space
  9759. * @param {Function} handler
  9760. * @param {Object} handler.ev event object
  9761. */
  9762. on: function onEvent(gestures, handler) {
  9763. var self = this;
  9764. Event.on(self.element, gestures, handler, function(type) {
  9765. self.eventHandlers.push({ gesture: type, handler: handler });
  9766. });
  9767. return self;
  9768. },
  9769. /**
  9770. * unbind events to the instance
  9771. * @method off
  9772. * @chainable
  9773. * @param {String} gestures
  9774. * @param {Function} handler
  9775. */
  9776. off: function offEvent(gestures, handler) {
  9777. var self = this;
  9778. Event.off(self.element, gestures, handler, function(type) {
  9779. var index = Utils.inArray({ gesture: type, handler: handler });
  9780. if(index !== false) {
  9781. self.eventHandlers.splice(index, 1);
  9782. }
  9783. });
  9784. return self;
  9785. },
  9786. /**
  9787. * trigger gesture event
  9788. * @method trigger
  9789. * @chainable
  9790. * @param {String} gesture
  9791. * @param {Object} [eventData]
  9792. */
  9793. trigger: function triggerEvent(gesture, eventData) {
  9794. // optional
  9795. if(!eventData) {
  9796. eventData = {};
  9797. }
  9798. // create DOM event
  9799. var event = Hammer.DOCUMENT.createEvent('Event');
  9800. event.initEvent(gesture, true, true);
  9801. event.gesture = eventData;
  9802. // trigger on the target if it is in the instance element,
  9803. // this is for event delegation tricks
  9804. var element = this.element;
  9805. if(Utils.hasParent(eventData.target, element)) {
  9806. element = eventData.target;
  9807. }
  9808. element.dispatchEvent(event);
  9809. return this;
  9810. },
  9811. /**
  9812. * enable of disable hammer.js detection
  9813. * @method enable
  9814. * @chainable
  9815. * @param {Boolean} state
  9816. */
  9817. enable: function enable(state) {
  9818. this.enabled = state;
  9819. return this;
  9820. },
  9821. /**
  9822. * dispose this hammer instance
  9823. * @method dispose
  9824. * @return {Null}
  9825. */
  9826. dispose: function dispose() {
  9827. var i, eh;
  9828. // undo all changes made by stop_browser_behavior
  9829. Utils.toggleBehavior(this.element, this.options.behavior, false);
  9830. // unbind all custom event handlers
  9831. for(i = -1; (eh = this.eventHandlers[++i]);) {
  9832. Utils.off(this.element, eh.gesture, eh.handler);
  9833. }
  9834. this.eventHandlers = [];
  9835. // unbind the start event listener
  9836. Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler);
  9837. return null;
  9838. }
  9839. };
  9840. /**
  9841. * @module gestures
  9842. */
  9843. /**
  9844. * Move with x fingers (default 1) around on the page.
  9845. * Preventing the default browser behavior is a good way to improve feel and working.
  9846. * ````
  9847. * hammertime.on("drag", function(ev) {
  9848. * console.log(ev);
  9849. * ev.gesture.preventDefault();
  9850. * });
  9851. * ````
  9852. *
  9853. * @class Drag
  9854. * @static
  9855. */
  9856. /**
  9857. * @event drag
  9858. * @param {Object} ev
  9859. */
  9860. /**
  9861. * @event dragstart
  9862. * @param {Object} ev
  9863. */
  9864. /**
  9865. * @event dragend
  9866. * @param {Object} ev
  9867. */
  9868. /**
  9869. * @event drapleft
  9870. * @param {Object} ev
  9871. */
  9872. /**
  9873. * @event dragright
  9874. * @param {Object} ev
  9875. */
  9876. /**
  9877. * @event dragup
  9878. * @param {Object} ev
  9879. */
  9880. /**
  9881. * @event dragdown
  9882. * @param {Object} ev
  9883. */
  9884. /**
  9885. * @param {String} name
  9886. */
  9887. (function(name) {
  9888. var triggered = false;
  9889. function dragGesture(ev, inst) {
  9890. var cur = Detection.current;
  9891. // max touches
  9892. if(inst.options.dragMaxTouches > 0 &&
  9893. ev.touches.length > inst.options.dragMaxTouches) {
  9894. return;
  9895. }
  9896. switch(ev.eventType) {
  9897. case EVENT_START:
  9898. triggered = false;
  9899. break;
  9900. case EVENT_MOVE:
  9901. // when the distance we moved is too small we skip this gesture
  9902. // or we can be already in dragging
  9903. if(ev.distance < inst.options.dragMinDistance &&
  9904. cur.name != name) {
  9905. return;
  9906. }
  9907. var startCenter = cur.startEvent.center;
  9908. // we are dragging!
  9909. if(cur.name != name) {
  9910. cur.name = name;
  9911. if(inst.options.dragDistanceCorrection && ev.distance > 0) {
  9912. // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center.
  9913. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0.
  9914. // It might be useful to save the original start point somewhere
  9915. var factor = Math.abs(inst.options.dragMinDistance / ev.distance);
  9916. startCenter.pageX += ev.deltaX * factor;
  9917. startCenter.pageY += ev.deltaY * factor;
  9918. startCenter.clientX += ev.deltaX * factor;
  9919. startCenter.clientY += ev.deltaY * factor;
  9920. // recalculate event data using new start point
  9921. ev = Detection.extendEventData(ev);
  9922. }
  9923. }
  9924. // lock drag to axis?
  9925. if(cur.lastEvent.dragLockToAxis ||
  9926. ( inst.options.dragLockToAxis &&
  9927. inst.options.dragLockMinDistance <= ev.distance
  9928. )) {
  9929. ev.dragLockToAxis = true;
  9930. }
  9931. // keep direction on the axis that the drag gesture started on
  9932. var lastDirection = cur.lastEvent.direction;
  9933. if(ev.dragLockToAxis && lastDirection !== ev.direction) {
  9934. if(Utils.isVertical(lastDirection)) {
  9935. ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  9936. } else {
  9937. ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  9938. }
  9939. }
  9940. // first time, trigger dragstart event
  9941. if(!triggered) {
  9942. inst.trigger(name + 'start', ev);
  9943. triggered = true;
  9944. }
  9945. // trigger events
  9946. inst.trigger(name, ev);
  9947. inst.trigger(name + ev.direction, ev);
  9948. var isVertical = Utils.isVertical(ev.direction);
  9949. // block the browser events
  9950. if((inst.options.dragBlockVertical && isVertical) ||
  9951. (inst.options.dragBlockHorizontal && !isVertical)) {
  9952. ev.preventDefault();
  9953. }
  9954. break;
  9955. case EVENT_RELEASE:
  9956. if(triggered && ev.changedLength <= inst.options.dragMaxTouches) {
  9957. inst.trigger(name + 'end', ev);
  9958. triggered = false;
  9959. }
  9960. break;
  9961. case EVENT_END:
  9962. triggered = false;
  9963. break;
  9964. }
  9965. }
  9966. Hammer.gestures.Drag = {
  9967. name: name,
  9968. index: 50,
  9969. handler: dragGesture,
  9970. defaults: {
  9971. /**
  9972. * minimal movement that have to be made before the drag event gets triggered
  9973. * @property dragMinDistance
  9974. * @type {Number}
  9975. * @default 10
  9976. */
  9977. dragMinDistance: 10,
  9978. /**
  9979. * Set dragDistanceCorrection to true to make the starting point of the drag
  9980. * be calculated from where the drag was triggered, not from where the touch started.
  9981. * Useful to avoid a jerk-starting drag, which can make fine-adjustments
  9982. * through dragging difficult, and be visually unappealing.
  9983. * @property dragDistanceCorrection
  9984. * @type {Boolean}
  9985. * @default true
  9986. */
  9987. dragDistanceCorrection: true,
  9988. /**
  9989. * set 0 for unlimited, but this can conflict with transform
  9990. * @property dragMaxTouches
  9991. * @type {Number}
  9992. * @default 1
  9993. */
  9994. dragMaxTouches: 1,
  9995. /**
  9996. * prevent default browser behavior when dragging occurs
  9997. * be careful with it, it makes the element a blocking element
  9998. * when you are using the drag gesture, it is a good practice to set this true
  9999. * @property dragBlockHorizontal
  10000. * @type {Boolean}
  10001. * @default false
  10002. */
  10003. dragBlockHorizontal: false,
  10004. /**
  10005. * same as `dragBlockHorizontal`, but for vertical movement
  10006. * @property dragBlockVertical
  10007. * @type {Boolean}
  10008. * @default false
  10009. */
  10010. dragBlockVertical: false,
  10011. /**
  10012. * dragLockToAxis keeps the drag gesture on the axis that it started on,
  10013. * It disallows vertical directions if the initial direction was horizontal, and vice versa.
  10014. * @property dragLockToAxis
  10015. * @type {Boolean}
  10016. * @default false
  10017. */
  10018. dragLockToAxis: false,
  10019. /**
  10020. * drag lock only kicks in when distance > dragLockMinDistance
  10021. * This way, locking occurs only when the distance has become large enough to reliably determine the direction
  10022. * @property dragLockMinDistance
  10023. * @type {Number}
  10024. * @default 25
  10025. */
  10026. dragLockMinDistance: 25
  10027. }
  10028. };
  10029. })('drag');
  10030. /**
  10031. * @module gestures
  10032. */
  10033. /**
  10034. * trigger a simple gesture event, so you can do anything in your handler.
  10035. * only usable if you know what your doing...
  10036. *
  10037. * @class Gesture
  10038. * @static
  10039. */
  10040. /**
  10041. * @event gesture
  10042. * @param {Object} ev
  10043. */
  10044. Hammer.gestures.Gesture = {
  10045. name: 'gesture',
  10046. index: 1337,
  10047. handler: function releaseGesture(ev, inst) {
  10048. inst.trigger(this.name, ev);
  10049. }
  10050. };
  10051. /**
  10052. * @module gestures
  10053. */
  10054. /**
  10055. * Touch stays at the same place for x time
  10056. *
  10057. * @class Hold
  10058. * @static
  10059. */
  10060. /**
  10061. * @event hold
  10062. * @param {Object} ev
  10063. */
  10064. /**
  10065. * @param {String} name
  10066. */
  10067. (function(name) {
  10068. var timer;
  10069. function holdGesture(ev, inst) {
  10070. var options = inst.options,
  10071. current = Detection.current;
  10072. switch(ev.eventType) {
  10073. case EVENT_START:
  10074. clearTimeout(timer);
  10075. // set the gesture so we can check in the timeout if it still is
  10076. current.name = name;
  10077. // set timer and if after the timeout it still is hold,
  10078. // we trigger the hold event
  10079. timer = setTimeout(function() {
  10080. if(current && current.name == name) {
  10081. inst.trigger(name, ev);
  10082. }
  10083. }, options.holdTimeout);
  10084. break;
  10085. case EVENT_MOVE:
  10086. if(ev.distance > options.holdThreshold) {
  10087. clearTimeout(timer);
  10088. }
  10089. break;
  10090. case EVENT_RELEASE:
  10091. clearTimeout(timer);
  10092. break;
  10093. }
  10094. }
  10095. Hammer.gestures.Hold = {
  10096. name: name,
  10097. index: 10,
  10098. defaults: {
  10099. /**
  10100. * @property holdTimeout
  10101. * @type {Number}
  10102. * @default 500
  10103. */
  10104. holdTimeout: 500,
  10105. /**
  10106. * movement allowed while holding
  10107. * @property holdThreshold
  10108. * @type {Number}
  10109. * @default 2
  10110. */
  10111. holdThreshold: 2
  10112. },
  10113. handler: holdGesture
  10114. };
  10115. })('hold');
  10116. /**
  10117. * @module gestures
  10118. */
  10119. /**
  10120. * when a touch is being released from the page
  10121. *
  10122. * @class Release
  10123. * @static
  10124. */
  10125. /**
  10126. * @event release
  10127. * @param {Object} ev
  10128. */
  10129. Hammer.gestures.Release = {
  10130. name: 'release',
  10131. index: Infinity,
  10132. handler: function releaseGesture(ev, inst) {
  10133. if(ev.eventType == EVENT_RELEASE) {
  10134. inst.trigger(this.name, ev);
  10135. }
  10136. }
  10137. };
  10138. /**
  10139. * @module gestures
  10140. */
  10141. /**
  10142. * triggers swipe events when the end velocity is above the threshold
  10143. * for best usage, set `preventDefault` (on the drag gesture) to `true`
  10144. * ````
  10145. * hammertime.on("dragleft swipeleft", function(ev) {
  10146. * console.log(ev);
  10147. * ev.gesture.preventDefault();
  10148. * });
  10149. * ````
  10150. *
  10151. * @class Swipe
  10152. * @static
  10153. */
  10154. /**
  10155. * @event swipe
  10156. * @param {Object} ev
  10157. */
  10158. /**
  10159. * @event swipeleft
  10160. * @param {Object} ev
  10161. */
  10162. /**
  10163. * @event swiperight
  10164. * @param {Object} ev
  10165. */
  10166. /**
  10167. * @event swipeup
  10168. * @param {Object} ev
  10169. */
  10170. /**
  10171. * @event swipedown
  10172. * @param {Object} ev
  10173. */
  10174. Hammer.gestures.Swipe = {
  10175. name: 'swipe',
  10176. index: 40,
  10177. defaults: {
  10178. /**
  10179. * @property swipeMinTouches
  10180. * @type {Number}
  10181. * @default 1
  10182. */
  10183. swipeMinTouches: 1,
  10184. /**
  10185. * @property swipeMaxTouches
  10186. * @type {Number}
  10187. * @default 1
  10188. */
  10189. swipeMaxTouches: 1,
  10190. /**
  10191. * horizontal swipe velocity
  10192. * @property swipeVelocityX
  10193. * @type {Number}
  10194. * @default 0.6
  10195. */
  10196. swipeVelocityX: 0.6,
  10197. /**
  10198. * vertical swipe velocity
  10199. * @property swipeVelocityY
  10200. * @type {Number}
  10201. * @default 0.6
  10202. */
  10203. swipeVelocityY: 0.6
  10204. },
  10205. handler: function swipeGesture(ev, inst) {
  10206. if(ev.eventType == EVENT_RELEASE) {
  10207. var touches = ev.touches.length,
  10208. options = inst.options;
  10209. // max touches
  10210. if(touches < options.swipeMinTouches ||
  10211. touches > options.swipeMaxTouches) {
  10212. return;
  10213. }
  10214. // when the distance we moved is too small we skip this gesture
  10215. // or we can be already in dragging
  10216. if(ev.velocityX > options.swipeVelocityX ||
  10217. ev.velocityY > options.swipeVelocityY) {
  10218. // trigger swipe events
  10219. inst.trigger(this.name, ev);
  10220. inst.trigger(this.name + ev.direction, ev);
  10221. }
  10222. }
  10223. }
  10224. };
  10225. /**
  10226. * @module gestures
  10227. */
  10228. /**
  10229. * Single tap and a double tap on a place
  10230. *
  10231. * @class Tap
  10232. * @static
  10233. */
  10234. /**
  10235. * @event tap
  10236. * @param {Object} ev
  10237. */
  10238. /**
  10239. * @event doubletap
  10240. * @param {Object} ev
  10241. */
  10242. /**
  10243. * @param {String} name
  10244. */
  10245. (function(name) {
  10246. var hasMoved = false;
  10247. function tapGesture(ev, inst) {
  10248. var options = inst.options,
  10249. current = Detection.current,
  10250. prev = Detection.previous,
  10251. sincePrev,
  10252. didDoubleTap;
  10253. switch(ev.eventType) {
  10254. case EVENT_START:
  10255. hasMoved = false;
  10256. break;
  10257. case EVENT_MOVE:
  10258. hasMoved = hasMoved || (ev.distance > options.tapMaxDistance);
  10259. break;
  10260. case EVENT_END:
  10261. if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) {
  10262. // previous gesture, for the double tap since these are two different gesture detections
  10263. sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp;
  10264. didDoubleTap = false;
  10265. // check if double tap
  10266. if(prev && prev.name == name &&
  10267. (sincePrev && sincePrev < options.doubleTapInterval) &&
  10268. ev.distance < options.doubleTapDistance) {
  10269. inst.trigger('doubletap', ev);
  10270. didDoubleTap = true;
  10271. }
  10272. // do a single tap
  10273. if(!didDoubleTap || options.tapAlways) {
  10274. current.name = name;
  10275. inst.trigger(current.name, ev);
  10276. }
  10277. }
  10278. break;
  10279. }
  10280. }
  10281. Hammer.gestures.Tap = {
  10282. name: name,
  10283. index: 100,
  10284. handler: tapGesture,
  10285. defaults: {
  10286. /**
  10287. * max time of a tap, this is for the slow tappers
  10288. * @property tapMaxTime
  10289. * @type {Number}
  10290. * @default 250
  10291. */
  10292. tapMaxTime: 250,
  10293. /**
  10294. * max distance of movement of a tap, this is for the slow tappers
  10295. * @property tapMaxDistance
  10296. * @type {Number}
  10297. * @default 10
  10298. */
  10299. tapMaxDistance: 10,
  10300. /**
  10301. * always trigger the `tap` event, even while double-tapping
  10302. * @property tapAlways
  10303. * @type {Boolean}
  10304. * @default true
  10305. */
  10306. tapAlways: true,
  10307. /**
  10308. * max distance between two taps
  10309. * @property doubleTapDistance
  10310. * @type {Number}
  10311. * @default 20
  10312. */
  10313. doubleTapDistance: 20,
  10314. /**
  10315. * max time between two taps
  10316. * @property doubleTapInterval
  10317. * @type {Number}
  10318. * @default 300
  10319. */
  10320. doubleTapInterval: 300
  10321. }
  10322. };
  10323. })('tap');
  10324. /**
  10325. * @module gestures
  10326. */
  10327. /**
  10328. * when a touch is being touched at the page
  10329. *
  10330. * @class Touch
  10331. * @static
  10332. */
  10333. /**
  10334. * @event touch
  10335. * @param {Object} ev
  10336. */
  10337. Hammer.gestures.Touch = {
  10338. name: 'touch',
  10339. index: -Infinity,
  10340. defaults: {
  10341. /**
  10342. * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page,
  10343. * but it improves gestures like transforming and dragging.
  10344. * be careful with using this, it can be very annoying for users to be stuck on the page
  10345. * @property preventDefault
  10346. * @type {Boolean}
  10347. * @default false
  10348. */
  10349. preventDefault: false,
  10350. /**
  10351. * disable mouse events, so only touch (or pen!) input triggers events
  10352. * @property preventMouse
  10353. * @type {Boolean}
  10354. * @default false
  10355. */
  10356. preventMouse: false
  10357. },
  10358. handler: function touchGesture(ev, inst) {
  10359. if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) {
  10360. ev.stopDetect();
  10361. return;
  10362. }
  10363. if(inst.options.preventDefault) {
  10364. ev.preventDefault();
  10365. }
  10366. if(ev.eventType == EVENT_TOUCH) {
  10367. inst.trigger('touch', ev);
  10368. }
  10369. }
  10370. };
  10371. /**
  10372. * @module gestures
  10373. */
  10374. /**
  10375. * User want to scale or rotate with 2 fingers
  10376. * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the
  10377. * `preventDefault` option.
  10378. *
  10379. * @class Transform
  10380. * @static
  10381. */
  10382. /**
  10383. * @event transform
  10384. * @param {Object} ev
  10385. */
  10386. /**
  10387. * @event transformstart
  10388. * @param {Object} ev
  10389. */
  10390. /**
  10391. * @event transformend
  10392. * @param {Object} ev
  10393. */
  10394. /**
  10395. * @event pinchin
  10396. * @param {Object} ev
  10397. */
  10398. /**
  10399. * @event pinchout
  10400. * @param {Object} ev
  10401. */
  10402. /**
  10403. * @event rotate
  10404. * @param {Object} ev
  10405. */
  10406. /**
  10407. * @param {String} name
  10408. */
  10409. (function(name) {
  10410. var triggered = false;
  10411. function transformGesture(ev, inst) {
  10412. switch(ev.eventType) {
  10413. case EVENT_START:
  10414. triggered = false;
  10415. break;
  10416. case EVENT_MOVE:
  10417. // at least multitouch
  10418. if(ev.touches.length < 2) {
  10419. return;
  10420. }
  10421. var scaleThreshold = Math.abs(1 - ev.scale);
  10422. var rotationThreshold = Math.abs(ev.rotation);
  10423. // when the distance we moved is too small we skip this gesture
  10424. // or we can be already in dragging
  10425. if(scaleThreshold < inst.options.transformMinScale &&
  10426. rotationThreshold < inst.options.transformMinRotation) {
  10427. return;
  10428. }
  10429. // we are transforming!
  10430. Detection.current.name = name;
  10431. // first time, trigger dragstart event
  10432. if(!triggered) {
  10433. inst.trigger(name + 'start', ev);
  10434. triggered = true;
  10435. }
  10436. inst.trigger(name, ev); // basic transform event
  10437. // trigger rotate event
  10438. if(rotationThreshold > inst.options.transformMinRotation) {
  10439. inst.trigger('rotate', ev);
  10440. }
  10441. // trigger pinch event
  10442. if(scaleThreshold > inst.options.transformMinScale) {
  10443. inst.trigger('pinch', ev);
  10444. inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev);
  10445. }
  10446. break;
  10447. case EVENT_RELEASE:
  10448. if(triggered && ev.changedLength < 2) {
  10449. inst.trigger(name + 'end', ev);
  10450. triggered = false;
  10451. }
  10452. break;
  10453. }
  10454. }
  10455. Hammer.gestures.Transform = {
  10456. name: name,
  10457. index: 45,
  10458. defaults: {
  10459. /**
  10460. * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  10461. * @property transformMinScale
  10462. * @type {Number}
  10463. * @default 0.01
  10464. */
  10465. transformMinScale: 0.01,
  10466. /**
  10467. * rotation in degrees
  10468. * @property transformMinRotation
  10469. * @type {Number}
  10470. * @default 1
  10471. */
  10472. transformMinRotation: 1
  10473. },
  10474. handler: transformGesture
  10475. };
  10476. })('transform');
  10477. /**
  10478. * @module hammer
  10479. */
  10480. // AMD export
  10481. if(true) {
  10482. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
  10483. return Hammer;
  10484. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  10485. // commonjs export
  10486. } else if(typeof module !== 'undefined' && module.exports) {
  10487. module.exports = Hammer;
  10488. // browser export
  10489. } else {
  10490. window.Hammer = Hammer;
  10491. }
  10492. })(window);
  10493. /***/ },
  10494. /* 21 */
  10495. /***/ function(module, exports, __webpack_require__) {
  10496. var util = __webpack_require__(1);
  10497. var hammerUtil = __webpack_require__(22);
  10498. var moment = __webpack_require__(2);
  10499. var Component = __webpack_require__(23);
  10500. var DateUtil = __webpack_require__(24);
  10501. /**
  10502. * @constructor Range
  10503. * A Range controls a numeric range with a start and end value.
  10504. * The Range adjusts the range based on mouse events or programmatic changes,
  10505. * and triggers events when the range is changing or has been changed.
  10506. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  10507. * @param {Object} [options] See description at Range.setOptions
  10508. */
  10509. function Range(body, options) {
  10510. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  10511. this.start = now.clone().add(-3, 'days').valueOf(); // Number
  10512. this.end = now.clone().add(4, 'days').valueOf(); // Number
  10513. this.body = body;
  10514. this.deltaDifference = 0;
  10515. this.scaleOffset = 0;
  10516. this.startToFront = false;
  10517. this.endToFront = true;
  10518. // default options
  10519. this.defaultOptions = {
  10520. start: null,
  10521. end: null,
  10522. direction: 'horizontal', // 'horizontal' or 'vertical'
  10523. moveable: true,
  10524. zoomable: true,
  10525. min: null,
  10526. max: null,
  10527. zoomMin: 10, // milliseconds
  10528. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
  10529. };
  10530. this.options = util.extend({}, this.defaultOptions);
  10531. this.props = {
  10532. touch: {}
  10533. };
  10534. this.animateTimer = null;
  10535. // drag listeners for dragging
  10536. this.body.emitter.on('dragstart', this._onDragStart.bind(this));
  10537. this.body.emitter.on('drag', this._onDrag.bind(this));
  10538. this.body.emitter.on('dragend', this._onDragEnd.bind(this));
  10539. // ignore dragging when holding
  10540. this.body.emitter.on('hold', this._onHold.bind(this));
  10541. // mouse wheel for zooming
  10542. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  10543. this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  10544. // pinch to zoom
  10545. this.body.emitter.on('touch', this._onTouch.bind(this));
  10546. this.body.emitter.on('pinch', this._onPinch.bind(this));
  10547. this.setOptions(options);
  10548. }
  10549. Range.prototype = new Component();
  10550. /**
  10551. * Set options for the range controller
  10552. * @param {Object} options Available options:
  10553. * {Number | Date | String} start Start date for the range
  10554. * {Number | Date | String} end End date for the range
  10555. * {Number} min Minimum value for start
  10556. * {Number} max Maximum value for end
  10557. * {Number} zoomMin Set a minimum value for
  10558. * (end - start).
  10559. * {Number} zoomMax Set a maximum value for
  10560. * (end - start).
  10561. * {Boolean} moveable Enable moving of the range
  10562. * by dragging. True by default
  10563. * {Boolean} zoomable Enable zooming of the range
  10564. * by pinching/scrolling. True by default
  10565. */
  10566. Range.prototype.setOptions = function (options) {
  10567. if (options) {
  10568. // copy the options that we know
  10569. var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates'];
  10570. util.selectiveExtend(fields, this.options, options);
  10571. if ('start' in options || 'end' in options) {
  10572. // apply a new range. both start and end are optional
  10573. this.setRange(options.start, options.end);
  10574. }
  10575. }
  10576. };
  10577. /**
  10578. * Test whether direction has a valid value
  10579. * @param {String} direction 'horizontal' or 'vertical'
  10580. */
  10581. function validateDirection (direction) {
  10582. if (direction != 'horizontal' && direction != 'vertical') {
  10583. throw new TypeError('Unknown direction "' + direction + '". ' +
  10584. 'Choose "horizontal" or "vertical".');
  10585. }
  10586. }
  10587. /**
  10588. * Set a new start and end range
  10589. * @param {Date | Number | String} [start]
  10590. * @param {Date | Number | String} [end]
  10591. * @param {boolean | number} [animate=false] If true, the range is animated
  10592. * smoothly to the new window.
  10593. * If animate is a number, the
  10594. * number is taken as duration
  10595. * Default duration is 500 ms.
  10596. *
  10597. */
  10598. Range.prototype.setRange = function(start, end, animate) {
  10599. var _start = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  10600. var _end = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  10601. this._cancelAnimation();
  10602. if (animate) {
  10603. var me = this;
  10604. var initStart = this.start;
  10605. var initEnd = this.end;
  10606. var duration = typeof animate === 'number' ? animate : 500;
  10607. var initTime = new Date().valueOf();
  10608. var anyChanged = false;
  10609. var next = function () {
  10610. if (!me.props.touch.dragging) {
  10611. var now = new Date().valueOf();
  10612. var time = now - initTime;
  10613. var done = time > duration;
  10614. var s = (done || _start === null) ? _start : util.easeInOutQuad(time, initStart, _start, duration);
  10615. var e = (done || _end === null) ? _end : util.easeInOutQuad(time, initEnd, _end, duration);
  10616. changed = me._applyRange(s, e);
  10617. DateUtil.updateHiddenDates(me.body, me.options.hiddenDates);
  10618. anyChanged = anyChanged || changed;
  10619. if (changed) {
  10620. me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end)});
  10621. }
  10622. if (done) {
  10623. if (anyChanged) {
  10624. me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end)});
  10625. }
  10626. }
  10627. else {
  10628. // animate with as high as possible frame rate, leave 20 ms in between
  10629. // each to prevent the browser from blocking
  10630. me.animateTimer = setTimeout(next, 20);
  10631. }
  10632. }
  10633. }
  10634. return next();
  10635. }
  10636. else {
  10637. var changed = this._applyRange(_start, _end);
  10638. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  10639. if (changed) {
  10640. var params = {start: new Date(this.start), end: new Date(this.end)};
  10641. this.body.emitter.emit('rangechange', params);
  10642. this.body.emitter.emit('rangechanged', params);
  10643. }
  10644. }
  10645. };
  10646. /**
  10647. * Stop an animation
  10648. * @private
  10649. */
  10650. Range.prototype._cancelAnimation = function () {
  10651. if (this.animateTimer) {
  10652. clearTimeout(this.animateTimer);
  10653. this.animateTimer = null;
  10654. }
  10655. };
  10656. /**
  10657. * Set a new start and end range. This method is the same as setRange, but
  10658. * does not trigger a range change and range changed event, and it returns
  10659. * true when the range is changed
  10660. * @param {Number} [start]
  10661. * @param {Number} [end]
  10662. * @return {Boolean} changed
  10663. * @private
  10664. */
  10665. Range.prototype._applyRange = function(start, end) {
  10666. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  10667. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  10668. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  10669. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  10670. diff;
  10671. // check for valid number
  10672. if (isNaN(newStart) || newStart === null) {
  10673. throw new Error('Invalid start "' + start + '"');
  10674. }
  10675. if (isNaN(newEnd) || newEnd === null) {
  10676. throw new Error('Invalid end "' + end + '"');
  10677. }
  10678. // prevent start < end
  10679. if (newEnd < newStart) {
  10680. newEnd = newStart;
  10681. }
  10682. // prevent start < min
  10683. if (min !== null) {
  10684. if (newStart < min) {
  10685. diff = (min - newStart);
  10686. newStart += diff;
  10687. newEnd += diff;
  10688. // prevent end > max
  10689. if (max != null) {
  10690. if (newEnd > max) {
  10691. newEnd = max;
  10692. }
  10693. }
  10694. }
  10695. }
  10696. // prevent end > max
  10697. if (max !== null) {
  10698. if (newEnd > max) {
  10699. diff = (newEnd - max);
  10700. newStart -= diff;
  10701. newEnd -= diff;
  10702. // prevent start < min
  10703. if (min != null) {
  10704. if (newStart < min) {
  10705. newStart = min;
  10706. }
  10707. }
  10708. }
  10709. }
  10710. // prevent (end-start) < zoomMin
  10711. if (this.options.zoomMin !== null) {
  10712. var zoomMin = parseFloat(this.options.zoomMin);
  10713. if (zoomMin < 0) {
  10714. zoomMin = 0;
  10715. }
  10716. if ((newEnd - newStart) < zoomMin) {
  10717. if ((this.end - this.start) === zoomMin) {
  10718. // ignore this action, we are already zoomed to the minimum
  10719. newStart = this.start;
  10720. newEnd = this.end;
  10721. }
  10722. else {
  10723. // zoom to the minimum
  10724. diff = (zoomMin - (newEnd - newStart));
  10725. newStart -= diff / 2;
  10726. newEnd += diff / 2;
  10727. }
  10728. }
  10729. }
  10730. // prevent (end-start) > zoomMax
  10731. if (this.options.zoomMax !== null) {
  10732. var zoomMax = parseFloat(this.options.zoomMax);
  10733. if (zoomMax < 0) {
  10734. zoomMax = 0;
  10735. }
  10736. if ((newEnd - newStart) > zoomMax) {
  10737. if ((this.end - this.start) === zoomMax) {
  10738. // ignore this action, we are already zoomed to the maximum
  10739. newStart = this.start;
  10740. newEnd = this.end;
  10741. }
  10742. else {
  10743. // zoom to the maximum
  10744. diff = ((newEnd - newStart) - zoomMax);
  10745. newStart += diff / 2;
  10746. newEnd -= diff / 2;
  10747. }
  10748. }
  10749. }
  10750. var changed = (this.start != newStart || this.end != newEnd);
  10751. // 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)
  10752. if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
  10753. !((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
  10754. this.body.emitter.emit('checkRangedItems');
  10755. }
  10756. this.start = newStart;
  10757. this.end = newEnd;
  10758. return changed;
  10759. };
  10760. /**
  10761. * Retrieve the current range.
  10762. * @return {Object} An object with start and end properties
  10763. */
  10764. Range.prototype.getRange = function() {
  10765. return {
  10766. start: this.start,
  10767. end: this.end
  10768. };
  10769. };
  10770. /**
  10771. * Calculate the conversion offset and scale for current range, based on
  10772. * the provided width
  10773. * @param {Number} width
  10774. * @returns {{offset: number, scale: number}} conversion
  10775. */
  10776. Range.prototype.conversion = function (width, totalHidden) {
  10777. return Range.conversion(this.start, this.end, width, totalHidden);
  10778. };
  10779. /**
  10780. * Static method to calculate the conversion offset and scale for a range,
  10781. * based on the provided start, end, and width
  10782. * @param {Number} start
  10783. * @param {Number} end
  10784. * @param {Number} width
  10785. * @returns {{offset: number, scale: number}} conversion
  10786. */
  10787. Range.conversion = function (start, end, width, totalHidden) {
  10788. if (totalHidden === undefined) {
  10789. totalHidden = 0;
  10790. }
  10791. if (width != 0 && (end - start != 0)) {
  10792. return {
  10793. offset: start,
  10794. scale: width / (end - start - totalHidden)
  10795. }
  10796. }
  10797. else {
  10798. return {
  10799. offset: 0,
  10800. scale: 1
  10801. };
  10802. }
  10803. };
  10804. /**
  10805. * Start dragging horizontally or vertically
  10806. * @param {Event} event
  10807. * @private
  10808. */
  10809. Range.prototype._onDragStart = function(event) {
  10810. this.deltaDifference = 0;
  10811. this.previousDelta = 0;
  10812. // only allow dragging when configured as movable
  10813. if (!this.options.moveable) return;
  10814. // refuse to drag when we where pinching to prevent the timeline make a jump
  10815. // when releasing the fingers in opposite order from the touch screen
  10816. if (!this.props.touch.allowDragging) return;
  10817. this.props.touch.start = this.start;
  10818. this.props.touch.end = this.end;
  10819. this.props.touch.dragging = true;
  10820. if (this.body.dom.root) {
  10821. this.body.dom.root.style.cursor = 'move';
  10822. }
  10823. };
  10824. /**
  10825. * Perform dragging operation
  10826. * @param {Event} event
  10827. * @private
  10828. */
  10829. Range.prototype._onDrag = function (event) {
  10830. // only allow dragging when configured as movable
  10831. if (!this.options.moveable) return;
  10832. // refuse to drag when we where pinching to prevent the timeline make a jump
  10833. // when releasing the fingers in opposite order from the touch screen
  10834. if (!this.props.touch.allowDragging) return;
  10835. var direction = this.options.direction;
  10836. validateDirection(direction);
  10837. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY;
  10838. delta -= this.deltaDifference;
  10839. var interval = (this.props.touch.end - this.props.touch.start);
  10840. // normalize dragging speed if cutout is in between.
  10841. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  10842. interval -= duration;
  10843. var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
  10844. var diffRange = -delta / width * interval;
  10845. var newStart = this.props.touch.start + diffRange;
  10846. var newEnd = this.props.touch.end + diffRange;
  10847. // snapping times away from hidden zones
  10848. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
  10849. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
  10850. if (safeStart != newStart || safeEnd != newEnd) {
  10851. this.deltaDifference += delta;
  10852. this.props.touch.start = safeStart;
  10853. this.props.touch.end = safeEnd;
  10854. this._onDrag(event);
  10855. return;
  10856. }
  10857. this.previousDelta = delta;
  10858. this._applyRange(newStart, newEnd);
  10859. // fire a rangechange event
  10860. this.body.emitter.emit('rangechange', {
  10861. start: new Date(this.start),
  10862. end: new Date(this.end)
  10863. });
  10864. };
  10865. /**
  10866. * Stop dragging operation
  10867. * @param {event} event
  10868. * @private
  10869. */
  10870. Range.prototype._onDragEnd = function (event) {
  10871. // only allow dragging when configured as movable
  10872. if (!this.options.moveable) return;
  10873. // refuse to drag when we where pinching to prevent the timeline make a jump
  10874. // when releasing the fingers in opposite order from the touch screen
  10875. if (!this.props.touch.allowDragging) return;
  10876. this.props.touch.dragging = false;
  10877. if (this.body.dom.root) {
  10878. this.body.dom.root.style.cursor = 'auto';
  10879. }
  10880. // fire a rangechanged event
  10881. this.body.emitter.emit('rangechanged', {
  10882. start: new Date(this.start),
  10883. end: new Date(this.end)
  10884. });
  10885. };
  10886. /**
  10887. * Event handler for mouse wheel event, used to zoom
  10888. * Code from http://adomas.org/javascript-mouse-wheel/
  10889. * @param {Event} event
  10890. * @private
  10891. */
  10892. Range.prototype._onMouseWheel = function(event) {
  10893. // only allow zooming when configured as zoomable and moveable
  10894. if (!(this.options.zoomable && this.options.moveable)) return;
  10895. // retrieve delta
  10896. var delta = 0;
  10897. if (event.wheelDelta) { /* IE/Opera. */
  10898. delta = event.wheelDelta / 120;
  10899. } else if (event.detail) { /* Mozilla case. */
  10900. // In Mozilla, sign of delta is different than in IE.
  10901. // Also, delta is multiple of 3.
  10902. delta = -event.detail / 3;
  10903. }
  10904. // If delta is nonzero, handle it.
  10905. // Basically, delta is now positive if wheel was scrolled up,
  10906. // and negative, if wheel was scrolled down.
  10907. if (delta) {
  10908. // perform the zoom action. Delta is normally 1 or -1
  10909. // adjust a negative delta such that zooming in with delta 0.1
  10910. // equals zooming out with a delta -0.1
  10911. var scale;
  10912. if (delta < 0) {
  10913. scale = 1 - (delta / 5);
  10914. }
  10915. else {
  10916. scale = 1 / (1 + (delta / 5)) ;
  10917. }
  10918. // calculate center, the date to zoom around
  10919. var gesture = hammerUtil.fakeGesture(this, event),
  10920. pointer = getPointer(gesture.center, this.body.dom.center),
  10921. pointerDate = this._pointerToDate(pointer);
  10922. this.zoom(scale, pointerDate, delta);
  10923. }
  10924. // Prevent default actions caused by mouse wheel
  10925. // (else the page and timeline both zoom and scroll)
  10926. event.preventDefault();
  10927. };
  10928. /**
  10929. * Start of a touch gesture
  10930. * @private
  10931. */
  10932. Range.prototype._onTouch = function (event) {
  10933. this.props.touch.start = this.start;
  10934. this.props.touch.end = this.end;
  10935. this.props.touch.allowDragging = true;
  10936. this.props.touch.center = null;
  10937. this.scaleOffset = 0;
  10938. this.deltaDifference = 0;
  10939. };
  10940. /**
  10941. * On start of a hold gesture
  10942. * @private
  10943. */
  10944. Range.prototype._onHold = function () {
  10945. this.props.touch.allowDragging = false;
  10946. };
  10947. /**
  10948. * Handle pinch event
  10949. * @param {Event} event
  10950. * @private
  10951. */
  10952. Range.prototype._onPinch = function (event) {
  10953. // only allow zooming when configured as zoomable and moveable
  10954. if (!(this.options.zoomable && this.options.moveable)) return;
  10955. this.props.touch.allowDragging = false;
  10956. if (event.gesture.touches.length > 1) {
  10957. if (!this.props.touch.center) {
  10958. this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center);
  10959. }
  10960. var scale = 1 / (event.gesture.scale + this.scaleOffset);
  10961. var centerDate = this._pointerToDate(this.props.touch.center);
  10962. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  10963. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate);
  10964. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  10965. // calculate new start and end
  10966. var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  10967. var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  10968. // snapping times away from hidden zones
  10969. this.startToFront = 1 - scale > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  10970. this.endToFront = scale - 1 > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  10971. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  10972. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  10973. if (safeStart != newStart || safeEnd != newEnd) {
  10974. this.props.touch.start = safeStart;
  10975. this.props.touch.end = safeEnd;
  10976. this.scaleOffset = 1 - event.gesture.scale;
  10977. newStart = safeStart;
  10978. newEnd = safeEnd;
  10979. }
  10980. this.setRange(newStart, newEnd);
  10981. this.startToFront = false; // revert to default
  10982. this.endToFront = true; // revert to default
  10983. }
  10984. };
  10985. /**
  10986. * Helper function to calculate the center date for zooming
  10987. * @param {{x: Number, y: Number}} pointer
  10988. * @return {number} date
  10989. * @private
  10990. */
  10991. Range.prototype._pointerToDate = function (pointer) {
  10992. var conversion;
  10993. var direction = this.options.direction;
  10994. validateDirection(direction);
  10995. if (direction == 'horizontal') {
  10996. return this.body.util.toTime(pointer.x).valueOf();
  10997. }
  10998. else {
  10999. var height = this.body.domProps.center.height;
  11000. conversion = this.conversion(height);
  11001. return pointer.y / conversion.scale + conversion.offset;
  11002. }
  11003. };
  11004. /**
  11005. * Get the pointer location relative to the location of the dom element
  11006. * @param {{pageX: Number, pageY: Number}} touch
  11007. * @param {Element} element HTML DOM element
  11008. * @return {{x: Number, y: Number}} pointer
  11009. * @private
  11010. */
  11011. function getPointer (touch, element) {
  11012. return {
  11013. x: touch.pageX - util.getAbsoluteLeft(element),
  11014. y: touch.pageY - util.getAbsoluteTop(element)
  11015. };
  11016. }
  11017. /**
  11018. * Zoom the range the given scale in or out. Start and end date will
  11019. * be adjusted, and the timeline will be redrawn. You can optionally give a
  11020. * date around which to zoom.
  11021. * For example, try scale = 0.9 or 1.1
  11022. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  11023. * values below 1 will zoom in.
  11024. * @param {Number} [center] Value representing a date around which will
  11025. * be zoomed.
  11026. */
  11027. Range.prototype.zoom = function(scale, center, delta) {
  11028. // if centerDate is not provided, take it half between start Date and end Date
  11029. if (center == null) {
  11030. center = (this.start + this.end) / 2;
  11031. }
  11032. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  11033. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center);
  11034. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  11035. // calculate new start and end
  11036. var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
  11037. var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
  11038. // snapping times away from hidden zones
  11039. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  11040. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  11041. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  11042. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  11043. if (safeStart != newStart || safeEnd != newEnd) {
  11044. newStart = safeStart;
  11045. newEnd = safeEnd;
  11046. }
  11047. this.setRange(newStart, newEnd);
  11048. this.startToFront = false; // revert to default
  11049. this.endToFront = true; // revert to default
  11050. };
  11051. /**
  11052. * Move the range with a given delta to the left or right. Start and end
  11053. * value will be adjusted. For example, try delta = 0.1 or -0.1
  11054. * @param {Number} delta Moving amount. Positive value will move right,
  11055. * negative value will move left
  11056. */
  11057. Range.prototype.move = function(delta) {
  11058. // zoom start Date and end Date relative to the centerDate
  11059. var diff = (this.end - this.start);
  11060. // apply new values
  11061. var newStart = this.start + diff * delta;
  11062. var newEnd = this.end + diff * delta;
  11063. // TODO: reckon with min and max range
  11064. this.start = newStart;
  11065. this.end = newEnd;
  11066. };
  11067. /**
  11068. * Move the range to a new center point
  11069. * @param {Number} moveTo New center point of the range
  11070. */
  11071. Range.prototype.moveTo = function(moveTo) {
  11072. var center = (this.start + this.end) / 2;
  11073. var diff = center - moveTo;
  11074. // calculate new start and end
  11075. var newStart = this.start - diff;
  11076. var newEnd = this.end - diff;
  11077. this.setRange(newStart, newEnd);
  11078. };
  11079. module.exports = Range;
  11080. /***/ },
  11081. /* 22 */
  11082. /***/ function(module, exports, __webpack_require__) {
  11083. var Hammer = __webpack_require__(19);
  11084. /**
  11085. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  11086. * @param {Element} element
  11087. * @param {Event} event
  11088. */
  11089. exports.fakeGesture = function(element, event) {
  11090. var eventType = null;
  11091. // for hammer.js 1.0.5
  11092. // var gesture = Hammer.event.collectEventData(this, eventType, event);
  11093. // for hammer.js 1.0.6+
  11094. var touches = Hammer.event.getTouchList(event, eventType);
  11095. var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  11096. // on IE in standards mode, no touches are recognized by hammer.js,
  11097. // resulting in NaN values for center.pageX and center.pageY
  11098. if (isNaN(gesture.center.pageX)) {
  11099. gesture.center.pageX = event.pageX;
  11100. }
  11101. if (isNaN(gesture.center.pageY)) {
  11102. gesture.center.pageY = event.pageY;
  11103. }
  11104. return gesture;
  11105. };
  11106. /***/ },
  11107. /* 23 */
  11108. /***/ function(module, exports, __webpack_require__) {
  11109. /**
  11110. * Prototype for visual components
  11111. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
  11112. * @param {Object} [options]
  11113. */
  11114. function Component (body, options) {
  11115. this.options = null;
  11116. this.props = null;
  11117. }
  11118. /**
  11119. * Set options for the component. The new options will be merged into the
  11120. * current options.
  11121. * @param {Object} options
  11122. */
  11123. Component.prototype.setOptions = function(options) {
  11124. if (options) {
  11125. util.extend(this.options, options);
  11126. }
  11127. };
  11128. /**
  11129. * Repaint the component
  11130. * @return {boolean} Returns true if the component is resized
  11131. */
  11132. Component.prototype.redraw = function() {
  11133. // should be implemented by the component
  11134. return false;
  11135. };
  11136. /**
  11137. * Destroy the component. Cleanup DOM and event listeners
  11138. */
  11139. Component.prototype.destroy = function() {
  11140. // should be implemented by the component
  11141. };
  11142. /**
  11143. * Test whether the component is resized since the last time _isResized() was
  11144. * called.
  11145. * @return {Boolean} Returns true if the component is resized
  11146. * @protected
  11147. */
  11148. Component.prototype._isResized = function() {
  11149. var resized = (this.props._previousWidth !== this.props.width ||
  11150. this.props._previousHeight !== this.props.height);
  11151. this.props._previousWidth = this.props.width;
  11152. this.props._previousHeight = this.props.height;
  11153. return resized;
  11154. };
  11155. module.exports = Component;
  11156. /***/ },
  11157. /* 24 */
  11158. /***/ function(module, exports, __webpack_require__) {
  11159. /**
  11160. * Created by Alex on 10/3/2014.
  11161. */
  11162. var moment = __webpack_require__(2);
  11163. /**
  11164. * used in Core to convert the options into a volatile variable
  11165. *
  11166. * @param Core
  11167. */
  11168. exports.convertHiddenOptions = function(body, hiddenDates) {
  11169. body.hiddenDates = [];
  11170. if (hiddenDates) {
  11171. if (Array.isArray(hiddenDates) == true) {
  11172. for (var i = 0; i < hiddenDates.length; i++) {
  11173. if (hiddenDates[i].repeat === undefined) {
  11174. var dateItem = {};
  11175. dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
  11176. dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
  11177. body.hiddenDates.push(dateItem);
  11178. }
  11179. }
  11180. body.hiddenDates.sort(function (a, b) {
  11181. return a.start - b.start;
  11182. }); // sort by start time
  11183. }
  11184. }
  11185. };
  11186. /**
  11187. * create new entrees for the repeating hidden dates
  11188. * @param body
  11189. * @param hiddenDates
  11190. */
  11191. exports.updateHiddenDates = function (body, hiddenDates) {
  11192. if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
  11193. exports.convertHiddenOptions(body, hiddenDates);
  11194. var start = moment(body.range.start);
  11195. var end = moment(body.range.end);
  11196. var totalRange = (body.range.end - body.range.start);
  11197. var pixelTime = totalRange / body.domProps.centerContainer.width;
  11198. for (var i = 0; i < hiddenDates.length; i++) {
  11199. if (hiddenDates[i].repeat !== undefined) {
  11200. var startDate = moment(hiddenDates[i].start);
  11201. var endDate = moment(hiddenDates[i].end);
  11202. if (startDate._d == "Invalid Date") {
  11203. throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
  11204. }
  11205. if (endDate._d == "Invalid Date") {
  11206. throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
  11207. }
  11208. var duration = endDate - startDate;
  11209. if (duration >= 4 * pixelTime) {
  11210. var offset = 0;
  11211. var runUntil = end.clone();
  11212. switch (hiddenDates[i].repeat) {
  11213. case "daily": // case of time
  11214. if (startDate.day() != endDate.day()) {
  11215. offset = 1;
  11216. }
  11217. startDate.dayOfYear(start.dayOfYear());
  11218. startDate.year(start.year());
  11219. startDate.subtract(7,'days');
  11220. endDate.dayOfYear(start.dayOfYear());
  11221. endDate.year(start.year());
  11222. endDate.subtract(7 - offset,'days');
  11223. runUntil.add(1, 'weeks');
  11224. break;
  11225. case "weekly":
  11226. var dayOffset = endDate.diff(startDate,'days')
  11227. var day = startDate.day();
  11228. // set the start date to the range.start
  11229. startDate.date(start.date());
  11230. startDate.month(start.month());
  11231. startDate.year(start.year());
  11232. endDate = startDate.clone();
  11233. // force
  11234. startDate.day(day);
  11235. endDate.day(day);
  11236. endDate.add(dayOffset,'days');
  11237. startDate.subtract(1,'weeks');
  11238. endDate.subtract(1,'weeks');
  11239. runUntil.add(1, 'weeks');
  11240. break
  11241. case "monthly":
  11242. if (startDate.month() != endDate.month()) {
  11243. offset = 1;
  11244. }
  11245. startDate.month(start.month());
  11246. startDate.year(start.year());
  11247. startDate.subtract(1,'months');
  11248. endDate.month(start.month());
  11249. endDate.year(start.year());
  11250. endDate.subtract(1,'months');
  11251. endDate.add(offset,'months');
  11252. runUntil.add(1, 'months');
  11253. break;
  11254. case "yearly":
  11255. if (startDate.year() != endDate.year()) {
  11256. offset = 1;
  11257. }
  11258. startDate.year(start.year());
  11259. startDate.subtract(1,'years');
  11260. endDate.year(start.year());
  11261. endDate.subtract(1,'years');
  11262. endDate.add(offset,'years');
  11263. runUntil.add(1, 'years');
  11264. break;
  11265. default:
  11266. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  11267. return;
  11268. }
  11269. while (startDate < runUntil) {
  11270. body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
  11271. switch (hiddenDates[i].repeat) {
  11272. case "daily":
  11273. startDate.add(1, 'days');
  11274. endDate.add(1, 'days');
  11275. break;
  11276. case "weekly":
  11277. startDate.add(1, 'weeks');
  11278. endDate.add(1, 'weeks');
  11279. break
  11280. case "monthly":
  11281. startDate.add(1, 'months');
  11282. endDate.add(1, 'months');
  11283. break;
  11284. case "yearly":
  11285. startDate.add(1, 'y');
  11286. endDate.add(1, 'y');
  11287. break;
  11288. default:
  11289. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  11290. return;
  11291. }
  11292. }
  11293. body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
  11294. }
  11295. }
  11296. }
  11297. // remove duplicates, merge where possible
  11298. exports.removeDuplicates(body);
  11299. // ensure the new positions are not on hidden dates
  11300. var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
  11301. var endHidden = exports.isHidden(body.range.end,body.hiddenDates);
  11302. var rangeStart = body.range.start;
  11303. var rangeEnd = body.range.end;
  11304. if (startHidden.hidden == true) {rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;}
  11305. if (endHidden.hidden == true) {rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;}
  11306. if (startHidden.hidden == true || endHidden.hidden == true) {
  11307. body.range._applyRange(rangeStart, rangeEnd);
  11308. }
  11309. }
  11310. }
  11311. /**
  11312. * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
  11313. * Scales with N^2
  11314. * @param body
  11315. */
  11316. exports.removeDuplicates = function(body) {
  11317. var hiddenDates = body.hiddenDates;
  11318. var safeDates = [];
  11319. for (var i = 0; i < hiddenDates.length; i++) {
  11320. for (var j = 0; j < hiddenDates.length; j++) {
  11321. if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
  11322. // j inside i
  11323. if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  11324. hiddenDates[j].remove = true;
  11325. }
  11326. // j start inside i
  11327. else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
  11328. hiddenDates[i].end = hiddenDates[j].end;
  11329. hiddenDates[j].remove = true;
  11330. }
  11331. // j end inside i
  11332. else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  11333. hiddenDates[i].start = hiddenDates[j].start;
  11334. hiddenDates[j].remove = true;
  11335. }
  11336. }
  11337. }
  11338. }
  11339. for (var i = 0; i < hiddenDates.length; i++) {
  11340. if (hiddenDates[i].remove !== true) {
  11341. safeDates.push(hiddenDates[i]);
  11342. }
  11343. }
  11344. body.hiddenDates = safeDates;
  11345. body.hiddenDates.sort(function (a, b) {
  11346. return a.start - b.start;
  11347. }); // sort by start time
  11348. }
  11349. exports.printDates = function(dates) {
  11350. for (var i =0; i < dates.length; i++) {
  11351. console.log(i, new Date(dates[i].start),new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
  11352. }
  11353. }
  11354. /**
  11355. * Used in TimeStep to avoid the hidden times.
  11356. * @param timeStep
  11357. * @param previousTime
  11358. */
  11359. exports.stepOverHiddenDates = function(timeStep, previousTime) {
  11360. var stepInHidden = false;
  11361. var currentValue = timeStep.current.valueOf();
  11362. for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  11363. var startDate = timeStep.hiddenDates[i].start;
  11364. var endDate = timeStep.hiddenDates[i].end;
  11365. if (currentValue >= startDate && currentValue < endDate) {
  11366. stepInHidden = true;
  11367. break;
  11368. }
  11369. }
  11370. if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
  11371. var prevValue = moment(previousTime);
  11372. var newValue = moment(endDate);
  11373. //check if the next step should be major
  11374. if (prevValue.year() != newValue.year()) {timeStep.switchedYear = true;}
  11375. else if (prevValue.month() != newValue.month()) {timeStep.switchedMonth = true;}
  11376. else if (prevValue.dayOfYear() != newValue.dayOfYear()) {timeStep.switchedDay = true;}
  11377. timeStep.current = newValue.toDate();
  11378. }
  11379. };
  11380. ///**
  11381. // * Used in TimeStep to avoid the hidden times.
  11382. // * @param timeStep
  11383. // * @param previousTime
  11384. // */
  11385. //exports.checkFirstStep = function(timeStep) {
  11386. // var stepInHidden = false;
  11387. // var currentValue = timeStep.current.valueOf();
  11388. // for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  11389. // var startDate = timeStep.hiddenDates[i].start;
  11390. // var endDate = timeStep.hiddenDates[i].end;
  11391. // if (currentValue >= startDate && currentValue < endDate) {
  11392. // stepInHidden = true;
  11393. // break;
  11394. // }
  11395. // }
  11396. //
  11397. // if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
  11398. // var newValue = moment(endDate);
  11399. // timeStep.current = newValue.toDate();
  11400. // }
  11401. //};
  11402. /**
  11403. * replaces the Core toScreen methods
  11404. * @param Core
  11405. * @param time
  11406. * @param width
  11407. * @returns {number}
  11408. */
  11409. exports.toScreen = function(Core, time, width) {
  11410. if (Core.body.hiddenDates.length == 0) {
  11411. var conversion = Core.range.conversion(width);
  11412. return (time.valueOf() - conversion.offset) * conversion.scale;
  11413. }
  11414. else {
  11415. var hidden = exports.isHidden(time, Core.body.hiddenDates)
  11416. if (hidden.hidden == true) {
  11417. time = hidden.startDate;
  11418. }
  11419. var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  11420. time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time);
  11421. var conversion = Core.range.conversion(width, duration);
  11422. return (time.valueOf() - conversion.offset) * conversion.scale;
  11423. }
  11424. };
  11425. /**
  11426. * Replaces the core toTime methods
  11427. * @param body
  11428. * @param range
  11429. * @param x
  11430. * @param width
  11431. * @returns {Date}
  11432. */
  11433. exports.toTime = function(Core, x, width) {
  11434. if (Core.body.hiddenDates.length == 0) {
  11435. var conversion = Core.range.conversion(width);
  11436. return new Date(x / conversion.scale + conversion.offset);
  11437. }
  11438. else {
  11439. var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  11440. var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
  11441. var partialDuration = totalDuration * x / width;
  11442. var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
  11443. var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
  11444. return newTime;
  11445. }
  11446. };
  11447. /**
  11448. * Support function
  11449. *
  11450. * @param hiddenDates
  11451. * @param range
  11452. * @returns {number}
  11453. */
  11454. exports.getHiddenDurationBetween = function(hiddenDates, start, end) {
  11455. var duration = 0;
  11456. for (var i = 0; i < hiddenDates.length; i++) {
  11457. var startDate = hiddenDates[i].start;
  11458. var endDate = hiddenDates[i].end;
  11459. // if time after the cutout, and the
  11460. if (startDate >= start && endDate < end) {
  11461. duration += endDate - startDate;
  11462. }
  11463. }
  11464. return duration;
  11465. };
  11466. /**
  11467. * Support function
  11468. * @param hiddenDates
  11469. * @param range
  11470. * @param time
  11471. * @returns {{duration: number, time: *, offset: number}}
  11472. */
  11473. exports.correctTimeForHidden = function(hiddenDates, range, time) {
  11474. time = moment(time).toDate().valueOf();
  11475. time -= exports.getHiddenDurationBefore(hiddenDates,range,time);
  11476. return time;
  11477. };
  11478. exports.getHiddenDurationBefore = function(hiddenDates, range, time) {
  11479. var timeOffset = 0;
  11480. time = moment(time).toDate().valueOf();
  11481. for (var i = 0; i < hiddenDates.length; i++) {
  11482. var startDate = hiddenDates[i].start;
  11483. var endDate = hiddenDates[i].end;
  11484. // if time after the cutout, and the
  11485. if (startDate >= range.start && endDate < range.end) {
  11486. if (time >= endDate) {
  11487. timeOffset += (endDate - startDate);
  11488. }
  11489. }
  11490. }
  11491. return timeOffset;
  11492. }
  11493. /**
  11494. * sum the duration from start to finish, including the hidden duration,
  11495. * until the required amount has been reached, return the accumulated hidden duration
  11496. * @param hiddenDates
  11497. * @param range
  11498. * @param time
  11499. * @returns {{duration: number, time: *, offset: number}}
  11500. */
  11501. exports.getAccumulatedHiddenDuration = function(hiddenDates, range, requiredDuration) {
  11502. var hiddenDuration = 0;
  11503. var duration = 0;
  11504. var previousPoint = range.start;
  11505. //exports.printDates(hiddenDates)
  11506. for (var i = 0; i < hiddenDates.length; i++) {
  11507. var startDate = hiddenDates[i].start;
  11508. var endDate = hiddenDates[i].end;
  11509. // if time after the cutout, and the
  11510. if (startDate >= range.start && endDate < range.end) {
  11511. duration += startDate - previousPoint;
  11512. previousPoint = endDate;
  11513. if (duration >= requiredDuration) {
  11514. break;
  11515. }
  11516. else {
  11517. hiddenDuration += endDate - startDate;
  11518. }
  11519. }
  11520. }
  11521. return hiddenDuration;
  11522. };
  11523. /**
  11524. * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
  11525. * @param hiddenDates
  11526. * @param time
  11527. * @param direction
  11528. * @param correctionEnabled
  11529. * @returns {*}
  11530. */
  11531. exports.snapAwayFromHidden = function(hiddenDates, time, direction, correctionEnabled) {
  11532. var isHidden = exports.isHidden(time, hiddenDates);
  11533. if (isHidden.hidden == true) {
  11534. if (direction < 0) {
  11535. if (correctionEnabled == true) {
  11536. return isHidden.startDate - (isHidden.endDate - time) - 1;
  11537. }
  11538. else {
  11539. return isHidden.startDate - 1;
  11540. }
  11541. }
  11542. else {
  11543. if (correctionEnabled == true) {
  11544. return isHidden.endDate + (time - isHidden.startDate) + 1;
  11545. }
  11546. else {
  11547. return isHidden.endDate + 1;
  11548. }
  11549. }
  11550. }
  11551. else {
  11552. return time;
  11553. }
  11554. }
  11555. /**
  11556. * Check if a time is hidden
  11557. *
  11558. * @param time
  11559. * @param hiddenDates
  11560. * @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
  11561. */
  11562. exports.isHidden = function(time, hiddenDates) {
  11563. for (var i = 0; i < hiddenDates.length; i++) {
  11564. var startDate = hiddenDates[i].start;
  11565. var endDate = hiddenDates[i].end;
  11566. if (time >= startDate && time < endDate) { // if the start is entering a hidden zone
  11567. return {hidden: true, startDate: startDate, endDate: endDate};
  11568. break;
  11569. }
  11570. }
  11571. return {hidden: false, startDate: startDate, endDate: endDate};
  11572. }
  11573. /***/ },
  11574. /* 25 */
  11575. /***/ function(module, exports, __webpack_require__) {
  11576. var Emitter = __webpack_require__(11);
  11577. var Hammer = __webpack_require__(19);
  11578. var util = __webpack_require__(1);
  11579. var DataSet = __webpack_require__(7);
  11580. var DataView = __webpack_require__(9);
  11581. var Range = __webpack_require__(21);
  11582. var ItemSet = __webpack_require__(26);
  11583. var Activator = __webpack_require__(35);
  11584. var DateUtil = __webpack_require__(24);
  11585. /**
  11586. * Create a timeline visualization
  11587. * @param {HTMLElement} container
  11588. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  11589. * @param {Object} [options] See Core.setOptions for the available options.
  11590. * @constructor
  11591. */
  11592. function Core () {}
  11593. // turn Core into an event emitter
  11594. Emitter(Core.prototype);
  11595. /**
  11596. * Create the main DOM for the Core: a root panel containing left, right,
  11597. * top, bottom, content, and background panel.
  11598. * @param {Element} container The container element where the Core will
  11599. * be attached.
  11600. * @private
  11601. */
  11602. Core.prototype._create = function (container) {
  11603. this.dom = {};
  11604. this.dom.root = document.createElement('div');
  11605. this.dom.background = document.createElement('div');
  11606. this.dom.backgroundVertical = document.createElement('div');
  11607. this.dom.backgroundHorizontal = document.createElement('div');
  11608. this.dom.centerContainer = document.createElement('div');
  11609. this.dom.leftContainer = document.createElement('div');
  11610. this.dom.rightContainer = document.createElement('div');
  11611. this.dom.center = document.createElement('div');
  11612. this.dom.left = document.createElement('div');
  11613. this.dom.right = document.createElement('div');
  11614. this.dom.top = document.createElement('div');
  11615. this.dom.bottom = document.createElement('div');
  11616. this.dom.shadowTop = document.createElement('div');
  11617. this.dom.shadowBottom = document.createElement('div');
  11618. this.dom.shadowTopLeft = document.createElement('div');
  11619. this.dom.shadowBottomLeft = document.createElement('div');
  11620. this.dom.shadowTopRight = document.createElement('div');
  11621. this.dom.shadowBottomRight = document.createElement('div');
  11622. this.dom.root.className = 'vis timeline root';
  11623. this.dom.background.className = 'vispanel background';
  11624. this.dom.backgroundVertical.className = 'vispanel background vertical';
  11625. this.dom.backgroundHorizontal.className = 'vispanel background horizontal';
  11626. this.dom.centerContainer.className = 'vispanel center';
  11627. this.dom.leftContainer.className = 'vispanel left';
  11628. this.dom.rightContainer.className = 'vispanel right';
  11629. this.dom.top.className = 'vispanel top';
  11630. this.dom.bottom.className = 'vispanel bottom';
  11631. this.dom.left.className = 'content';
  11632. this.dom.center.className = 'content';
  11633. this.dom.right.className = 'content';
  11634. this.dom.shadowTop.className = 'shadow top';
  11635. this.dom.shadowBottom.className = 'shadow bottom';
  11636. this.dom.shadowTopLeft.className = 'shadow top';
  11637. this.dom.shadowBottomLeft.className = 'shadow bottom';
  11638. this.dom.shadowTopRight.className = 'shadow top';
  11639. this.dom.shadowBottomRight.className = 'shadow bottom';
  11640. this.dom.root.appendChild(this.dom.background);
  11641. this.dom.root.appendChild(this.dom.backgroundVertical);
  11642. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  11643. this.dom.root.appendChild(this.dom.centerContainer);
  11644. this.dom.root.appendChild(this.dom.leftContainer);
  11645. this.dom.root.appendChild(this.dom.rightContainer);
  11646. this.dom.root.appendChild(this.dom.top);
  11647. this.dom.root.appendChild(this.dom.bottom);
  11648. this.dom.centerContainer.appendChild(this.dom.center);
  11649. this.dom.leftContainer.appendChild(this.dom.left);
  11650. this.dom.rightContainer.appendChild(this.dom.right);
  11651. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  11652. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  11653. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  11654. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  11655. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  11656. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  11657. this.on('rangechange', this.redraw.bind(this));
  11658. this.on('touch', this._onTouch.bind(this));
  11659. this.on('pinch', this._onPinch.bind(this));
  11660. this.on('dragstart', this._onDragStart.bind(this));
  11661. this.on('drag', this._onDrag.bind(this));
  11662. var me = this;
  11663. this.on('change', function (properties) {
  11664. if (properties && properties.queue == true) {
  11665. // redraw once on next tick
  11666. if (!me._redrawTimer) {
  11667. me._redrawTimer = setTimeout(function () {
  11668. me._redrawTimer = null;
  11669. me.redraw();
  11670. }, 0)
  11671. }
  11672. }
  11673. else {
  11674. // redraw immediately
  11675. me.redraw();
  11676. }
  11677. });
  11678. // create event listeners for all interesting events, these events will be
  11679. // emitted via emitter
  11680. this.hammer = Hammer(this.dom.root, {
  11681. preventDefault: true
  11682. });
  11683. this.listeners = {};
  11684. var events = [
  11685. 'touch', 'pinch',
  11686. 'tap', 'doubletap', 'hold',
  11687. 'dragstart', 'drag', 'dragend',
  11688. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  11689. ];
  11690. events.forEach(function (event) {
  11691. var listener = function () {
  11692. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  11693. if (me.isActive()) {
  11694. me.emit.apply(me, args);
  11695. }
  11696. };
  11697. me.hammer.on(event, listener);
  11698. me.listeners[event] = listener;
  11699. });
  11700. // size properties of each of the panels
  11701. this.props = {
  11702. root: {},
  11703. background: {},
  11704. centerContainer: {},
  11705. leftContainer: {},
  11706. rightContainer: {},
  11707. center: {},
  11708. left: {},
  11709. right: {},
  11710. top: {},
  11711. bottom: {},
  11712. border: {},
  11713. scrollTop: 0,
  11714. scrollTopMin: 0
  11715. };
  11716. this.touch = {}; // store state information needed for touch events
  11717. this.redrawCount = 0;
  11718. // attach the root panel to the provided container
  11719. if (!container) throw new Error('No container provided');
  11720. container.appendChild(this.dom.root);
  11721. };
  11722. /**
  11723. * Set options. Options will be passed to all components loaded in the Timeline.
  11724. * @param {Object} [options]
  11725. * {String} orientation
  11726. * Vertical orientation for the Timeline,
  11727. * can be 'bottom' (default) or 'top'.
  11728. * {String | Number} width
  11729. * Width for the timeline, a number in pixels or
  11730. * a css string like '1000px' or '75%'. '100%' by default.
  11731. * {String | Number} height
  11732. * Fixed height for the Timeline, a number in pixels or
  11733. * a css string like '400px' or '75%'. If undefined,
  11734. * The Timeline will automatically size such that
  11735. * its contents fit.
  11736. * {String | Number} minHeight
  11737. * Minimum height for the Timeline, a number in pixels or
  11738. * a css string like '400px' or '75%'.
  11739. * {String | Number} maxHeight
  11740. * Maximum height for the Timeline, a number in pixels or
  11741. * a css string like '400px' or '75%'.
  11742. * {Number | Date | String} start
  11743. * Start date for the visible window
  11744. * {Number | Date | String} end
  11745. * End date for the visible window
  11746. */
  11747. Core.prototype.setOptions = function (options) {
  11748. if (options) {
  11749. // copy the known options
  11750. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation', 'clickToUse', 'dataAttributes', 'hiddenDates'];
  11751. util.selectiveExtend(fields, this.options, options);
  11752. if ('hiddenDates' in this.options) {
  11753. DateUtil.convertHiddenOptions(this.body, this.options.hiddenDates);
  11754. }
  11755. if ('clickToUse' in options) {
  11756. if (options.clickToUse) {
  11757. this.activator = new Activator(this.dom.root);
  11758. }
  11759. else {
  11760. if (this.activator) {
  11761. this.activator.destroy();
  11762. delete this.activator;
  11763. }
  11764. }
  11765. }
  11766. // enable/disable autoResize
  11767. this._initAutoResize();
  11768. }
  11769. // propagate options to all components
  11770. this.components.forEach(function (component) {
  11771. component.setOptions(options);
  11772. });
  11773. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  11774. if (options && options.order) {
  11775. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  11776. }
  11777. // redraw everything
  11778. this.redraw();
  11779. };
  11780. /**
  11781. * Returns true when the Timeline is active.
  11782. * @returns {boolean}
  11783. */
  11784. Core.prototype.isActive = function () {
  11785. return !this.activator || this.activator.active;
  11786. };
  11787. /**
  11788. * Destroy the Core, clean up all DOM elements and event listeners.
  11789. */
  11790. Core.prototype.destroy = function () {
  11791. // unbind datasets
  11792. this.clear();
  11793. // remove all event listeners
  11794. this.off();
  11795. // stop checking for changed size
  11796. this._stopAutoResize();
  11797. // remove from DOM
  11798. if (this.dom.root.parentNode) {
  11799. this.dom.root.parentNode.removeChild(this.dom.root);
  11800. }
  11801. this.dom = null;
  11802. // remove Activator
  11803. if (this.activator) {
  11804. this.activator.destroy();
  11805. delete this.activator;
  11806. }
  11807. // cleanup hammer touch events
  11808. for (var event in this.listeners) {
  11809. if (this.listeners.hasOwnProperty(event)) {
  11810. delete this.listeners[event];
  11811. }
  11812. }
  11813. this.listeners = null;
  11814. this.hammer = null;
  11815. // give all components the opportunity to cleanup
  11816. this.components.forEach(function (component) {
  11817. component.destroy();
  11818. });
  11819. this.body = null;
  11820. };
  11821. /**
  11822. * Set a custom time bar
  11823. * @param {Date} time
  11824. */
  11825. Core.prototype.setCustomTime = function (time) {
  11826. if (!this.customTime) {
  11827. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  11828. }
  11829. this.customTime.setCustomTime(time);
  11830. };
  11831. /**
  11832. * Retrieve the current custom time.
  11833. * @return {Date} customTime
  11834. */
  11835. Core.prototype.getCustomTime = function() {
  11836. if (!this.customTime) {
  11837. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  11838. }
  11839. return this.customTime.getCustomTime();
  11840. };
  11841. /**
  11842. * Get the id's of the currently visible items.
  11843. * @returns {Array} The ids of the visible items
  11844. */
  11845. Core.prototype.getVisibleItems = function() {
  11846. return this.itemSet && this.itemSet.getVisibleItems() || [];
  11847. };
  11848. /**
  11849. * Clear the Core. By Default, items, groups and options are cleared.
  11850. * Example usage:
  11851. *
  11852. * timeline.clear(); // clear items, groups, and options
  11853. * timeline.clear({options: true}); // clear options only
  11854. *
  11855. * @param {Object} [what] Optionally specify what to clear. By default:
  11856. * {items: true, groups: true, options: true}
  11857. */
  11858. Core.prototype.clear = function(what) {
  11859. // clear items
  11860. if (!what || what.items) {
  11861. this.setItems(null);
  11862. }
  11863. // clear groups
  11864. if (!what || what.groups) {
  11865. this.setGroups(null);
  11866. }
  11867. // clear options of timeline and of each of the components
  11868. if (!what || what.options) {
  11869. this.components.forEach(function (component) {
  11870. component.setOptions(component.defaultOptions);
  11871. });
  11872. this.setOptions(this.defaultOptions); // this will also do a redraw
  11873. }
  11874. };
  11875. /**
  11876. * Set Core window such that it fits all items
  11877. * @param {Object} [options] Available options:
  11878. * `animate: boolean | number`
  11879. * If true (default), the range is animated
  11880. * smoothly to the new window.
  11881. * If a number, the number is taken as duration
  11882. * for the animation. Default duration is 500 ms.
  11883. */
  11884. Core.prototype.fit = function(options) {
  11885. var range = this._getDataRange();
  11886. // skip range set if there is no start and end date
  11887. if (range.start === null && range.end === null) {
  11888. return;
  11889. }
  11890. var animate = (options && options.animate !== undefined) ? options.animate : true;
  11891. this.range.setRange(range.start, range.end, animate);
  11892. };
  11893. /**
  11894. * Calculate the data range of the items and applies a 5% window around it.
  11895. * @returns {{start: Date | null, end: Date | null}}
  11896. * @protected
  11897. */
  11898. Core.prototype._getDataRange = function() {
  11899. // apply the data range as range
  11900. var dataRange = this.getItemRange();
  11901. // add 5% space on both sides
  11902. var start = dataRange.min;
  11903. var end = dataRange.max;
  11904. if (start != null && end != null) {
  11905. var interval = (end.valueOf() - start.valueOf());
  11906. if (interval <= 0) {
  11907. // prevent an empty interval
  11908. interval = 24 * 60 * 60 * 1000; // 1 day
  11909. }
  11910. start = new Date(start.valueOf() - interval * 0.05);
  11911. end = new Date(end.valueOf() + interval * 0.05);
  11912. }
  11913. return {
  11914. start: start,
  11915. end: end
  11916. }
  11917. };
  11918. /**
  11919. * Set the visible window. Both parameters are optional, you can change only
  11920. * start or only end. Syntax:
  11921. *
  11922. * TimeLine.setWindow(start, end)
  11923. * TimeLine.setWindow(range)
  11924. *
  11925. * Where start and end can be a Date, number, or string, and range is an
  11926. * object with properties start and end.
  11927. *
  11928. * @param {Date | Number | String | Object} [start] Start date of visible window
  11929. * @param {Date | Number | String} [end] End date of visible window
  11930. * @param {Object} [options] Available options:
  11931. * `animate: boolean | number`
  11932. * If true (default), the range is animated
  11933. * smoothly to the new window.
  11934. * If a number, the number is taken as duration
  11935. * for the animation. Default duration is 500 ms.
  11936. */
  11937. Core.prototype.setWindow = function(start, end, options) {
  11938. var animate = (options && options.animate !== undefined) ? options.animate : true;
  11939. if (arguments.length == 1) {
  11940. var range = arguments[0];
  11941. this.range.setRange(range.start, range.end, animate);
  11942. }
  11943. else {
  11944. this.range.setRange(start, end, animate);
  11945. }
  11946. };
  11947. /**
  11948. * Move the window such that given time is centered on screen.
  11949. * @param {Date | Number | String} time
  11950. * @param {Object} [options] Available options:
  11951. * `animate: boolean | number`
  11952. * If true (default), the range is animated
  11953. * smoothly to the new window.
  11954. * If a number, the number is taken as duration
  11955. * for the animation. Default duration is 500 ms.
  11956. */
  11957. Core.prototype.moveTo = function(time, options) {
  11958. var interval = this.range.end - this.range.start;
  11959. var t = util.convert(time, 'Date').valueOf();
  11960. var start = t - interval / 2;
  11961. var end = t + interval / 2;
  11962. var animate = (options && options.animate !== undefined) ? options.animate : true;
  11963. this.range.setRange(start, end, animate);
  11964. };
  11965. /**
  11966. * Get the visible window
  11967. * @return {{start: Date, end: Date}} Visible range
  11968. */
  11969. Core.prototype.getWindow = function() {
  11970. var range = this.range.getRange();
  11971. return {
  11972. start: new Date(range.start),
  11973. end: new Date(range.end)
  11974. };
  11975. };
  11976. /**
  11977. * Force a redraw of the Core. Can be useful to manually redraw when
  11978. * option autoResize=false
  11979. */
  11980. Core.prototype.redraw = function() {
  11981. var resized = false;
  11982. var options = this.options;
  11983. var props = this.props;
  11984. var dom = this.dom;
  11985. if (!dom) return; // when destroyed
  11986. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  11987. // update class names
  11988. if (options.orientation == 'top') {
  11989. util.addClassName(dom.root, 'top');
  11990. util.removeClassName(dom.root, 'bottom');
  11991. }
  11992. else {
  11993. util.removeClassName(dom.root, 'top');
  11994. util.addClassName(dom.root, 'bottom');
  11995. }
  11996. // update root width and height options
  11997. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  11998. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  11999. dom.root.style.width = util.option.asSize(options.width, '');
  12000. // calculate border widths
  12001. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  12002. props.border.right = props.border.left;
  12003. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  12004. props.border.bottom = props.border.top;
  12005. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  12006. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  12007. // workaround for a bug in IE: the clientWidth of an element with
  12008. // a height:0px and overflow:hidden is not calculated and always has value 0
  12009. if (dom.centerContainer.clientHeight === 0) {
  12010. props.border.left = props.border.top;
  12011. props.border.right = props.border.left;
  12012. }
  12013. if (dom.root.clientHeight === 0) {
  12014. borderRootWidth = borderRootHeight;
  12015. }
  12016. // calculate the heights. If any of the side panels is empty, we set the height to
  12017. // minus the border width, such that the border will be invisible
  12018. props.center.height = dom.center.offsetHeight;
  12019. props.left.height = dom.left.offsetHeight;
  12020. props.right.height = dom.right.offsetHeight;
  12021. props.top.height = dom.top.clientHeight || -props.border.top;
  12022. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  12023. // TODO: compensate borders when any of the panels is empty.
  12024. // apply auto height
  12025. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  12026. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  12027. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  12028. borderRootHeight + props.border.top + props.border.bottom;
  12029. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  12030. // calculate heights of the content panels
  12031. props.root.height = dom.root.offsetHeight;
  12032. props.background.height = props.root.height - borderRootHeight;
  12033. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  12034. borderRootHeight;
  12035. props.centerContainer.height = containerHeight;
  12036. props.leftContainer.height = containerHeight;
  12037. props.rightContainer.height = props.leftContainer.height;
  12038. // calculate the widths of the panels
  12039. props.root.width = dom.root.offsetWidth;
  12040. props.background.width = props.root.width - borderRootWidth;
  12041. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  12042. props.leftContainer.width = props.left.width;
  12043. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  12044. props.rightContainer.width = props.right.width;
  12045. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  12046. props.center.width = centerWidth;
  12047. props.centerContainer.width = centerWidth;
  12048. props.top.width = centerWidth;
  12049. props.bottom.width = centerWidth;
  12050. // resize the panels
  12051. dom.background.style.height = props.background.height + 'px';
  12052. dom.backgroundVertical.style.height = props.background.height + 'px';
  12053. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  12054. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  12055. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  12056. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  12057. dom.background.style.width = props.background.width + 'px';
  12058. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  12059. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  12060. dom.centerContainer.style.width = props.center.width + 'px';
  12061. dom.top.style.width = props.top.width + 'px';
  12062. dom.bottom.style.width = props.bottom.width + 'px';
  12063. // reposition the panels
  12064. dom.background.style.left = '0';
  12065. dom.background.style.top = '0';
  12066. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  12067. dom.backgroundVertical.style.top = '0';
  12068. dom.backgroundHorizontal.style.left = '0';
  12069. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  12070. dom.centerContainer.style.left = props.left.width + 'px';
  12071. dom.centerContainer.style.top = props.top.height + 'px';
  12072. dom.leftContainer.style.left = '0';
  12073. dom.leftContainer.style.top = props.top.height + 'px';
  12074. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  12075. dom.rightContainer.style.top = props.top.height + 'px';
  12076. dom.top.style.left = props.left.width + 'px';
  12077. dom.top.style.top = '0';
  12078. dom.bottom.style.left = props.left.width + 'px';
  12079. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  12080. // update the scrollTop, feasible range for the offset can be changed
  12081. // when the height of the Core or of the contents of the center changed
  12082. this._updateScrollTop();
  12083. // reposition the scrollable contents
  12084. var offset = this.props.scrollTop;
  12085. if (options.orientation == 'bottom') {
  12086. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  12087. this.props.border.top - this.props.border.bottom, 0);
  12088. }
  12089. dom.center.style.left = '0';
  12090. dom.center.style.top = offset + 'px';
  12091. dom.left.style.left = '0';
  12092. dom.left.style.top = offset + 'px';
  12093. dom.right.style.left = '0';
  12094. dom.right.style.top = offset + 'px';
  12095. // show shadows when vertical scrolling is available
  12096. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  12097. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  12098. dom.shadowTop.style.visibility = visibilityTop;
  12099. dom.shadowBottom.style.visibility = visibilityBottom;
  12100. dom.shadowTopLeft.style.visibility = visibilityTop;
  12101. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  12102. dom.shadowTopRight.style.visibility = visibilityTop;
  12103. dom.shadowBottomRight.style.visibility = visibilityBottom;
  12104. // redraw all components
  12105. this.components.forEach(function (component) {
  12106. resized = component.redraw() || resized;
  12107. });
  12108. if (resized) {
  12109. // keep repainting until all sizes are settled
  12110. var MAX_REDRAWS = 3; // maximum number of consecutive redraws
  12111. if (this.redrawCount < MAX_REDRAWS) {
  12112. this.redrawCount++;
  12113. this.redraw();
  12114. }
  12115. else {
  12116. console.log('WARNING: infinite loop in redraw?')
  12117. }
  12118. this.redrawCount = 0;
  12119. }
  12120. this.emit("finishedRedraw");
  12121. };
  12122. // TODO: deprecated since version 1.1.0, remove some day
  12123. Core.prototype.repaint = function () {
  12124. throw new Error('Function repaint is deprecated. Use redraw instead.');
  12125. };
  12126. /**
  12127. * Set a current time. This can be used for example to ensure that a client's
  12128. * time is synchronized with a shared server time.
  12129. * Only applicable when option `showCurrentTime` is true.
  12130. * @param {Date | String | Number} time A Date, unix timestamp, or
  12131. * ISO date string.
  12132. */
  12133. Core.prototype.setCurrentTime = function(time) {
  12134. if (!this.currentTime) {
  12135. throw new Error('Option showCurrentTime must be true');
  12136. }
  12137. this.currentTime.setCurrentTime(time);
  12138. };
  12139. /**
  12140. * Get the current time.
  12141. * Only applicable when option `showCurrentTime` is true.
  12142. * @return {Date} Returns the current time.
  12143. */
  12144. Core.prototype.getCurrentTime = function() {
  12145. if (!this.currentTime) {
  12146. throw new Error('Option showCurrentTime must be true');
  12147. }
  12148. return this.currentTime.getCurrentTime();
  12149. };
  12150. /**
  12151. * Convert a position on screen (pixels) to a datetime
  12152. * @param {int} x Position on the screen in pixels
  12153. * @return {Date} time The datetime the corresponds with given position x
  12154. * @private
  12155. */
  12156. // TODO: move this function to Range
  12157. Core.prototype._toTime = function(x) {
  12158. return DateUtil.toTime(this, x, this.props.center.width);
  12159. };
  12160. /**
  12161. * Convert a position on the global screen (pixels) to a datetime
  12162. * @param {int} x Position on the screen in pixels
  12163. * @return {Date} time The datetime the corresponds with given position x
  12164. * @private
  12165. */
  12166. // TODO: move this function to Range
  12167. Core.prototype._toGlobalTime = function(x) {
  12168. return DateUtil.toTime(this, x, this.props.root.width);
  12169. //var conversion = this.range.conversion(this.props.root.width);
  12170. //return new Date(x / conversion.scale + conversion.offset);
  12171. };
  12172. /**
  12173. * Convert a datetime (Date object) into a position on the screen
  12174. * @param {Date} time A date
  12175. * @return {int} x The position on the screen in pixels which corresponds
  12176. * with the given date.
  12177. * @private
  12178. */
  12179. // TODO: move this function to Range
  12180. Core.prototype._toScreen = function(time) {
  12181. return DateUtil.toScreen(this, time, this.props.center.width);
  12182. };
  12183. /**
  12184. * Convert a datetime (Date object) into a position on the root
  12185. * This is used to get the pixel density estimate for the screen, not the center panel
  12186. * @param {Date} time A date
  12187. * @return {int} x The position on root in pixels which corresponds
  12188. * with the given date.
  12189. * @private
  12190. */
  12191. // TODO: move this function to Range
  12192. Core.prototype._toGlobalScreen = function(time) {
  12193. return DateUtil.toScreen(this, time, this.props.root.width);
  12194. //var conversion = this.range.conversion(this.props.root.width);
  12195. //return (time.valueOf() - conversion.offset) * conversion.scale;
  12196. };
  12197. /**
  12198. * Initialize watching when option autoResize is true
  12199. * @private
  12200. */
  12201. Core.prototype._initAutoResize = function () {
  12202. if (this.options.autoResize == true) {
  12203. this._startAutoResize();
  12204. }
  12205. else {
  12206. this._stopAutoResize();
  12207. }
  12208. };
  12209. /**
  12210. * Watch for changes in the size of the container. On resize, the Panel will
  12211. * automatically redraw itself.
  12212. * @private
  12213. */
  12214. Core.prototype._startAutoResize = function () {
  12215. var me = this;
  12216. this._stopAutoResize();
  12217. this._onResize = function() {
  12218. if (me.options.autoResize != true) {
  12219. // stop watching when the option autoResize is changed to false
  12220. me._stopAutoResize();
  12221. return;
  12222. }
  12223. if (me.dom.root) {
  12224. // check whether the frame is resized
  12225. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  12226. // IE does not restore the clientWidth from 0 to the actual width after
  12227. // changing the timeline's container display style from none to visible
  12228. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  12229. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  12230. me.props.lastWidth = me.dom.root.offsetWidth;
  12231. me.props.lastHeight = me.dom.root.offsetHeight;
  12232. me.emit('change');
  12233. }
  12234. }
  12235. };
  12236. // add event listener to window resize
  12237. util.addEventListener(window, 'resize', this._onResize);
  12238. this.watchTimer = setInterval(this._onResize, 1000);
  12239. };
  12240. /**
  12241. * Stop watching for a resize of the frame.
  12242. * @private
  12243. */
  12244. Core.prototype._stopAutoResize = function () {
  12245. if (this.watchTimer) {
  12246. clearInterval(this.watchTimer);
  12247. this.watchTimer = undefined;
  12248. }
  12249. // remove event listener on window.resize
  12250. util.removeEventListener(window, 'resize', this._onResize);
  12251. this._onResize = null;
  12252. };
  12253. /**
  12254. * Start moving the timeline vertically
  12255. * @param {Event} event
  12256. * @private
  12257. */
  12258. Core.prototype._onTouch = function (event) {
  12259. this.touch.allowDragging = true;
  12260. };
  12261. /**
  12262. * Start moving the timeline vertically
  12263. * @param {Event} event
  12264. * @private
  12265. */
  12266. Core.prototype._onPinch = function (event) {
  12267. this.touch.allowDragging = false;
  12268. };
  12269. /**
  12270. * Start moving the timeline vertically
  12271. * @param {Event} event
  12272. * @private
  12273. */
  12274. Core.prototype._onDragStart = function (event) {
  12275. this.touch.initialScrollTop = this.props.scrollTop;
  12276. };
  12277. /**
  12278. * Move the timeline vertically
  12279. * @param {Event} event
  12280. * @private
  12281. */
  12282. Core.prototype._onDrag = function (event) {
  12283. // refuse to drag when we where pinching to prevent the timeline make a jump
  12284. // when releasing the fingers in opposite order from the touch screen
  12285. if (!this.touch.allowDragging) return;
  12286. var delta = event.gesture.deltaY;
  12287. var oldScrollTop = this._getScrollTop();
  12288. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  12289. if (newScrollTop != oldScrollTop) {
  12290. this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already
  12291. this.emit("verticalDrag");
  12292. }
  12293. };
  12294. /**
  12295. * Apply a scrollTop
  12296. * @param {Number} scrollTop
  12297. * @returns {Number} scrollTop Returns the applied scrollTop
  12298. * @private
  12299. */
  12300. Core.prototype._setScrollTop = function (scrollTop) {
  12301. this.props.scrollTop = scrollTop;
  12302. this._updateScrollTop();
  12303. return this.props.scrollTop;
  12304. };
  12305. /**
  12306. * Update the current scrollTop when the height of the containers has been changed
  12307. * @returns {Number} scrollTop Returns the applied scrollTop
  12308. * @private
  12309. */
  12310. Core.prototype._updateScrollTop = function () {
  12311. // recalculate the scrollTopMin
  12312. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  12313. if (scrollTopMin != this.props.scrollTopMin) {
  12314. // in case of bottom orientation, change the scrollTop such that the contents
  12315. // do not move relative to the time axis at the bottom
  12316. if (this.options.orientation == 'bottom') {
  12317. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  12318. }
  12319. this.props.scrollTopMin = scrollTopMin;
  12320. }
  12321. // limit the scrollTop to the feasible scroll range
  12322. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  12323. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  12324. return this.props.scrollTop;
  12325. };
  12326. /**
  12327. * Get the current scrollTop
  12328. * @returns {number} scrollTop
  12329. * @private
  12330. */
  12331. Core.prototype._getScrollTop = function () {
  12332. return this.props.scrollTop;
  12333. };
  12334. module.exports = Core;
  12335. /***/ },
  12336. /* 26 */
  12337. /***/ function(module, exports, __webpack_require__) {
  12338. var Hammer = __webpack_require__(19);
  12339. var util = __webpack_require__(1);
  12340. var DataSet = __webpack_require__(7);
  12341. var DataView = __webpack_require__(9);
  12342. var Component = __webpack_require__(23);
  12343. var Group = __webpack_require__(27);
  12344. var BackgroundGroup = __webpack_require__(31);
  12345. var BoxItem = __webpack_require__(32);
  12346. var PointItem = __webpack_require__(33);
  12347. var RangeItem = __webpack_require__(29);
  12348. var BackgroundItem = __webpack_require__(34);
  12349. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  12350. var BACKGROUND = '__background__'; // reserved group id for background items without group
  12351. /**
  12352. * An ItemSet holds a set of items and ranges which can be displayed in a
  12353. * range. The width is determined by the parent of the ItemSet, and the height
  12354. * is determined by the size of the items.
  12355. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  12356. * @param {Object} [options] See ItemSet.setOptions for the available options.
  12357. * @constructor ItemSet
  12358. * @extends Component
  12359. */
  12360. function ItemSet(body, options) {
  12361. this.body = body;
  12362. this.defaultOptions = {
  12363. type: null, // 'box', 'point', 'range', 'background'
  12364. orientation: 'bottom', // 'top' or 'bottom'
  12365. align: 'auto', // alignment of box items
  12366. stack: true,
  12367. groupOrder: null,
  12368. selectable: true,
  12369. editable: {
  12370. updateTime: false,
  12371. updateGroup: false,
  12372. add: false,
  12373. remove: false
  12374. },
  12375. onAdd: function (item, callback) {
  12376. callback(item);
  12377. },
  12378. onUpdate: function (item, callback) {
  12379. callback(item);
  12380. },
  12381. onMove: function (item, callback) {
  12382. callback(item);
  12383. },
  12384. onRemove: function (item, callback) {
  12385. callback(item);
  12386. },
  12387. onMoving: function (item, callback) {
  12388. callback(item);
  12389. },
  12390. margin: {
  12391. item: {
  12392. horizontal: 10,
  12393. vertical: 10
  12394. },
  12395. axis: 20
  12396. },
  12397. padding: 5
  12398. };
  12399. // options is shared by this ItemSet and all its items
  12400. this.options = util.extend({}, this.defaultOptions);
  12401. // options for getting items from the DataSet with the correct type
  12402. this.itemOptions = {
  12403. type: {start: 'Date', end: 'Date'}
  12404. };
  12405. this.conversion = {
  12406. toScreen: body.util.toScreen,
  12407. toTime: body.util.toTime
  12408. };
  12409. this.dom = {};
  12410. this.props = {};
  12411. this.hammer = null;
  12412. var me = this;
  12413. this.itemsData = null; // DataSet
  12414. this.groupsData = null; // DataSet
  12415. // listeners for the DataSet of the items
  12416. this.itemListeners = {
  12417. 'add': function (event, params, senderId) {
  12418. me._onAdd(params.items);
  12419. },
  12420. 'update': function (event, params, senderId) {
  12421. me._onUpdate(params.items);
  12422. },
  12423. 'remove': function (event, params, senderId) {
  12424. me._onRemove(params.items);
  12425. }
  12426. };
  12427. // listeners for the DataSet of the groups
  12428. this.groupListeners = {
  12429. 'add': function (event, params, senderId) {
  12430. me._onAddGroups(params.items);
  12431. },
  12432. 'update': function (event, params, senderId) {
  12433. me._onUpdateGroups(params.items);
  12434. },
  12435. 'remove': function (event, params, senderId) {
  12436. me._onRemoveGroups(params.items);
  12437. }
  12438. };
  12439. this.items = {}; // object with an Item for every data item
  12440. this.groups = {}; // Group object for every group
  12441. this.groupIds = [];
  12442. this.selection = []; // list with the ids of all selected nodes
  12443. this.stackDirty = true; // if true, all items will be restacked on next redraw
  12444. this.touchParams = {}; // stores properties while dragging
  12445. // create the HTML DOM
  12446. this._create();
  12447. this.setOptions(options);
  12448. }
  12449. ItemSet.prototype = new Component();
  12450. // available item types will be registered here
  12451. ItemSet.types = {
  12452. background: BackgroundItem,
  12453. box: BoxItem,
  12454. range: RangeItem,
  12455. point: PointItem
  12456. };
  12457. /**
  12458. * Create the HTML DOM for the ItemSet
  12459. */
  12460. ItemSet.prototype._create = function(){
  12461. var frame = document.createElement('div');
  12462. frame.className = 'itemset';
  12463. frame['timeline-itemset'] = this;
  12464. this.dom.frame = frame;
  12465. // create background panel
  12466. var background = document.createElement('div');
  12467. background.className = 'background';
  12468. frame.appendChild(background);
  12469. this.dom.background = background;
  12470. // create foreground panel
  12471. var foreground = document.createElement('div');
  12472. foreground.className = 'foreground';
  12473. frame.appendChild(foreground);
  12474. this.dom.foreground = foreground;
  12475. // create axis panel
  12476. var axis = document.createElement('div');
  12477. axis.className = 'axis';
  12478. this.dom.axis = axis;
  12479. // create labelset
  12480. var labelSet = document.createElement('div');
  12481. labelSet.className = 'labelset';
  12482. this.dom.labelSet = labelSet;
  12483. // create ungrouped Group
  12484. this._updateUngrouped();
  12485. // create background Group
  12486. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  12487. backgroundGroup.show();
  12488. this.groups[BACKGROUND] = backgroundGroup;
  12489. // attach event listeners
  12490. // Note: we bind to the centerContainer for the case where the height
  12491. // of the center container is larger than of the ItemSet, so we
  12492. // can click in the empty area to create a new item or deselect an item.
  12493. this.hammer = Hammer(this.body.dom.centerContainer, {
  12494. preventDefault: true
  12495. });
  12496. // drag items when selected
  12497. this.hammer.on('touch', this._onTouch.bind(this));
  12498. this.hammer.on('dragstart', this._onDragStart.bind(this));
  12499. this.hammer.on('drag', this._onDrag.bind(this));
  12500. this.hammer.on('dragend', this._onDragEnd.bind(this));
  12501. // single select (or unselect) when tapping an item
  12502. this.hammer.on('tap', this._onSelectItem.bind(this));
  12503. // multi select when holding mouse/touch, or on ctrl+click
  12504. this.hammer.on('hold', this._onMultiSelectItem.bind(this));
  12505. // add item on doubletap
  12506. this.hammer.on('doubletap', this._onAddItem.bind(this));
  12507. // attach to the DOM
  12508. this.show();
  12509. };
  12510. /**
  12511. * Set options for the ItemSet. Existing options will be extended/overwritten.
  12512. * @param {Object} [options] The following options are available:
  12513. * {String} type
  12514. * Default type for the items. Choose from 'box'
  12515. * (default), 'point', 'range', or 'background'.
  12516. * The default style can be overwritten by
  12517. * individual items.
  12518. * {String} align
  12519. * Alignment for the items, only applicable for
  12520. * BoxItem. Choose 'center' (default), 'left', or
  12521. * 'right'.
  12522. * {String} orientation
  12523. * Orientation of the item set. Choose 'top' or
  12524. * 'bottom' (default).
  12525. * {Function} groupOrder
  12526. * A sorting function for ordering groups
  12527. * {Boolean} stack
  12528. * If true (deafult), items will be stacked on
  12529. * top of each other.
  12530. * {Number} margin.axis
  12531. * Margin between the axis and the items in pixels.
  12532. * Default is 20.
  12533. * {Number} margin.item.horizontal
  12534. * Horizontal margin between items in pixels.
  12535. * Default is 10.
  12536. * {Number} margin.item.vertical
  12537. * Vertical Margin between items in pixels.
  12538. * Default is 10.
  12539. * {Number} margin.item
  12540. * Margin between items in pixels in both horizontal
  12541. * and vertical direction. Default is 10.
  12542. * {Number} margin
  12543. * Set margin for both axis and items in pixels.
  12544. * {Number} padding
  12545. * Padding of the contents of an item in pixels.
  12546. * Must correspond with the items css. Default is 5.
  12547. * {Boolean} selectable
  12548. * If true (default), items can be selected.
  12549. * {Boolean} editable
  12550. * Set all editable options to true or false
  12551. * {Boolean} editable.updateTime
  12552. * Allow dragging an item to an other moment in time
  12553. * {Boolean} editable.updateGroup
  12554. * Allow dragging an item to an other group
  12555. * {Boolean} editable.add
  12556. * Allow creating new items on double tap
  12557. * {Boolean} editable.remove
  12558. * Allow removing items by clicking the delete button
  12559. * top right of a selected item.
  12560. * {Function(item: Item, callback: Function)} onAdd
  12561. * Callback function triggered when an item is about to be added:
  12562. * when the user double taps an empty space in the Timeline.
  12563. * {Function(item: Item, callback: Function)} onUpdate
  12564. * Callback function fired when an item is about to be updated.
  12565. * This function typically has to show a dialog where the user
  12566. * change the item. If not implemented, nothing happens.
  12567. * {Function(item: Item, callback: Function)} onMove
  12568. * Fired when an item has been moved. If not implemented,
  12569. * the move action will be accepted.
  12570. * {Function(item: Item, callback: Function)} onRemove
  12571. * Fired when an item is about to be deleted.
  12572. * If not implemented, the item will be always removed.
  12573. */
  12574. ItemSet.prototype.setOptions = function(options) {
  12575. if (options) {
  12576. // copy all options that we know
  12577. var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder', 'dataAttributes', 'template','hide'];
  12578. util.selectiveExtend(fields, this.options, options);
  12579. if ('margin' in options) {
  12580. if (typeof options.margin === 'number') {
  12581. this.options.margin.axis = options.margin;
  12582. this.options.margin.item.horizontal = options.margin;
  12583. this.options.margin.item.vertical = options.margin;
  12584. }
  12585. else if (typeof options.margin === 'object') {
  12586. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  12587. if ('item' in options.margin) {
  12588. if (typeof options.margin.item === 'number') {
  12589. this.options.margin.item.horizontal = options.margin.item;
  12590. this.options.margin.item.vertical = options.margin.item;
  12591. }
  12592. else if (typeof options.margin.item === 'object') {
  12593. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  12594. }
  12595. }
  12596. }
  12597. }
  12598. if ('editable' in options) {
  12599. if (typeof options.editable === 'boolean') {
  12600. this.options.editable.updateTime = options.editable;
  12601. this.options.editable.updateGroup = options.editable;
  12602. this.options.editable.add = options.editable;
  12603. this.options.editable.remove = options.editable;
  12604. }
  12605. else if (typeof options.editable === 'object') {
  12606. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
  12607. }
  12608. }
  12609. // callback functions
  12610. var addCallback = (function (name) {
  12611. var fn = options[name];
  12612. if (fn) {
  12613. if (!(fn instanceof Function)) {
  12614. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  12615. }
  12616. this.options[name] = fn;
  12617. }
  12618. }).bind(this);
  12619. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback);
  12620. // force the itemSet to refresh: options like orientation and margins may be changed
  12621. this.markDirty();
  12622. }
  12623. };
  12624. /**
  12625. * Mark the ItemSet dirty so it will refresh everything with next redraw
  12626. */
  12627. ItemSet.prototype.markDirty = function() {
  12628. this.groupIds = [];
  12629. this.stackDirty = true;
  12630. };
  12631. /**
  12632. * Destroy the ItemSet
  12633. */
  12634. ItemSet.prototype.destroy = function() {
  12635. this.hide();
  12636. this.setItems(null);
  12637. this.setGroups(null);
  12638. this.hammer = null;
  12639. this.body = null;
  12640. this.conversion = null;
  12641. };
  12642. /**
  12643. * Hide the component from the DOM
  12644. */
  12645. ItemSet.prototype.hide = function() {
  12646. // remove the frame containing the items
  12647. if (this.dom.frame.parentNode) {
  12648. this.dom.frame.parentNode.removeChild(this.dom.frame);
  12649. }
  12650. // remove the axis with dots
  12651. if (this.dom.axis.parentNode) {
  12652. this.dom.axis.parentNode.removeChild(this.dom.axis);
  12653. }
  12654. // remove the labelset containing all group labels
  12655. if (this.dom.labelSet.parentNode) {
  12656. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  12657. }
  12658. };
  12659. /**
  12660. * Show the component in the DOM (when not already visible).
  12661. * @return {Boolean} changed
  12662. */
  12663. ItemSet.prototype.show = function() {
  12664. // show frame containing the items
  12665. if (!this.dom.frame.parentNode) {
  12666. this.body.dom.center.appendChild(this.dom.frame);
  12667. }
  12668. // show axis with dots
  12669. if (!this.dom.axis.parentNode) {
  12670. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  12671. }
  12672. // show labelset containing labels
  12673. if (!this.dom.labelSet.parentNode) {
  12674. this.body.dom.left.appendChild(this.dom.labelSet);
  12675. }
  12676. };
  12677. /**
  12678. * Set selected items by their id. Replaces the current selection
  12679. * Unknown id's are silently ignored.
  12680. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  12681. * selected, or a single item id. If ids is undefined
  12682. * or an empty array, all items will be unselected.
  12683. */
  12684. ItemSet.prototype.setSelection = function(ids) {
  12685. var i, ii, id, item;
  12686. if (ids == undefined) ids = [];
  12687. if (!Array.isArray(ids)) ids = [ids];
  12688. // unselect currently selected items
  12689. for (i = 0, ii = this.selection.length; i < ii; i++) {
  12690. id = this.selection[i];
  12691. item = this.items[id];
  12692. if (item) item.unselect();
  12693. }
  12694. // select items
  12695. this.selection = [];
  12696. for (i = 0, ii = ids.length; i < ii; i++) {
  12697. id = ids[i];
  12698. item = this.items[id];
  12699. if (item) {
  12700. this.selection.push(id);
  12701. item.select();
  12702. }
  12703. }
  12704. };
  12705. /**
  12706. * Get the selected items by their id
  12707. * @return {Array} ids The ids of the selected items
  12708. */
  12709. ItemSet.prototype.getSelection = function() {
  12710. return this.selection.concat([]);
  12711. };
  12712. /**
  12713. * Get the id's of the currently visible items.
  12714. * @returns {Array} The ids of the visible items
  12715. */
  12716. ItemSet.prototype.getVisibleItems = function() {
  12717. var range = this.body.range.getRange();
  12718. var left = this.body.util.toScreen(range.start);
  12719. var right = this.body.util.toScreen(range.end);
  12720. var ids = [];
  12721. for (var groupId in this.groups) {
  12722. if (this.groups.hasOwnProperty(groupId)) {
  12723. var group = this.groups[groupId];
  12724. var rawVisibleItems = group.visibleItems;
  12725. // filter the "raw" set with visibleItems into a set which is really
  12726. // visible by pixels
  12727. for (var i = 0; i < rawVisibleItems.length; i++) {
  12728. var item = rawVisibleItems[i];
  12729. // TODO: also check whether visible vertically
  12730. if ((item.left < right) && (item.left + item.width > left)) {
  12731. ids.push(item.id);
  12732. }
  12733. }
  12734. }
  12735. }
  12736. return ids;
  12737. };
  12738. /**
  12739. * Deselect a selected item
  12740. * @param {String | Number} id
  12741. * @private
  12742. */
  12743. ItemSet.prototype._deselect = function(id) {
  12744. var selection = this.selection;
  12745. for (var i = 0, ii = selection.length; i < ii; i++) {
  12746. if (selection[i] == id) { // non-strict comparison!
  12747. selection.splice(i, 1);
  12748. break;
  12749. }
  12750. }
  12751. };
  12752. /**
  12753. * Repaint the component
  12754. * @return {boolean} Returns true if the component is resized
  12755. */
  12756. ItemSet.prototype.redraw = function() {
  12757. var margin = this.options.margin,
  12758. range = this.body.range,
  12759. asSize = util.option.asSize,
  12760. options = this.options,
  12761. orientation = options.orientation,
  12762. resized = false,
  12763. frame = this.dom.frame,
  12764. editable = options.editable.updateTime || options.editable.updateGroup;
  12765. // recalculate absolute position (before redrawing groups)
  12766. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  12767. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  12768. // update class name
  12769. frame.className = 'itemset' + (editable ? ' editable' : '');
  12770. // reorder the groups (if needed)
  12771. resized = this._orderGroups() || resized;
  12772. // check whether zoomed (in that case we need to re-stack everything)
  12773. // TODO: would be nicer to get this as a trigger from Range
  12774. var visibleInterval = range.end - range.start;
  12775. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  12776. if (zoomed) this.stackDirty = true;
  12777. this.lastVisibleInterval = visibleInterval;
  12778. this.props.lastWidth = this.props.width;
  12779. var restack = this.stackDirty;
  12780. var firstGroup = this._firstGroup();
  12781. var firstMargin = {
  12782. item: margin.item,
  12783. axis: margin.axis
  12784. };
  12785. var nonFirstMargin = {
  12786. item: margin.item,
  12787. axis: margin.item.vertical / 2
  12788. };
  12789. var height = 0;
  12790. var minHeight = margin.axis + margin.item.vertical;
  12791. // redraw the background group
  12792. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  12793. // redraw all regular groups
  12794. util.forEach(this.groups, function (group) {
  12795. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  12796. var groupResized = group.redraw(range, groupMargin, restack);
  12797. resized = groupResized || resized;
  12798. height += group.height;
  12799. });
  12800. height = Math.max(height, minHeight);
  12801. this.stackDirty = false;
  12802. // update frame height
  12803. frame.style.height = asSize(height);
  12804. // calculate actual size
  12805. this.props.width = frame.offsetWidth;
  12806. this.props.height = height;
  12807. // reposition axis
  12808. this.dom.axis.style.top = asSize((orientation == 'top') ?
  12809. (this.body.domProps.top.height + this.body.domProps.border.top) :
  12810. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  12811. this.dom.axis.style.left = '0';
  12812. // check if this component is resized
  12813. resized = this._isResized() || resized;
  12814. return resized;
  12815. };
  12816. /**
  12817. * Get the first group, aligned with the axis
  12818. * @return {Group | null} firstGroup
  12819. * @private
  12820. */
  12821. ItemSet.prototype._firstGroup = function() {
  12822. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  12823. var firstGroupId = this.groupIds[firstGroupIndex];
  12824. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  12825. return firstGroup || null;
  12826. };
  12827. /**
  12828. * Create or delete the group holding all ungrouped items. This group is used when
  12829. * there are no groups specified.
  12830. * @protected
  12831. */
  12832. ItemSet.prototype._updateUngrouped = function() {
  12833. var ungrouped = this.groups[UNGROUPED];
  12834. var background = this.groups[BACKGROUND];
  12835. var item, itemId;
  12836. if (this.groupsData) {
  12837. // remove the group holding all ungrouped items
  12838. if (ungrouped) {
  12839. ungrouped.hide();
  12840. delete this.groups[UNGROUPED];
  12841. for (itemId in this.items) {
  12842. if (this.items.hasOwnProperty(itemId)) {
  12843. item = this.items[itemId];
  12844. item.parent && item.parent.remove(item);
  12845. var groupId = this._getGroupId(item.data);
  12846. var group = this.groups[groupId];
  12847. group && group.add(item) || item.hide();
  12848. }
  12849. }
  12850. }
  12851. }
  12852. else {
  12853. // create a group holding all (unfiltered) items
  12854. if (!ungrouped) {
  12855. var id = null;
  12856. var data = null;
  12857. ungrouped = new Group(id, data, this);
  12858. this.groups[UNGROUPED] = ungrouped;
  12859. for (itemId in this.items) {
  12860. if (this.items.hasOwnProperty(itemId)) {
  12861. item = this.items[itemId];
  12862. ungrouped.add(item);
  12863. }
  12864. }
  12865. ungrouped.show();
  12866. }
  12867. }
  12868. };
  12869. /**
  12870. * Get the element for the labelset
  12871. * @return {HTMLElement} labelSet
  12872. */
  12873. ItemSet.prototype.getLabelSet = function() {
  12874. return this.dom.labelSet;
  12875. };
  12876. /**
  12877. * Set items
  12878. * @param {vis.DataSet | null} items
  12879. */
  12880. ItemSet.prototype.setItems = function(items) {
  12881. var me = this,
  12882. ids,
  12883. oldItemsData = this.itemsData;
  12884. // replace the dataset
  12885. if (!items) {
  12886. this.itemsData = null;
  12887. }
  12888. else if (items instanceof DataSet || items instanceof DataView) {
  12889. this.itemsData = items;
  12890. }
  12891. else {
  12892. throw new TypeError('Data must be an instance of DataSet or DataView');
  12893. }
  12894. if (oldItemsData) {
  12895. // unsubscribe from old dataset
  12896. util.forEach(this.itemListeners, function (callback, event) {
  12897. oldItemsData.off(event, callback);
  12898. });
  12899. // remove all drawn items
  12900. ids = oldItemsData.getIds();
  12901. this._onRemove(ids);
  12902. }
  12903. if (this.itemsData) {
  12904. // subscribe to new dataset
  12905. var id = this.id;
  12906. util.forEach(this.itemListeners, function (callback, event) {
  12907. me.itemsData.on(event, callback, id);
  12908. });
  12909. // add all new items
  12910. ids = this.itemsData.getIds();
  12911. this._onAdd(ids);
  12912. // update the group holding all ungrouped items
  12913. this._updateUngrouped();
  12914. }
  12915. };
  12916. /**
  12917. * Get the current items
  12918. * @returns {vis.DataSet | null}
  12919. */
  12920. ItemSet.prototype.getItems = function() {
  12921. return this.itemsData;
  12922. };
  12923. /**
  12924. * Set groups
  12925. * @param {vis.DataSet} groups
  12926. */
  12927. ItemSet.prototype.setGroups = function(groups) {
  12928. var me = this,
  12929. ids;
  12930. // unsubscribe from current dataset
  12931. if (this.groupsData) {
  12932. util.forEach(this.groupListeners, function (callback, event) {
  12933. me.groupsData.unsubscribe(event, callback);
  12934. });
  12935. // remove all drawn groups
  12936. ids = this.groupsData.getIds();
  12937. this.groupsData = null;
  12938. this._onRemoveGroups(ids); // note: this will cause a redraw
  12939. }
  12940. // replace the dataset
  12941. if (!groups) {
  12942. this.groupsData = null;
  12943. }
  12944. else if (groups instanceof DataSet || groups instanceof DataView) {
  12945. this.groupsData = groups;
  12946. }
  12947. else {
  12948. throw new TypeError('Data must be an instance of DataSet or DataView');
  12949. }
  12950. if (this.groupsData) {
  12951. // subscribe to new dataset
  12952. var id = this.id;
  12953. util.forEach(this.groupListeners, function (callback, event) {
  12954. me.groupsData.on(event, callback, id);
  12955. });
  12956. // draw all ms
  12957. ids = this.groupsData.getIds();
  12958. this._onAddGroups(ids);
  12959. }
  12960. // update the group holding all ungrouped items
  12961. this._updateUngrouped();
  12962. // update the order of all items in each group
  12963. this._order();
  12964. this.body.emitter.emit('change', {queue: true});
  12965. };
  12966. /**
  12967. * Get the current groups
  12968. * @returns {vis.DataSet | null} groups
  12969. */
  12970. ItemSet.prototype.getGroups = function() {
  12971. return this.groupsData;
  12972. };
  12973. /**
  12974. * Remove an item by its id
  12975. * @param {String | Number} id
  12976. */
  12977. ItemSet.prototype.removeItem = function(id) {
  12978. var item = this.itemsData.get(id),
  12979. dataset = this.itemsData.getDataSet();
  12980. if (item) {
  12981. // confirm deletion
  12982. this.options.onRemove(item, function (item) {
  12983. if (item) {
  12984. // remove by id here, it is possible that an item has no id defined
  12985. // itself, so better not delete by the item itself
  12986. dataset.remove(id);
  12987. }
  12988. });
  12989. }
  12990. };
  12991. /**
  12992. * Get the time of an item based on it's data and options.type
  12993. * @param {Object} itemData
  12994. * @returns {string} Returns the type
  12995. * @private
  12996. */
  12997. ItemSet.prototype._getType = function (itemData) {
  12998. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  12999. };
  13000. /**
  13001. * Get the group id for an item
  13002. * @param {Object} itemData
  13003. * @returns {string} Returns the groupId
  13004. * @private
  13005. */
  13006. ItemSet.prototype._getGroupId = function (itemData) {
  13007. var type = this._getType(itemData);
  13008. if (type == 'background' && itemData.group == undefined) {
  13009. return BACKGROUND;
  13010. }
  13011. else {
  13012. return this.groupsData ? itemData.group : UNGROUPED;
  13013. }
  13014. };
  13015. /**
  13016. * Handle updated items
  13017. * @param {Number[]} ids
  13018. * @protected
  13019. */
  13020. ItemSet.prototype._onUpdate = function(ids) {
  13021. var me = this;
  13022. ids.forEach(function (id) {
  13023. var itemData = me.itemsData.get(id, me.itemOptions);
  13024. var item = me.items[id];
  13025. var type = me._getType(itemData);
  13026. var constructor = ItemSet.types[type];
  13027. if (item) {
  13028. // update item
  13029. if (!constructor || !(item instanceof constructor)) {
  13030. // item type has changed, delete the item and recreate it
  13031. me._removeItem(item);
  13032. item = null;
  13033. }
  13034. else {
  13035. me._updateItem(item, itemData);
  13036. }
  13037. }
  13038. if (!item) {
  13039. // create item
  13040. if (constructor) {
  13041. item = new constructor(itemData, me.conversion, me.options);
  13042. item.id = id; // TODO: not so nice setting id afterwards
  13043. me._addItem(item);
  13044. }
  13045. else if (type == 'rangeoverflow') {
  13046. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  13047. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  13048. '.vis.timeline .item.range .content {overflow: visible;}');
  13049. }
  13050. else {
  13051. throw new TypeError('Unknown item type "' + type + '"');
  13052. }
  13053. }
  13054. });
  13055. this._order();
  13056. this.stackDirty = true; // force re-stacking of all items next redraw
  13057. this.body.emitter.emit('change', {queue: true});
  13058. };
  13059. /**
  13060. * Handle added items
  13061. * @param {Number[]} ids
  13062. * @protected
  13063. */
  13064. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  13065. /**
  13066. * Handle removed items
  13067. * @param {Number[]} ids
  13068. * @protected
  13069. */
  13070. ItemSet.prototype._onRemove = function(ids) {
  13071. var count = 0;
  13072. var me = this;
  13073. ids.forEach(function (id) {
  13074. var item = me.items[id];
  13075. if (item) {
  13076. count++;
  13077. me._removeItem(item);
  13078. }
  13079. });
  13080. if (count) {
  13081. // update order
  13082. this._order();
  13083. this.stackDirty = true; // force re-stacking of all items next redraw
  13084. this.body.emitter.emit('change', {queue: true});
  13085. }
  13086. };
  13087. /**
  13088. * Update the order of item in all groups
  13089. * @private
  13090. */
  13091. ItemSet.prototype._order = function() {
  13092. // reorder the items in all groups
  13093. // TODO: optimization: only reorder groups affected by the changed items
  13094. util.forEach(this.groups, function (group) {
  13095. group.order();
  13096. });
  13097. };
  13098. /**
  13099. * Handle updated groups
  13100. * @param {Number[]} ids
  13101. * @private
  13102. */
  13103. ItemSet.prototype._onUpdateGroups = function(ids) {
  13104. this._onAddGroups(ids);
  13105. };
  13106. /**
  13107. * Handle changed groups (added or updated)
  13108. * @param {Number[]} ids
  13109. * @private
  13110. */
  13111. ItemSet.prototype._onAddGroups = function(ids) {
  13112. var me = this;
  13113. ids.forEach(function (id) {
  13114. var groupData = me.groupsData.get(id);
  13115. var group = me.groups[id];
  13116. if (!group) {
  13117. // check for reserved ids
  13118. if (id == UNGROUPED || id == BACKGROUND) {
  13119. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  13120. }
  13121. var groupOptions = Object.create(me.options);
  13122. util.extend(groupOptions, {
  13123. height: null
  13124. });
  13125. group = new Group(id, groupData, me);
  13126. me.groups[id] = group;
  13127. // add items with this groupId to the new group
  13128. for (var itemId in me.items) {
  13129. if (me.items.hasOwnProperty(itemId)) {
  13130. var item = me.items[itemId];
  13131. if (item.data.group == id) {
  13132. group.add(item);
  13133. }
  13134. }
  13135. }
  13136. group.order();
  13137. group.show();
  13138. }
  13139. else {
  13140. // update group
  13141. group.setData(groupData);
  13142. }
  13143. });
  13144. this.body.emitter.emit('change', {queue: true});
  13145. };
  13146. /**
  13147. * Handle removed groups
  13148. * @param {Number[]} ids
  13149. * @private
  13150. */
  13151. ItemSet.prototype._onRemoveGroups = function(ids) {
  13152. var groups = this.groups;
  13153. ids.forEach(function (id) {
  13154. var group = groups[id];
  13155. if (group) {
  13156. group.hide();
  13157. delete groups[id];
  13158. }
  13159. });
  13160. this.markDirty();
  13161. this.body.emitter.emit('change', {queue: true});
  13162. };
  13163. /**
  13164. * Reorder the groups if needed
  13165. * @return {boolean} changed
  13166. * @private
  13167. */
  13168. ItemSet.prototype._orderGroups = function () {
  13169. if (this.groupsData) {
  13170. // reorder the groups
  13171. var groupIds = this.groupsData.getIds({
  13172. order: this.options.groupOrder
  13173. });
  13174. var changed = !util.equalArray(groupIds, this.groupIds);
  13175. if (changed) {
  13176. // hide all groups, removes them from the DOM
  13177. var groups = this.groups;
  13178. groupIds.forEach(function (groupId) {
  13179. groups[groupId].hide();
  13180. });
  13181. // show the groups again, attach them to the DOM in correct order
  13182. groupIds.forEach(function (groupId) {
  13183. groups[groupId].show();
  13184. });
  13185. this.groupIds = groupIds;
  13186. }
  13187. return changed;
  13188. }
  13189. else {
  13190. return false;
  13191. }
  13192. };
  13193. /**
  13194. * Add a new item
  13195. * @param {Item} item
  13196. * @private
  13197. */
  13198. ItemSet.prototype._addItem = function(item) {
  13199. this.items[item.id] = item;
  13200. // add to group
  13201. var groupId = this._getGroupId(item.data);
  13202. var group = this.groups[groupId];
  13203. if (group) group.add(item);
  13204. };
  13205. /**
  13206. * Update an existing item
  13207. * @param {Item} item
  13208. * @param {Object} itemData
  13209. * @private
  13210. */
  13211. ItemSet.prototype._updateItem = function(item, itemData) {
  13212. var oldGroupId = item.data.group;
  13213. // update the items data (will redraw the item when displayed)
  13214. item.setData(itemData);
  13215. // update group
  13216. if (oldGroupId != item.data.group) {
  13217. var oldGroup = this.groups[oldGroupId];
  13218. if (oldGroup) oldGroup.remove(item);
  13219. var groupId = this._getGroupId(item.data);
  13220. var group = this.groups[groupId];
  13221. if (group) group.add(item);
  13222. }
  13223. };
  13224. /**
  13225. * Delete an item from the ItemSet: remove it from the DOM, from the map
  13226. * with items, and from the map with visible items, and from the selection
  13227. * @param {Item} item
  13228. * @private
  13229. */
  13230. ItemSet.prototype._removeItem = function(item) {
  13231. // remove from DOM
  13232. item.hide();
  13233. // remove from items
  13234. delete this.items[item.id];
  13235. // remove from selection
  13236. var index = this.selection.indexOf(item.id);
  13237. if (index != -1) this.selection.splice(index, 1);
  13238. // remove from group
  13239. item.parent && item.parent.remove(item);
  13240. };
  13241. /**
  13242. * Create an array containing all items being a range (having an end date)
  13243. * @param array
  13244. * @returns {Array}
  13245. * @private
  13246. */
  13247. ItemSet.prototype._constructByEndArray = function(array) {
  13248. var endArray = [];
  13249. for (var i = 0; i < array.length; i++) {
  13250. if (array[i] instanceof RangeItem) {
  13251. endArray.push(array[i]);
  13252. }
  13253. }
  13254. return endArray;
  13255. };
  13256. /**
  13257. * Register the clicked item on touch, before dragStart is initiated.
  13258. *
  13259. * dragStart is initiated from a mousemove event, which can have left the item
  13260. * already resulting in an item == null
  13261. *
  13262. * @param {Event} event
  13263. * @private
  13264. */
  13265. ItemSet.prototype._onTouch = function (event) {
  13266. // store the touched item, used in _onDragStart
  13267. this.touchParams.item = ItemSet.itemFromTarget(event);
  13268. };
  13269. /**
  13270. * Start dragging the selected events
  13271. * @param {Event} event
  13272. * @private
  13273. */
  13274. ItemSet.prototype._onDragStart = function (event) {
  13275. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  13276. return;
  13277. }
  13278. var item = this.touchParams.item || null;
  13279. var me = this;
  13280. var props;
  13281. if (item && item.selected) {
  13282. var dragLeftItem = event.target.dragLeftItem;
  13283. var dragRightItem = event.target.dragRightItem;
  13284. if (dragLeftItem) {
  13285. props = {
  13286. item: dragLeftItem,
  13287. initialX: event.gesture.center.clientX
  13288. };
  13289. if (me.options.editable.updateTime) {
  13290. props.start = item.data.start.valueOf();
  13291. }
  13292. if (me.options.editable.updateGroup) {
  13293. if ('group' in item.data) props.group = item.data.group;
  13294. }
  13295. this.touchParams.itemProps = [props];
  13296. }
  13297. else if (dragRightItem) {
  13298. props = {
  13299. item: dragRightItem,
  13300. initialX: event.gesture.center.clientX
  13301. };
  13302. if (me.options.editable.updateTime) {
  13303. props.end = item.data.end.valueOf();
  13304. }
  13305. if (me.options.editable.updateGroup) {
  13306. if ('group' in item.data) props.group = item.data.group;
  13307. }
  13308. this.touchParams.itemProps = [props];
  13309. }
  13310. else {
  13311. this.touchParams.itemProps = this.getSelection().map(function (id) {
  13312. var item = me.items[id];
  13313. var props = {
  13314. item: item,
  13315. initialX: event.gesture.center.clientX
  13316. };
  13317. if (me.options.editable.updateTime) {
  13318. if ('start' in item.data) props.start = item.data.start.valueOf();
  13319. if ('end' in item.data) props.end = item.data.end.valueOf();
  13320. }
  13321. if (me.options.editable.updateGroup) {
  13322. if ('group' in item.data) props.group = item.data.group;
  13323. }
  13324. return props;
  13325. });
  13326. }
  13327. event.stopPropagation();
  13328. }
  13329. };
  13330. /**
  13331. * Drag selected items
  13332. * @param {Event} event
  13333. * @private
  13334. */
  13335. ItemSet.prototype._onDrag = function (event) {
  13336. event.preventDefault()
  13337. if (this.touchParams.itemProps) {
  13338. var me = this;
  13339. var snap = this.body.util.snap || null;
  13340. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  13341. // move
  13342. this.touchParams.itemProps.forEach(function (props) {
  13343. var newProps = {};
  13344. var current = me.body.util.toTime(event.gesture.center.clientX - xOffset);
  13345. var initial = me.body.util.toTime(props.initialX - xOffset);
  13346. var offset = current - initial;
  13347. if ('start' in props) {
  13348. var start = new Date(props.start + offset);
  13349. newProps.start = snap ? snap(start) : start;
  13350. }
  13351. if ('end' in props) {
  13352. var end = new Date(props.end + offset);
  13353. newProps.end = snap ? snap(end) : end;
  13354. }
  13355. if ('group' in props) {
  13356. // drag from one group to another
  13357. var group = ItemSet.groupFromTarget(event);
  13358. newProps.group = group && group.groupId;
  13359. }
  13360. // confirm moving the item
  13361. var itemData = util.extend({}, props.item.data, newProps);
  13362. me.options.onMoving(itemData, function (itemData) {
  13363. if (itemData) {
  13364. me._updateItemProps(props.item, itemData);
  13365. }
  13366. });
  13367. });
  13368. this.stackDirty = true; // force re-stacking of all items next redraw
  13369. this.body.emitter.emit('change');
  13370. event.stopPropagation();
  13371. }
  13372. };
  13373. /**
  13374. * Update an items properties
  13375. * @param {Item} item
  13376. * @param {Object} props Can contain properties start, end, and group.
  13377. * @private
  13378. */
  13379. ItemSet.prototype._updateItemProps = function(item, props) {
  13380. // TODO: copy all properties from props to item? (also new ones)
  13381. if ('start' in props) item.data.start = props.start;
  13382. if ('end' in props) item.data.end = props.end;
  13383. if ('group' in props && item.data.group != props.group) {
  13384. this._moveToGroup(item, props.group)
  13385. }
  13386. };
  13387. /**
  13388. * Move an item to another group
  13389. * @param {Item} item
  13390. * @param {String | Number} groupId
  13391. * @private
  13392. */
  13393. ItemSet.prototype._moveToGroup = function(item, groupId) {
  13394. var group = this.groups[groupId];
  13395. if (group && group.groupId != item.data.group) {
  13396. var oldGroup = item.parent;
  13397. oldGroup.remove(item);
  13398. oldGroup.order();
  13399. group.add(item);
  13400. group.order();
  13401. item.data.group = group.groupId;
  13402. }
  13403. };
  13404. /**
  13405. * End of dragging selected items
  13406. * @param {Event} event
  13407. * @private
  13408. */
  13409. ItemSet.prototype._onDragEnd = function (event) {
  13410. event.preventDefault()
  13411. if (this.touchParams.itemProps) {
  13412. // prepare a change set for the changed items
  13413. var changes = [],
  13414. me = this,
  13415. dataset = this.itemsData.getDataSet();
  13416. var itemProps = this.touchParams.itemProps ;
  13417. this.touchParams.itemProps = null;
  13418. itemProps.forEach(function (props) {
  13419. var id = props.item.id,
  13420. itemData = me.itemsData.get(id, me.itemOptions);
  13421. var changed = false;
  13422. if ('start' in props.item.data) {
  13423. changed = (props.start != props.item.data.start.valueOf());
  13424. itemData.start = util.convert(props.item.data.start,
  13425. dataset._options.type && dataset._options.type.start || 'Date');
  13426. }
  13427. if ('end' in props.item.data) {
  13428. changed = changed || (props.end != props.item.data.end.valueOf());
  13429. itemData.end = util.convert(props.item.data.end,
  13430. dataset._options.type && dataset._options.type.end || 'Date');
  13431. }
  13432. if ('group' in props.item.data) {
  13433. changed = changed || (props.group != props.item.data.group);
  13434. itemData.group = props.item.data.group;
  13435. }
  13436. // only apply changes when start or end is actually changed
  13437. if (changed) {
  13438. me.options.onMove(itemData, function (itemData) {
  13439. if (itemData) {
  13440. // apply changes
  13441. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  13442. changes.push(itemData);
  13443. }
  13444. else {
  13445. // restore original values
  13446. me._updateItemProps(props.item, props);
  13447. me.stackDirty = true; // force re-stacking of all items next redraw
  13448. me.body.emitter.emit('change');
  13449. }
  13450. });
  13451. }
  13452. });
  13453. // apply the changes to the data (if there are changes)
  13454. if (changes.length) {
  13455. dataset.update(changes);
  13456. }
  13457. event.stopPropagation();
  13458. }
  13459. };
  13460. /**
  13461. * Handle selecting/deselecting an item when tapping it
  13462. * @param {Event} event
  13463. * @private
  13464. */
  13465. ItemSet.prototype._onSelectItem = function (event) {
  13466. if (!this.options.selectable) return;
  13467. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  13468. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  13469. if (ctrlKey || shiftKey) {
  13470. this._onMultiSelectItem(event);
  13471. return;
  13472. }
  13473. var oldSelection = this.getSelection();
  13474. var item = ItemSet.itemFromTarget(event);
  13475. var selection = item ? [item.id] : [];
  13476. this.setSelection(selection);
  13477. var newSelection = this.getSelection();
  13478. // emit a select event,
  13479. // except when old selection is empty and new selection is still empty
  13480. if (newSelection.length > 0 || oldSelection.length > 0) {
  13481. this.body.emitter.emit('select', {
  13482. items: newSelection
  13483. });
  13484. }
  13485. };
  13486. /**
  13487. * Handle creation and updates of an item on double tap
  13488. * @param event
  13489. * @private
  13490. */
  13491. ItemSet.prototype._onAddItem = function (event) {
  13492. if (!this.options.selectable) return;
  13493. if (!this.options.editable.add) return;
  13494. var me = this,
  13495. snap = this.body.util.snap || null,
  13496. item = ItemSet.itemFromTarget(event);
  13497. if (item) {
  13498. // update item
  13499. // execute async handler to update the item (or cancel it)
  13500. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  13501. this.options.onUpdate(itemData, function (itemData) {
  13502. if (itemData) {
  13503. me.itemsData.getDataSet().update(itemData);
  13504. }
  13505. });
  13506. }
  13507. else {
  13508. // add item
  13509. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  13510. var x = event.gesture.center.pageX - xAbs;
  13511. var start = this.body.util.toTime(x);
  13512. var newItem = {
  13513. start: snap ? snap(start) : start,
  13514. content: 'new item'
  13515. };
  13516. // when default type is a range, add a default end date to the new item
  13517. if (this.options.type === 'range') {
  13518. var end = this.body.util.toTime(x + this.props.width / 5);
  13519. newItem.end = snap ? snap(end) : end;
  13520. }
  13521. newItem[this.itemsData._fieldId] = util.randomUUID();
  13522. var group = ItemSet.groupFromTarget(event);
  13523. if (group) {
  13524. newItem.group = group.groupId;
  13525. }
  13526. // execute async handler to customize (or cancel) adding an item
  13527. this.options.onAdd(newItem, function (item) {
  13528. if (item) {
  13529. me.itemsData.getDataSet().add(item);
  13530. // TODO: need to trigger a redraw?
  13531. }
  13532. });
  13533. }
  13534. };
  13535. /**
  13536. * Handle selecting/deselecting multiple items when holding an item
  13537. * @param {Event} event
  13538. * @private
  13539. */
  13540. ItemSet.prototype._onMultiSelectItem = function (event) {
  13541. if (!this.options.selectable) return;
  13542. var selection,
  13543. item = ItemSet.itemFromTarget(event);
  13544. if (item) {
  13545. // multi select items
  13546. selection = this.getSelection(); // current selection
  13547. var shiftKey = event.gesture.touches[0] && event.gesture.touches[0].shiftKey || false;
  13548. if (shiftKey) {
  13549. // select all items between the old selection and the tapped item
  13550. // determine the selection range
  13551. selection.push(item.id);
  13552. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  13553. // select all items within the selection range
  13554. selection = [];
  13555. for (var id in this.items) {
  13556. if (this.items.hasOwnProperty(id)) {
  13557. var _item = this.items[id];
  13558. var start = _item.data.start;
  13559. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  13560. if (start >= range.min && end <= range.max) {
  13561. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  13562. }
  13563. }
  13564. }
  13565. }
  13566. else {
  13567. // add/remove this item from the current selection
  13568. var index = selection.indexOf(item.id);
  13569. if (index == -1) {
  13570. // item is not yet selected -> select it
  13571. selection.push(item.id);
  13572. }
  13573. else {
  13574. // item is already selected -> deselect it
  13575. selection.splice(index, 1);
  13576. }
  13577. }
  13578. this.setSelection(selection);
  13579. this.body.emitter.emit('select', {
  13580. items: this.getSelection()
  13581. });
  13582. }
  13583. };
  13584. /**
  13585. * Calculate the time range of a list of items
  13586. * @param {Array.<Object>} itemsData
  13587. * @return {{min: Date, max: Date}} Returns the range of the provided items
  13588. * @private
  13589. */
  13590. ItemSet._getItemRange = function(itemsData) {
  13591. var max = null;
  13592. var min = null;
  13593. itemsData.forEach(function (data) {
  13594. if (min == null || data.start < min) {
  13595. min = data.start;
  13596. }
  13597. if (data.end != undefined) {
  13598. if (max == null || data.end > max) {
  13599. max = data.end;
  13600. }
  13601. }
  13602. else {
  13603. if (max == null || data.start > max) {
  13604. max = data.start;
  13605. }
  13606. }
  13607. });
  13608. return {
  13609. min: min,
  13610. max: max
  13611. }
  13612. };
  13613. /**
  13614. * Find an item from an event target:
  13615. * searches for the attribute 'timeline-item' in the event target's element tree
  13616. * @param {Event} event
  13617. * @return {Item | null} item
  13618. */
  13619. ItemSet.itemFromTarget = function(event) {
  13620. var target = event.target;
  13621. while (target) {
  13622. if (target.hasOwnProperty('timeline-item')) {
  13623. return target['timeline-item'];
  13624. }
  13625. target = target.parentNode;
  13626. }
  13627. return null;
  13628. };
  13629. /**
  13630. * Find the Group from an event target:
  13631. * searches for the attribute 'timeline-group' in the event target's element tree
  13632. * @param {Event} event
  13633. * @return {Group | null} group
  13634. */
  13635. ItemSet.groupFromTarget = function(event) {
  13636. var target = event.target;
  13637. while (target) {
  13638. if (target.hasOwnProperty('timeline-group')) {
  13639. return target['timeline-group'];
  13640. }
  13641. target = target.parentNode;
  13642. }
  13643. return null;
  13644. };
  13645. /**
  13646. * Find the ItemSet from an event target:
  13647. * searches for the attribute 'timeline-itemset' in the event target's element tree
  13648. * @param {Event} event
  13649. * @return {ItemSet | null} item
  13650. */
  13651. ItemSet.itemSetFromTarget = function(event) {
  13652. var target = event.target;
  13653. while (target) {
  13654. if (target.hasOwnProperty('timeline-itemset')) {
  13655. return target['timeline-itemset'];
  13656. }
  13657. target = target.parentNode;
  13658. }
  13659. return null;
  13660. };
  13661. module.exports = ItemSet;
  13662. /***/ },
  13663. /* 27 */
  13664. /***/ function(module, exports, __webpack_require__) {
  13665. var util = __webpack_require__(1);
  13666. var stack = __webpack_require__(28);
  13667. var RangeItem = __webpack_require__(29);
  13668. /**
  13669. * @constructor Group
  13670. * @param {Number | String} groupId
  13671. * @param {Object} data
  13672. * @param {ItemSet} itemSet
  13673. */
  13674. function Group (groupId, data, itemSet) {
  13675. this.groupId = groupId;
  13676. this.subgroups = {};
  13677. this.subgroupIndex = 0;
  13678. this.subgroupOrderer = data && data.subgroupOrder;
  13679. this.itemSet = itemSet;
  13680. this.dom = {};
  13681. this.props = {
  13682. label: {
  13683. width: 0,
  13684. height: 0
  13685. }
  13686. };
  13687. this.className = null;
  13688. this.items = {}; // items filtered by groupId of this group
  13689. this.visibleItems = []; // items currently visible in window
  13690. this.orderedItems = {
  13691. byStart: [],
  13692. byEnd: []
  13693. };
  13694. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  13695. var me = this;
  13696. this.itemSet.body.emitter.on("checkRangedItems", function () {
  13697. me.checkRangedItems = true;
  13698. })
  13699. this._create();
  13700. this.setData(data);
  13701. }
  13702. /**
  13703. * Create DOM elements for the group
  13704. * @private
  13705. */
  13706. Group.prototype._create = function() {
  13707. var label = document.createElement('div');
  13708. label.className = 'vlabel';
  13709. this.dom.label = label;
  13710. var inner = document.createElement('div');
  13711. inner.className = 'inner';
  13712. label.appendChild(inner);
  13713. this.dom.inner = inner;
  13714. var foreground = document.createElement('div');
  13715. foreground.className = 'group';
  13716. foreground['timeline-group'] = this;
  13717. this.dom.foreground = foreground;
  13718. this.dom.background = document.createElement('div');
  13719. this.dom.background.className = 'group';
  13720. this.dom.axis = document.createElement('div');
  13721. this.dom.axis.className = 'group';
  13722. // create a hidden marker to detect when the Timelines container is attached
  13723. // to the DOM, or the style of a parent of the Timeline is changed from
  13724. // display:none is changed to visible.
  13725. this.dom.marker = document.createElement('div');
  13726. this.dom.marker.style.visibility = 'hidden'; // TODO: ask jos why this is not none?
  13727. this.dom.marker.innerHTML = '?';
  13728. this.dom.background.appendChild(this.dom.marker);
  13729. };
  13730. /**
  13731. * Set the group data for this group
  13732. * @param {Object} data Group data, can contain properties content and className
  13733. */
  13734. Group.prototype.setData = function(data) {
  13735. // update contents
  13736. var content = data && data.content;
  13737. if (content instanceof Element) {
  13738. this.dom.inner.appendChild(content);
  13739. }
  13740. else if (content !== undefined && content !== null) {
  13741. this.dom.inner.innerHTML = content;
  13742. }
  13743. else {
  13744. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  13745. }
  13746. // update title
  13747. this.dom.label.title = data && data.title || '';
  13748. if (!this.dom.inner.firstChild) {
  13749. util.addClassName(this.dom.inner, 'hidden');
  13750. }
  13751. else {
  13752. util.removeClassName(this.dom.inner, 'hidden');
  13753. }
  13754. // update className
  13755. var className = data && data.className || null;
  13756. if (className != this.className) {
  13757. if (this.className) {
  13758. util.removeClassName(this.dom.label, this.className);
  13759. util.removeClassName(this.dom.foreground, this.className);
  13760. util.removeClassName(this.dom.background, this.className);
  13761. util.removeClassName(this.dom.axis, this.className);
  13762. }
  13763. util.addClassName(this.dom.label, className);
  13764. util.addClassName(this.dom.foreground, className);
  13765. util.addClassName(this.dom.background, className);
  13766. util.addClassName(this.dom.axis, className);
  13767. this.className = className;
  13768. }
  13769. // update style
  13770. if (this.style) {
  13771. util.removeCssText(this.dom.label, this.style);
  13772. this.style = null;
  13773. }
  13774. if (data && data.style) {
  13775. util.addCssText(this.dom.label, data.style);
  13776. this.style = data.style;
  13777. }
  13778. };
  13779. /**
  13780. * Get the width of the group label
  13781. * @return {number} width
  13782. */
  13783. Group.prototype.getLabelWidth = function() {
  13784. return this.props.label.width;
  13785. };
  13786. /**
  13787. * Repaint this group
  13788. * @param {{start: number, end: number}} range
  13789. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  13790. * @param {boolean} [restack=false] Force restacking of all items
  13791. * @return {boolean} Returns true if the group is resized
  13792. */
  13793. Group.prototype.redraw = function(range, margin, restack) {
  13794. var resized = false;
  13795. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  13796. // force recalculation of the height of the items when the marker height changed
  13797. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  13798. var markerHeight = this.dom.marker.clientHeight;
  13799. if (markerHeight != this.lastMarkerHeight) {
  13800. this.lastMarkerHeight = markerHeight;
  13801. util.forEach(this.items, function (item) {
  13802. item.dirty = true;
  13803. if (item.displayed) item.redraw();
  13804. });
  13805. restack = true;
  13806. }
  13807. // reposition visible items vertically
  13808. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  13809. stack.stack(this.visibleItems, margin, restack);
  13810. }
  13811. else { // no stacking
  13812. stack.nostack(this.visibleItems, margin, this.subgroups);
  13813. }
  13814. // recalculate the height of the group
  13815. var height = this._calculateHeight(margin);
  13816. // calculate actual size and position
  13817. var foreground = this.dom.foreground;
  13818. this.top = foreground.offsetTop;
  13819. this.left = foreground.offsetLeft;
  13820. this.width = foreground.offsetWidth;
  13821. resized = util.updateProperty(this, 'height', height) || resized;
  13822. // recalculate size of label
  13823. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  13824. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  13825. // apply new height
  13826. this.dom.background.style.height = height + 'px';
  13827. this.dom.foreground.style.height = height + 'px';
  13828. this.dom.label.style.height = height + 'px';
  13829. // update vertical position of items after they are re-stacked and the height of the group is calculated
  13830. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  13831. var item = this.visibleItems[i];
  13832. item.repositionY(margin);
  13833. }
  13834. return resized;
  13835. };
  13836. /**
  13837. * recalculate the height of the group
  13838. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  13839. * @returns {number} Returns the height
  13840. * @private
  13841. */
  13842. Group.prototype._calculateHeight = function (margin) {
  13843. // recalculate the height of the group
  13844. var height;
  13845. var visibleItems = this.visibleItems;
  13846. //var visibleSubgroups = [];
  13847. //this.visibleSubgroups = 0;
  13848. this.resetSubgroups();
  13849. var me = this;
  13850. if (visibleItems.length) {
  13851. var min = visibleItems[0].top;
  13852. var max = visibleItems[0].top + visibleItems[0].height;
  13853. util.forEach(visibleItems, function (item) {
  13854. min = Math.min(min, item.top);
  13855. max = Math.max(max, (item.top + item.height));
  13856. if (item.data.subgroup !== undefined) {
  13857. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height,item.height);
  13858. me.subgroups[item.data.subgroup].visible = true;
  13859. //if (visibleSubgroups.indexOf(item.data.subgroup) == -1){
  13860. // visibleSubgroups.push(item.data.subgroup);
  13861. // me.visibleSubgroups += 1;
  13862. //}
  13863. }
  13864. });
  13865. if (min > margin.axis) {
  13866. // there is an empty gap between the lowest item and the axis
  13867. var offset = min - margin.axis;
  13868. max -= offset;
  13869. util.forEach(visibleItems, function (item) {
  13870. item.top -= offset;
  13871. });
  13872. }
  13873. height = max + margin.item.vertical / 2;
  13874. }
  13875. else {
  13876. height = margin.axis + margin.item.vertical;
  13877. }
  13878. height = Math.max(height, this.props.label.height);
  13879. return height;
  13880. };
  13881. /**
  13882. * Show this group: attach to the DOM
  13883. */
  13884. Group.prototype.show = function() {
  13885. if (!this.dom.label.parentNode) {
  13886. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  13887. }
  13888. if (!this.dom.foreground.parentNode) {
  13889. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  13890. }
  13891. if (!this.dom.background.parentNode) {
  13892. this.itemSet.dom.background.appendChild(this.dom.background);
  13893. }
  13894. if (!this.dom.axis.parentNode) {
  13895. this.itemSet.dom.axis.appendChild(this.dom.axis);
  13896. }
  13897. };
  13898. /**
  13899. * Hide this group: remove from the DOM
  13900. */
  13901. Group.prototype.hide = function() {
  13902. var label = this.dom.label;
  13903. if (label.parentNode) {
  13904. label.parentNode.removeChild(label);
  13905. }
  13906. var foreground = this.dom.foreground;
  13907. if (foreground.parentNode) {
  13908. foreground.parentNode.removeChild(foreground);
  13909. }
  13910. var background = this.dom.background;
  13911. if (background.parentNode) {
  13912. background.parentNode.removeChild(background);
  13913. }
  13914. var axis = this.dom.axis;
  13915. if (axis.parentNode) {
  13916. axis.parentNode.removeChild(axis);
  13917. }
  13918. };
  13919. /**
  13920. * Add an item to the group
  13921. * @param {Item} item
  13922. */
  13923. Group.prototype.add = function(item) {
  13924. this.items[item.id] = item;
  13925. item.setParent(this);
  13926. // add to
  13927. if (item.data.subgroup !== undefined) {
  13928. if (this.subgroups[item.data.subgroup] === undefined) {
  13929. this.subgroups[item.data.subgroup] = {height:0, visible: false, index:this.subgroupIndex, items: []};
  13930. this.subgroupIndex++;
  13931. }
  13932. this.subgroups[item.data.subgroup].items.push(item);
  13933. }
  13934. this.orderSubgroups();
  13935. if (this.visibleItems.indexOf(item) == -1) {
  13936. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  13937. this._checkIfVisible(item, this.visibleItems, range);
  13938. }
  13939. };
  13940. Group.prototype.orderSubgroups = function() {
  13941. if (this.subgroupOrderer !== undefined) {
  13942. var sortArray = [];
  13943. if (typeof this.subgroupOrderer == 'string') {
  13944. for (var subgroup in this.subgroups) {
  13945. sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
  13946. }
  13947. sortArray.sort(function (a, b) {
  13948. return a.sortField - b.sortField;
  13949. })
  13950. }
  13951. else if (typeof this.subgroupOrderer == 'function') {
  13952. for (var subgroup in this.subgroups) {
  13953. sortArray.push(this.subgroups[subgroup].items[0].data);
  13954. }
  13955. sortArray.sort(this.subgroupOrderer);
  13956. }
  13957. if (sortArray.length > 0) {
  13958. for (var i = 0; i < sortArray.length; i++) {
  13959. this.subgroups[sortArray[i].subgroup].index = i;
  13960. }
  13961. }
  13962. }
  13963. };
  13964. Group.prototype.resetSubgroups = function() {
  13965. for (var subgroup in this.subgroups) {
  13966. if (this.subgroups.hasOwnProperty(subgroup)) {
  13967. this.subgroups[subgroup].visible = false;
  13968. }
  13969. }
  13970. };
  13971. /**
  13972. * Remove an item from the group
  13973. * @param {Item} item
  13974. */
  13975. Group.prototype.remove = function(item) {
  13976. delete this.items[item.id];
  13977. item.setParent(null);
  13978. // remove from visible items
  13979. var index = this.visibleItems.indexOf(item);
  13980. if (index != -1) this.visibleItems.splice(index, 1);
  13981. // TODO: also remove from ordered items?
  13982. };
  13983. /**
  13984. * Remove an item from the corresponding DataSet
  13985. * @param {Item} item
  13986. */
  13987. Group.prototype.removeFromDataSet = function(item) {
  13988. this.itemSet.removeItem(item.id);
  13989. };
  13990. /**
  13991. * Reorder the items
  13992. */
  13993. Group.prototype.order = function() {
  13994. var array = util.toArray(this.items);
  13995. var startArray = [];
  13996. var endArray = [];
  13997. for (var i = 0; i < array.length; i++) {
  13998. if (array[i].data.end !== undefined) {
  13999. endArray.push(array[i]);
  14000. }
  14001. startArray.push(array[i]);
  14002. }
  14003. this.orderedItems = {
  14004. byStart: startArray,
  14005. byEnd: endArray
  14006. };
  14007. stack.orderByStart(this.orderedItems.byStart);
  14008. stack.orderByEnd(this.orderedItems.byEnd);
  14009. };
  14010. /**
  14011. * Update the visible items
  14012. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  14013. * @param {Item[]} visibleItems The previously visible items.
  14014. * @param {{start: number, end: number}} range Visible range
  14015. * @return {Item[]} visibleItems The new visible items.
  14016. * @private
  14017. */
  14018. Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
  14019. var visibleItems = [];
  14020. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  14021. var interval = (range.end - range.start) / 4;
  14022. var lowerBound = range.start - interval;
  14023. var upperBound = range.end + interval;
  14024. var item, i;
  14025. // this function is used to do the binary search.
  14026. var searchFunction = function (value) {
  14027. if (value < lowerBound) {return -1;}
  14028. else if (value <= upperBound) {return 0;}
  14029. else {return 1;}
  14030. }
  14031. // first check if the items that were in view previously are still in view.
  14032. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  14033. // also cleans up invisible items.
  14034. if (oldVisibleItems.length > 0) {
  14035. for (i = 0; i < oldVisibleItems.length; i++) {
  14036. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  14037. }
  14038. }
  14039. // we do a binary search for the items that have only start values.
  14040. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  14041. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  14042. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  14043. return (item.data.start < lowerBound || item.data.start > upperBound);
  14044. });
  14045. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  14046. // We therefore have to brute force check all items in the byEnd list
  14047. if (this.checkRangedItems == true) {
  14048. this.checkRangedItems = false;
  14049. for (i = 0; i < orderedItems.byEnd.length; i++) {
  14050. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  14051. }
  14052. }
  14053. else {
  14054. // we do a binary search for the items that have defined end times.
  14055. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  14056. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  14057. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  14058. return (item.data.end < lowerBound || item.data.end > upperBound);
  14059. });
  14060. }
  14061. // finally, we reposition all the visible items.
  14062. for (i = 0; i < visibleItems.length; i++) {
  14063. item = visibleItems[i];
  14064. if (!item.displayed) item.show();
  14065. // reposition item horizontally
  14066. item.repositionX();
  14067. }
  14068. // debug
  14069. //console.log("new line")
  14070. //if (this.groupId == null) {
  14071. // for (i = 0; i < orderedItems.byStart.length; i++) {
  14072. // item = orderedItems.byStart[i].data;
  14073. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  14074. // }
  14075. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  14076. // item = orderedItems.byEnd[i].data;
  14077. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  14078. // }
  14079. //}
  14080. return visibleItems;
  14081. };
  14082. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  14083. var item;
  14084. var i;
  14085. if (initialPos != -1) {
  14086. for (i = initialPos; i >= 0; i--) {
  14087. item = items[i];
  14088. if (breakCondition(item)) {
  14089. break;
  14090. }
  14091. else {
  14092. if (visibleItemsLookup[item.id] === undefined) {
  14093. visibleItemsLookup[item.id] = true;
  14094. visibleItems.push(item);
  14095. }
  14096. }
  14097. }
  14098. for (i = initialPos + 1; i < items.length; i++) {
  14099. item = items[i];
  14100. if (breakCondition(item)) {
  14101. break;
  14102. }
  14103. else {
  14104. if (visibleItemsLookup[item.id] === undefined) {
  14105. visibleItemsLookup[item.id] = true;
  14106. visibleItems.push(item);
  14107. }
  14108. }
  14109. }
  14110. }
  14111. }
  14112. /**
  14113. * this function is very similar to the _checkIfInvisible() but it does not
  14114. * return booleans, hides the item if it should not be seen and always adds to
  14115. * the visibleItems.
  14116. * this one is for brute forcing and hiding.
  14117. *
  14118. * @param {Item} item
  14119. * @param {Array} visibleItems
  14120. * @param {{start:number, end:number}} range
  14121. * @private
  14122. */
  14123. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  14124. if (item.isVisible(range)) {
  14125. if (!item.displayed) item.show();
  14126. // reposition item horizontally
  14127. item.repositionX();
  14128. visibleItems.push(item);
  14129. }
  14130. else {
  14131. if (item.displayed) item.hide();
  14132. }
  14133. };
  14134. /**
  14135. * this function is very similar to the _checkIfInvisible() but it does not
  14136. * return booleans, hides the item if it should not be seen and always adds to
  14137. * the visibleItems.
  14138. * this one is for brute forcing and hiding.
  14139. *
  14140. * @param {Item} item
  14141. * @param {Array} visibleItems
  14142. * @param {{start:number, end:number}} range
  14143. * @private
  14144. */
  14145. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  14146. if (item.isVisible(range)) {
  14147. if (visibleItemsLookup[item.id] === undefined) {
  14148. visibleItemsLookup[item.id] = true;
  14149. visibleItems.push(item);
  14150. }
  14151. }
  14152. else {
  14153. if (item.displayed) item.hide();
  14154. }
  14155. };
  14156. module.exports = Group;
  14157. /***/ },
  14158. /* 28 */
  14159. /***/ function(module, exports, __webpack_require__) {
  14160. // Utility functions for ordering and stacking of items
  14161. var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
  14162. /**
  14163. * Order items by their start data
  14164. * @param {Item[]} items
  14165. */
  14166. exports.orderByStart = function(items) {
  14167. items.sort(function (a, b) {
  14168. return a.data.start - b.data.start;
  14169. });
  14170. };
  14171. /**
  14172. * Order items by their end date. If they have no end date, their start date
  14173. * is used.
  14174. * @param {Item[]} items
  14175. */
  14176. exports.orderByEnd = function(items) {
  14177. items.sort(function (a, b) {
  14178. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  14179. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  14180. return aTime - bTime;
  14181. });
  14182. };
  14183. /**
  14184. * Adjust vertical positions of the items such that they don't overlap each
  14185. * other.
  14186. * @param {Item[]} items
  14187. * All visible items
  14188. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  14189. * Margins between items and between items and the axis.
  14190. * @param {boolean} [force=false]
  14191. * If true, all items will be repositioned. If false (default), only
  14192. * items having a top===null will be re-stacked
  14193. */
  14194. exports.stack = function(items, margin, force) {
  14195. var i, iMax;
  14196. if (force) {
  14197. // reset top position of all items
  14198. for (i = 0, iMax = items.length; i < iMax; i++) {
  14199. items[i].top = null;
  14200. }
  14201. }
  14202. // calculate new, non-overlapping positions
  14203. for (i = 0, iMax = items.length; i < iMax; i++) {
  14204. var item = items[i];
  14205. if (item.stack && item.top === null) {
  14206. // initialize top position
  14207. item.top = margin.axis;
  14208. do {
  14209. // TODO: optimize checking for overlap. when there is a gap without items,
  14210. // you only need to check for items from the next item on, not from zero
  14211. var collidingItem = null;
  14212. for (var j = 0, jj = items.length; j < jj; j++) {
  14213. var other = items[j];
  14214. if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) {
  14215. collidingItem = other;
  14216. break;
  14217. }
  14218. }
  14219. if (collidingItem != null) {
  14220. // There is a collision. Reposition the items above the colliding element
  14221. item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
  14222. }
  14223. } while (collidingItem);
  14224. }
  14225. }
  14226. };
  14227. /**
  14228. * Adjust vertical positions of the items without stacking them
  14229. * @param {Item[]} items
  14230. * All visible items
  14231. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  14232. * Margins between items and between items and the axis.
  14233. */
  14234. exports.nostack = function(items, margin, subgroups) {
  14235. var i, iMax, newTop;
  14236. // reset top position of all items
  14237. for (i = 0, iMax = items.length; i < iMax; i++) {
  14238. if (items[i].data.subgroup !== undefined) {
  14239. newTop = margin.axis;
  14240. for (var subgroup in subgroups) {
  14241. if (subgroups.hasOwnProperty(subgroup)) {
  14242. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) {
  14243. newTop += subgroups[subgroup].height + margin.item.vertical;
  14244. }
  14245. }
  14246. }
  14247. items[i].top = newTop;
  14248. }
  14249. else {
  14250. items[i].top = margin.axis;
  14251. }
  14252. }
  14253. };
  14254. /**
  14255. * Test if the two provided items collide
  14256. * The items must have parameters left, width, top, and height.
  14257. * @param {Item} a The first item
  14258. * @param {Item} b The second item
  14259. * @param {{horizontal: number, vertical: number}} margin
  14260. * An object containing a horizontal and vertical
  14261. * minimum required margin.
  14262. * @return {boolean} true if a and b collide, else false
  14263. */
  14264. exports.collision = function(a, b, margin) {
  14265. return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) &&
  14266. (a.left + a.width + margin.horizontal - EPSILON) > b.left &&
  14267. (a.top - margin.vertical + EPSILON) < (b.top + b.height) &&
  14268. (a.top + a.height + margin.vertical - EPSILON) > b.top);
  14269. };
  14270. /***/ },
  14271. /* 29 */
  14272. /***/ function(module, exports, __webpack_require__) {
  14273. var Hammer = __webpack_require__(19);
  14274. var Item = __webpack_require__(30);
  14275. /**
  14276. * @constructor RangeItem
  14277. * @extends Item
  14278. * @param {Object} data Object containing parameters start, end
  14279. * content, className.
  14280. * @param {{toScreen: function, toTime: function}} conversion
  14281. * Conversion functions from time to screen and vice versa
  14282. * @param {Object} [options] Configuration options
  14283. * // TODO: describe options
  14284. */
  14285. function RangeItem (data, conversion, options) {
  14286. this.props = {
  14287. content: {
  14288. width: 0
  14289. }
  14290. };
  14291. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  14292. // validate data
  14293. if (data) {
  14294. if (data.start == undefined) {
  14295. throw new Error('Property "start" missing in item ' + data.id);
  14296. }
  14297. if (data.end == undefined) {
  14298. throw new Error('Property "end" missing in item ' + data.id);
  14299. }
  14300. }
  14301. Item.call(this, data, conversion, options);
  14302. }
  14303. RangeItem.prototype = new Item (null, null, null);
  14304. RangeItem.prototype.baseClassName = 'item range';
  14305. /**
  14306. * Check whether this item is visible inside given range
  14307. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  14308. * @returns {boolean} True if visible
  14309. */
  14310. RangeItem.prototype.isVisible = function(range) {
  14311. // determine visibility
  14312. return (this.data.start < range.end) && (this.data.end > range.start);
  14313. };
  14314. /**
  14315. * Repaint the item
  14316. */
  14317. RangeItem.prototype.redraw = function() {
  14318. var dom = this.dom;
  14319. if (!dom) {
  14320. // create DOM
  14321. this.dom = {};
  14322. dom = this.dom;
  14323. // background box
  14324. dom.box = document.createElement('div');
  14325. // className is updated in redraw()
  14326. // contents box
  14327. dom.content = document.createElement('div');
  14328. dom.content.className = 'content';
  14329. dom.box.appendChild(dom.content);
  14330. // attach this item as attribute
  14331. dom.box['timeline-item'] = this;
  14332. this.dirty = true;
  14333. }
  14334. // append DOM to parent DOM
  14335. if (!this.parent) {
  14336. throw new Error('Cannot redraw item: no parent attached');
  14337. }
  14338. if (!dom.box.parentNode) {
  14339. var foreground = this.parent.dom.foreground;
  14340. if (!foreground) {
  14341. throw new Error('Cannot redraw item: parent has no foreground container element');
  14342. }
  14343. foreground.appendChild(dom.box);
  14344. }
  14345. this.displayed = true;
  14346. // Update DOM when item is marked dirty. An item is marked dirty when:
  14347. // - the item is not yet rendered
  14348. // - the item's data is changed
  14349. // - the item is selected/deselected
  14350. if (this.dirty) {
  14351. this._updateContents(this.dom.content);
  14352. this._updateTitle(this.dom.box);
  14353. this._updateDataAttributes(this.dom.box);
  14354. this._updateStyle(this.dom.box);
  14355. // update class
  14356. var className = (this.data.className ? (' ' + this.data.className) : '') +
  14357. (this.selected ? ' selected' : '');
  14358. dom.box.className = this.baseClassName + className;
  14359. // determine from css whether this box has overflow
  14360. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  14361. // recalculate size
  14362. // turn off max-width to be able to calculate the real width
  14363. // this causes an extra browser repaint/reflow, but so be it
  14364. this.dom.content.style.maxWidth = 'none';
  14365. this.props.content.width = this.dom.content.offsetWidth;
  14366. this.height = this.dom.box.offsetHeight;
  14367. this.dom.content.style.maxWidth = '';
  14368. this.dirty = false;
  14369. }
  14370. this._repaintDeleteButton(dom.box);
  14371. this._repaintDragLeft();
  14372. this._repaintDragRight();
  14373. };
  14374. /**
  14375. * Show the item in the DOM (when not already visible). The items DOM will
  14376. * be created when needed.
  14377. */
  14378. RangeItem.prototype.show = function() {
  14379. if (!this.displayed) {
  14380. this.redraw();
  14381. }
  14382. };
  14383. /**
  14384. * Hide the item from the DOM (when visible)
  14385. * @return {Boolean} changed
  14386. */
  14387. RangeItem.prototype.hide = function() {
  14388. if (this.displayed) {
  14389. var box = this.dom.box;
  14390. if (box.parentNode) {
  14391. box.parentNode.removeChild(box);
  14392. }
  14393. this.top = null;
  14394. this.left = null;
  14395. this.displayed = false;
  14396. }
  14397. };
  14398. /**
  14399. * Reposition the item horizontally
  14400. * @Override
  14401. */
  14402. RangeItem.prototype.repositionX = function() {
  14403. var parentWidth = this.parent.width;
  14404. var start = this.conversion.toScreen(this.data.start);
  14405. var end = this.conversion.toScreen(this.data.end);
  14406. var contentLeft;
  14407. var contentWidth;
  14408. // limit the width of the this, as browsers cannot draw very wide divs
  14409. if (start < -parentWidth) {
  14410. start = -parentWidth;
  14411. }
  14412. if (end > 2 * parentWidth) {
  14413. end = 2 * parentWidth;
  14414. }
  14415. var boxWidth = Math.max(end - start, 1);
  14416. if (this.overflow) {
  14417. this.left = start;
  14418. this.width = boxWidth + this.props.content.width;
  14419. contentWidth = this.props.content.width;
  14420. // Note: The calculation of width is an optimistic calculation, giving
  14421. // a width which will not change when moving the Timeline
  14422. // So no re-stacking needed, which is nicer for the eye;
  14423. }
  14424. else {
  14425. this.left = start;
  14426. this.width = boxWidth;
  14427. contentWidth = Math.min(end - start - 2 * this.options.padding, this.props.content.width);
  14428. }
  14429. this.dom.box.style.left = this.left + 'px';
  14430. this.dom.box.style.width = boxWidth + 'px';
  14431. switch (this.options.align) {
  14432. case 'left':
  14433. this.dom.content.style.left = '0';
  14434. break;
  14435. case 'right':
  14436. this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding), 0) + 'px';
  14437. break;
  14438. case 'center':
  14439. this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding) / 2, 0) + 'px';
  14440. break;
  14441. default: // 'auto'
  14442. // when range exceeds left of the window, position the contents at the left of the visible area
  14443. if (this.overflow) {
  14444. if (end > 0) {
  14445. contentLeft = Math.max(-start, 0);
  14446. }
  14447. else {
  14448. contentLeft = -contentWidth; // ensure it's not visible anymore
  14449. }
  14450. }
  14451. else {
  14452. if (start < 0) {
  14453. contentLeft = Math.min(-start,
  14454. (end - start - contentWidth - 2 * this.options.padding));
  14455. // TODO: remove the need for options.padding. it's terrible.
  14456. }
  14457. else {
  14458. contentLeft = 0;
  14459. }
  14460. }
  14461. this.dom.content.style.left = contentLeft + 'px';
  14462. }
  14463. };
  14464. /**
  14465. * Reposition the item vertically
  14466. * @Override
  14467. */
  14468. RangeItem.prototype.repositionY = function() {
  14469. var orientation = this.options.orientation,
  14470. box = this.dom.box;
  14471. if (orientation == 'top') {
  14472. box.style.top = this.top + 'px';
  14473. }
  14474. else {
  14475. box.style.top = (this.parent.height - this.top - this.height) + 'px';
  14476. }
  14477. };
  14478. /**
  14479. * Repaint a drag area on the left side of the range when the range is selected
  14480. * @protected
  14481. */
  14482. RangeItem.prototype._repaintDragLeft = function () {
  14483. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  14484. // create and show drag area
  14485. var dragLeft = document.createElement('div');
  14486. dragLeft.className = 'drag-left';
  14487. dragLeft.dragLeftItem = this;
  14488. // TODO: this should be redundant?
  14489. Hammer(dragLeft, {
  14490. preventDefault: true
  14491. }).on('drag', function () {
  14492. //console.log('drag left')
  14493. });
  14494. this.dom.box.appendChild(dragLeft);
  14495. this.dom.dragLeft = dragLeft;
  14496. }
  14497. else if (!this.selected && this.dom.dragLeft) {
  14498. // delete drag area
  14499. if (this.dom.dragLeft.parentNode) {
  14500. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  14501. }
  14502. this.dom.dragLeft = null;
  14503. }
  14504. };
  14505. /**
  14506. * Repaint a drag area on the right side of the range when the range is selected
  14507. * @protected
  14508. */
  14509. RangeItem.prototype._repaintDragRight = function () {
  14510. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  14511. // create and show drag area
  14512. var dragRight = document.createElement('div');
  14513. dragRight.className = 'drag-right';
  14514. dragRight.dragRightItem = this;
  14515. // TODO: this should be redundant?
  14516. Hammer(dragRight, {
  14517. preventDefault: true
  14518. }).on('drag', function () {
  14519. //console.log('drag right')
  14520. });
  14521. this.dom.box.appendChild(dragRight);
  14522. this.dom.dragRight = dragRight;
  14523. }
  14524. else if (!this.selected && this.dom.dragRight) {
  14525. // delete drag area
  14526. if (this.dom.dragRight.parentNode) {
  14527. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  14528. }
  14529. this.dom.dragRight = null;
  14530. }
  14531. };
  14532. module.exports = RangeItem;
  14533. /***/ },
  14534. /* 30 */
  14535. /***/ function(module, exports, __webpack_require__) {
  14536. var Hammer = __webpack_require__(19);
  14537. var util = __webpack_require__(1);
  14538. /**
  14539. * @constructor Item
  14540. * @param {Object} data Object containing (optional) parameters type,
  14541. * start, end, content, group, className.
  14542. * @param {{toScreen: function, toTime: function}} conversion
  14543. * Conversion functions from time to screen and vice versa
  14544. * @param {Object} options Configuration options
  14545. * // TODO: describe available options
  14546. */
  14547. function Item (data, conversion, options) {
  14548. this.id = null;
  14549. this.parent = null;
  14550. this.data = data;
  14551. this.dom = null;
  14552. this.conversion = conversion || {};
  14553. this.options = options || {};
  14554. this.selected = false;
  14555. this.displayed = false;
  14556. this.dirty = true;
  14557. this.top = null;
  14558. this.left = null;
  14559. this.width = null;
  14560. this.height = null;
  14561. }
  14562. Item.prototype.stack = true;
  14563. /**
  14564. * Select current item
  14565. */
  14566. Item.prototype.select = function() {
  14567. this.selected = true;
  14568. this.dirty = true;
  14569. if (this.displayed) this.redraw();
  14570. };
  14571. /**
  14572. * Unselect current item
  14573. */
  14574. Item.prototype.unselect = function() {
  14575. this.selected = false;
  14576. this.dirty = true;
  14577. if (this.displayed) this.redraw();
  14578. };
  14579. /**
  14580. * Set data for the item. Existing data will be updated. The id should not
  14581. * be changed. When the item is displayed, it will be redrawn immediately.
  14582. * @param {Object} data
  14583. */
  14584. Item.prototype.setData = function(data) {
  14585. this.data = data;
  14586. this.dirty = true;
  14587. if (this.displayed) this.redraw();
  14588. };
  14589. /**
  14590. * Set a parent for the item
  14591. * @param {ItemSet | Group} parent
  14592. */
  14593. Item.prototype.setParent = function(parent) {
  14594. if (this.displayed) {
  14595. this.hide();
  14596. this.parent = parent;
  14597. if (this.parent) {
  14598. this.show();
  14599. }
  14600. }
  14601. else {
  14602. this.parent = parent;
  14603. }
  14604. };
  14605. /**
  14606. * Check whether this item is visible inside given range
  14607. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  14608. * @returns {boolean} True if visible
  14609. */
  14610. Item.prototype.isVisible = function(range) {
  14611. // Should be implemented by Item implementations
  14612. return false;
  14613. };
  14614. /**
  14615. * Show the Item in the DOM (when not already visible)
  14616. * @return {Boolean} changed
  14617. */
  14618. Item.prototype.show = function() {
  14619. return false;
  14620. };
  14621. /**
  14622. * Hide the Item from the DOM (when visible)
  14623. * @return {Boolean} changed
  14624. */
  14625. Item.prototype.hide = function() {
  14626. return false;
  14627. };
  14628. /**
  14629. * Repaint the item
  14630. */
  14631. Item.prototype.redraw = function() {
  14632. // should be implemented by the item
  14633. };
  14634. /**
  14635. * Reposition the Item horizontally
  14636. */
  14637. Item.prototype.repositionX = function() {
  14638. // should be implemented by the item
  14639. };
  14640. /**
  14641. * Reposition the Item vertically
  14642. */
  14643. Item.prototype.repositionY = function() {
  14644. // should be implemented by the item
  14645. };
  14646. /**
  14647. * Repaint a delete button on the top right of the item when the item is selected
  14648. * @param {HTMLElement} anchor
  14649. * @protected
  14650. */
  14651. Item.prototype._repaintDeleteButton = function (anchor) {
  14652. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  14653. // create and show button
  14654. var me = this;
  14655. var deleteButton = document.createElement('div');
  14656. deleteButton.className = 'delete';
  14657. deleteButton.title = 'Delete this item';
  14658. Hammer(deleteButton, {
  14659. preventDefault: true
  14660. }).on('tap', function (event) {
  14661. me.parent.removeFromDataSet(me);
  14662. event.stopPropagation();
  14663. });
  14664. anchor.appendChild(deleteButton);
  14665. this.dom.deleteButton = deleteButton;
  14666. }
  14667. else if (!this.selected && this.dom.deleteButton) {
  14668. // remove button
  14669. if (this.dom.deleteButton.parentNode) {
  14670. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  14671. }
  14672. this.dom.deleteButton = null;
  14673. }
  14674. };
  14675. /**
  14676. * Set HTML contents for the item
  14677. * @param {Element} element HTML element to fill with the contents
  14678. * @private
  14679. */
  14680. Item.prototype._updateContents = function (element) {
  14681. var content;
  14682. if (this.options.template) {
  14683. var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
  14684. content = this.options.template(itemData);
  14685. }
  14686. else {
  14687. content = this.data.content;
  14688. }
  14689. if(content !== this.content) {
  14690. // only replace the content when changed
  14691. if (content instanceof Element) {
  14692. element.innerHTML = '';
  14693. element.appendChild(content);
  14694. }
  14695. else if (content != undefined) {
  14696. element.innerHTML = content;
  14697. }
  14698. else {
  14699. if (!(this.data.type == 'background' && this.data.content === undefined)) {
  14700. throw new Error('Property "content" missing in item ' + this.id);
  14701. }
  14702. }
  14703. this.content = content;
  14704. }
  14705. };
  14706. /**
  14707. * Set HTML contents for the item
  14708. * @param {Element} element HTML element to fill with the contents
  14709. * @private
  14710. */
  14711. Item.prototype._updateTitle = function (element) {
  14712. if (this.data.title != null) {
  14713. element.title = this.data.title || '';
  14714. }
  14715. else {
  14716. element.removeAttribute('title');
  14717. }
  14718. };
  14719. /**
  14720. * Process dataAttributes timeline option and set as data- attributes on dom.content
  14721. * @param {Element} element HTML element to which the attributes will be attached
  14722. * @private
  14723. */
  14724. Item.prototype._updateDataAttributes = function(element) {
  14725. if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
  14726. var attributes = [];
  14727. if (Array.isArray(this.options.dataAttributes)) {
  14728. attributes = this.options.dataAttributes;
  14729. }
  14730. else if (this.options.dataAttributes == 'all') {
  14731. attributes = Object.keys(this.data);
  14732. }
  14733. else {
  14734. return;
  14735. }
  14736. for (var i = 0; i < attributes.length; i++) {
  14737. var name = attributes[i];
  14738. var value = this.data[name];
  14739. if (value != null) {
  14740. element.setAttribute('data-' + name, value);
  14741. }
  14742. else {
  14743. element.removeAttribute('data-' + name);
  14744. }
  14745. }
  14746. }
  14747. };
  14748. /**
  14749. * Update custom styles of the element
  14750. * @param element
  14751. * @private
  14752. */
  14753. Item.prototype._updateStyle = function(element) {
  14754. // remove old styles
  14755. if (this.style) {
  14756. util.removeCssText(element, this.style);
  14757. this.style = null;
  14758. }
  14759. // append new styles
  14760. if (this.data.style) {
  14761. util.addCssText(element, this.data.style);
  14762. this.style = this.data.style;
  14763. }
  14764. };
  14765. module.exports = Item;
  14766. /***/ },
  14767. /* 31 */
  14768. /***/ function(module, exports, __webpack_require__) {
  14769. var util = __webpack_require__(1);
  14770. var Group = __webpack_require__(27);
  14771. /**
  14772. * @constructor BackgroundGroup
  14773. * @param {Number | String} groupId
  14774. * @param {Object} data
  14775. * @param {ItemSet} itemSet
  14776. */
  14777. function BackgroundGroup (groupId, data, itemSet) {
  14778. Group.call(this, groupId, data, itemSet);
  14779. this.width = 0;
  14780. this.height = 0;
  14781. this.top = 0;
  14782. this.left = 0;
  14783. }
  14784. BackgroundGroup.prototype = Object.create(Group.prototype);
  14785. /**
  14786. * Repaint this group
  14787. * @param {{start: number, end: number}} range
  14788. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  14789. * @param {boolean} [restack=false] Force restacking of all items
  14790. * @return {boolean} Returns true if the group is resized
  14791. */
  14792. BackgroundGroup.prototype.redraw = function(range, margin, restack) {
  14793. var resized = false;
  14794. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  14795. // calculate actual size
  14796. this.width = this.dom.background.offsetWidth;
  14797. // apply new height (just always zero for BackgroundGroup
  14798. this.dom.background.style.height = '0';
  14799. // update vertical position of items after they are re-stacked and the height of the group is calculated
  14800. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  14801. var item = this.visibleItems[i];
  14802. item.repositionY(margin);
  14803. }
  14804. return resized;
  14805. };
  14806. /**
  14807. * Show this group: attach to the DOM
  14808. */
  14809. BackgroundGroup.prototype.show = function() {
  14810. if (!this.dom.background.parentNode) {
  14811. this.itemSet.dom.background.appendChild(this.dom.background);
  14812. }
  14813. };
  14814. module.exports = BackgroundGroup;
  14815. /***/ },
  14816. /* 32 */
  14817. /***/ function(module, exports, __webpack_require__) {
  14818. var Item = __webpack_require__(30);
  14819. var util = __webpack_require__(1);
  14820. /**
  14821. * @constructor BoxItem
  14822. * @extends Item
  14823. * @param {Object} data Object containing parameters start
  14824. * content, className.
  14825. * @param {{toScreen: function, toTime: function}} conversion
  14826. * Conversion functions from time to screen and vice versa
  14827. * @param {Object} [options] Configuration options
  14828. * // TODO: describe available options
  14829. */
  14830. function BoxItem (data, conversion, options) {
  14831. this.props = {
  14832. dot: {
  14833. width: 0,
  14834. height: 0
  14835. },
  14836. line: {
  14837. width: 0,
  14838. height: 0
  14839. }
  14840. };
  14841. // validate data
  14842. if (data) {
  14843. if (data.start == undefined) {
  14844. throw new Error('Property "start" missing in item ' + data);
  14845. }
  14846. }
  14847. Item.call(this, data, conversion, options);
  14848. }
  14849. BoxItem.prototype = new Item (null, null, null);
  14850. /**
  14851. * Check whether this item is visible inside given range
  14852. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  14853. * @returns {boolean} True if visible
  14854. */
  14855. BoxItem.prototype.isVisible = function(range) {
  14856. // determine visibility
  14857. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  14858. var interval = (range.end - range.start) / 4;
  14859. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  14860. };
  14861. /**
  14862. * Repaint the item
  14863. */
  14864. BoxItem.prototype.redraw = function() {
  14865. var dom = this.dom;
  14866. if (!dom) {
  14867. // create DOM
  14868. this.dom = {};
  14869. dom = this.dom;
  14870. // create main box
  14871. dom.box = document.createElement('DIV');
  14872. // contents box (inside the background box). used for making margins
  14873. dom.content = document.createElement('DIV');
  14874. dom.content.className = 'content';
  14875. dom.box.appendChild(dom.content);
  14876. // line to axis
  14877. dom.line = document.createElement('DIV');
  14878. dom.line.className = 'line';
  14879. // dot on axis
  14880. dom.dot = document.createElement('DIV');
  14881. dom.dot.className = 'dot';
  14882. // attach this item as attribute
  14883. dom.box['timeline-item'] = this;
  14884. this.dirty = true;
  14885. }
  14886. // append DOM to parent DOM
  14887. if (!this.parent) {
  14888. throw new Error('Cannot redraw item: no parent attached');
  14889. }
  14890. if (!dom.box.parentNode) {
  14891. var foreground = this.parent.dom.foreground;
  14892. if (!foreground) throw new Error('Cannot redraw item: parent has no foreground container element');
  14893. foreground.appendChild(dom.box);
  14894. }
  14895. if (!dom.line.parentNode) {
  14896. var background = this.parent.dom.background;
  14897. if (!background) throw new Error('Cannot redraw item: parent has no background container element');
  14898. background.appendChild(dom.line);
  14899. }
  14900. if (!dom.dot.parentNode) {
  14901. var axis = this.parent.dom.axis;
  14902. if (!background) throw new Error('Cannot redraw item: parent has no axis container element');
  14903. axis.appendChild(dom.dot);
  14904. }
  14905. this.displayed = true;
  14906. // Update DOM when item is marked dirty. An item is marked dirty when:
  14907. // - the item is not yet rendered
  14908. // - the item's data is changed
  14909. // - the item is selected/deselected
  14910. if (this.dirty) {
  14911. this._updateContents(this.dom.content);
  14912. this._updateTitle(this.dom.box);
  14913. this._updateDataAttributes(this.dom.box);
  14914. this._updateStyle(this.dom.box);
  14915. // update class
  14916. var className = (this.data.className? ' ' + this.data.className : '') +
  14917. (this.selected ? ' selected' : '');
  14918. dom.box.className = 'item box' + className;
  14919. dom.line.className = 'item line' + className;
  14920. dom.dot.className = 'item dot' + className;
  14921. // recalculate size
  14922. this.props.dot.height = dom.dot.offsetHeight;
  14923. this.props.dot.width = dom.dot.offsetWidth;
  14924. this.props.line.width = dom.line.offsetWidth;
  14925. this.width = dom.box.offsetWidth;
  14926. this.height = dom.box.offsetHeight;
  14927. this.dirty = false;
  14928. }
  14929. this._repaintDeleteButton(dom.box);
  14930. };
  14931. /**
  14932. * Show the item in the DOM (when not already displayed). The items DOM will
  14933. * be created when needed.
  14934. */
  14935. BoxItem.prototype.show = function() {
  14936. if (!this.displayed) {
  14937. this.redraw();
  14938. }
  14939. };
  14940. /**
  14941. * Hide the item from the DOM (when visible)
  14942. */
  14943. BoxItem.prototype.hide = function() {
  14944. if (this.displayed) {
  14945. var dom = this.dom;
  14946. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  14947. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  14948. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  14949. this.top = null;
  14950. this.left = null;
  14951. this.displayed = false;
  14952. }
  14953. };
  14954. /**
  14955. * Reposition the item horizontally
  14956. * @Override
  14957. */
  14958. BoxItem.prototype.repositionX = function() {
  14959. var start = this.conversion.toScreen(this.data.start);
  14960. var align = this.options.align;
  14961. var left;
  14962. var box = this.dom.box;
  14963. var line = this.dom.line;
  14964. var dot = this.dom.dot;
  14965. // calculate left position of the box
  14966. if (align == 'right') {
  14967. this.left = start - this.width;
  14968. }
  14969. else if (align == 'left') {
  14970. this.left = start;
  14971. }
  14972. else {
  14973. // default or 'center'
  14974. this.left = start - this.width / 2;
  14975. }
  14976. // reposition box
  14977. box.style.left = this.left + 'px';
  14978. // reposition line
  14979. line.style.left = (start - this.props.line.width / 2) + 'px';
  14980. // reposition dot
  14981. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  14982. };
  14983. /**
  14984. * Reposition the item vertically
  14985. * @Override
  14986. */
  14987. BoxItem.prototype.repositionY = function() {
  14988. var orientation = this.options.orientation;
  14989. var box = this.dom.box;
  14990. var line = this.dom.line;
  14991. var dot = this.dom.dot;
  14992. if (orientation == 'top') {
  14993. box.style.top = (this.top || 0) + 'px';
  14994. line.style.top = '0';
  14995. line.style.height = (this.parent.top + this.top + 1) + 'px';
  14996. line.style.bottom = '';
  14997. }
  14998. else { // orientation 'bottom'
  14999. var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
  15000. var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
  15001. box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
  15002. line.style.top = (itemSetHeight - lineHeight) + 'px';
  15003. line.style.bottom = '0';
  15004. }
  15005. dot.style.top = (-this.props.dot.height / 2) + 'px';
  15006. };
  15007. module.exports = BoxItem;
  15008. /***/ },
  15009. /* 33 */
  15010. /***/ function(module, exports, __webpack_require__) {
  15011. var Item = __webpack_require__(30);
  15012. /**
  15013. * @constructor PointItem
  15014. * @extends Item
  15015. * @param {Object} data Object containing parameters start
  15016. * content, className.
  15017. * @param {{toScreen: function, toTime: function}} conversion
  15018. * Conversion functions from time to screen and vice versa
  15019. * @param {Object} [options] Configuration options
  15020. * // TODO: describe available options
  15021. */
  15022. function PointItem (data, conversion, options) {
  15023. this.props = {
  15024. dot: {
  15025. top: 0,
  15026. width: 0,
  15027. height: 0
  15028. },
  15029. content: {
  15030. height: 0,
  15031. marginLeft: 0
  15032. }
  15033. };
  15034. // validate data
  15035. if (data) {
  15036. if (data.start == undefined) {
  15037. throw new Error('Property "start" missing in item ' + data);
  15038. }
  15039. }
  15040. Item.call(this, data, conversion, options);
  15041. }
  15042. PointItem.prototype = new Item (null, null, null);
  15043. /**
  15044. * Check whether this item is visible inside given range
  15045. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  15046. * @returns {boolean} True if visible
  15047. */
  15048. PointItem.prototype.isVisible = function(range) {
  15049. // determine visibility
  15050. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  15051. var interval = (range.end - range.start) / 4;
  15052. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  15053. };
  15054. /**
  15055. * Repaint the item
  15056. */
  15057. PointItem.prototype.redraw = function() {
  15058. var dom = this.dom;
  15059. if (!dom) {
  15060. // create DOM
  15061. this.dom = {};
  15062. dom = this.dom;
  15063. // background box
  15064. dom.point = document.createElement('div');
  15065. // className is updated in redraw()
  15066. // contents box, right from the dot
  15067. dom.content = document.createElement('div');
  15068. dom.content.className = 'content';
  15069. dom.point.appendChild(dom.content);
  15070. // dot at start
  15071. dom.dot = document.createElement('div');
  15072. dom.point.appendChild(dom.dot);
  15073. // attach this item as attribute
  15074. dom.point['timeline-item'] = this;
  15075. this.dirty = true;
  15076. }
  15077. // append DOM to parent DOM
  15078. if (!this.parent) {
  15079. throw new Error('Cannot redraw item: no parent attached');
  15080. }
  15081. if (!dom.point.parentNode) {
  15082. var foreground = this.parent.dom.foreground;
  15083. if (!foreground) {
  15084. throw new Error('Cannot redraw item: parent has no foreground container element');
  15085. }
  15086. foreground.appendChild(dom.point);
  15087. }
  15088. this.displayed = true;
  15089. // Update DOM when item is marked dirty. An item is marked dirty when:
  15090. // - the item is not yet rendered
  15091. // - the item's data is changed
  15092. // - the item is selected/deselected
  15093. if (this.dirty) {
  15094. this._updateContents(this.dom.content);
  15095. this._updateTitle(this.dom.point);
  15096. this._updateDataAttributes(this.dom.point);
  15097. this._updateStyle(this.dom.point);
  15098. // update class
  15099. var className = (this.data.className? ' ' + this.data.className : '') +
  15100. (this.selected ? ' selected' : '');
  15101. dom.point.className = 'item point' + className;
  15102. dom.dot.className = 'item dot' + className;
  15103. // recalculate size
  15104. this.width = dom.point.offsetWidth;
  15105. this.height = dom.point.offsetHeight;
  15106. this.props.dot.width = dom.dot.offsetWidth;
  15107. this.props.dot.height = dom.dot.offsetHeight;
  15108. this.props.content.height = dom.content.offsetHeight;
  15109. // resize contents
  15110. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  15111. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  15112. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  15113. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  15114. this.dirty = false;
  15115. }
  15116. this._repaintDeleteButton(dom.point);
  15117. };
  15118. /**
  15119. * Show the item in the DOM (when not already visible). The items DOM will
  15120. * be created when needed.
  15121. */
  15122. PointItem.prototype.show = function() {
  15123. if (!this.displayed) {
  15124. this.redraw();
  15125. }
  15126. };
  15127. /**
  15128. * Hide the item from the DOM (when visible)
  15129. */
  15130. PointItem.prototype.hide = function() {
  15131. if (this.displayed) {
  15132. if (this.dom.point.parentNode) {
  15133. this.dom.point.parentNode.removeChild(this.dom.point);
  15134. }
  15135. this.top = null;
  15136. this.left = null;
  15137. this.displayed = false;
  15138. }
  15139. };
  15140. /**
  15141. * Reposition the item horizontally
  15142. * @Override
  15143. */
  15144. PointItem.prototype.repositionX = function() {
  15145. var start = this.conversion.toScreen(this.data.start);
  15146. this.left = start - this.props.dot.width;
  15147. // reposition point
  15148. this.dom.point.style.left = this.left + 'px';
  15149. };
  15150. /**
  15151. * Reposition the item vertically
  15152. * @Override
  15153. */
  15154. PointItem.prototype.repositionY = function() {
  15155. var orientation = this.options.orientation,
  15156. point = this.dom.point;
  15157. if (orientation == 'top') {
  15158. point.style.top = this.top + 'px';
  15159. }
  15160. else {
  15161. point.style.top = (this.parent.height - this.top - this.height) + 'px';
  15162. }
  15163. };
  15164. module.exports = PointItem;
  15165. /***/ },
  15166. /* 34 */
  15167. /***/ function(module, exports, __webpack_require__) {
  15168. var Hammer = __webpack_require__(19);
  15169. var Item = __webpack_require__(30);
  15170. var BackgroundGroup = __webpack_require__(31);
  15171. var RangeItem = __webpack_require__(29);
  15172. /**
  15173. * @constructor BackgroundItem
  15174. * @extends Item
  15175. * @param {Object} data Object containing parameters start, end
  15176. * content, className.
  15177. * @param {{toScreen: function, toTime: function}} conversion
  15178. * Conversion functions from time to screen and vice versa
  15179. * @param {Object} [options] Configuration options
  15180. * // TODO: describe options
  15181. */
  15182. // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
  15183. function BackgroundItem (data, conversion, options) {
  15184. this.props = {
  15185. content: {
  15186. width: 0
  15187. }
  15188. };
  15189. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  15190. // validate data
  15191. if (data) {
  15192. if (data.start == undefined) {
  15193. throw new Error('Property "start" missing in item ' + data.id);
  15194. }
  15195. if (data.end == undefined) {
  15196. throw new Error('Property "end" missing in item ' + data.id);
  15197. }
  15198. }
  15199. Item.call(this, data, conversion, options);
  15200. this.emptyContent = false;
  15201. }
  15202. BackgroundItem.prototype = new Item (null, null, null);
  15203. BackgroundItem.prototype.baseClassName = 'item background';
  15204. BackgroundItem.prototype.stack = false;
  15205. /**
  15206. * Check whether this item is visible inside given range
  15207. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  15208. * @returns {boolean} True if visible
  15209. */
  15210. BackgroundItem.prototype.isVisible = function(range) {
  15211. // determine visibility
  15212. return (this.data.start < range.end) && (this.data.end > range.start);
  15213. };
  15214. /**
  15215. * Repaint the item
  15216. */
  15217. BackgroundItem.prototype.redraw = function() {
  15218. var dom = this.dom;
  15219. if (!dom) {
  15220. // create DOM
  15221. this.dom = {};
  15222. dom = this.dom;
  15223. // background box
  15224. dom.box = document.createElement('div');
  15225. // className is updated in redraw()
  15226. // contents box
  15227. dom.content = document.createElement('div');
  15228. dom.content.className = 'content';
  15229. dom.box.appendChild(dom.content);
  15230. // Note: we do NOT attach this item as attribute to the DOM,
  15231. // such that background items cannot be selected
  15232. //dom.box['timeline-item'] = this;
  15233. this.dirty = true;
  15234. }
  15235. // append DOM to parent DOM
  15236. if (!this.parent) {
  15237. throw new Error('Cannot redraw item: no parent attached');
  15238. }
  15239. if (!dom.box.parentNode) {
  15240. var background = this.parent.dom.background;
  15241. if (!background) {
  15242. throw new Error('Cannot redraw item: parent has no background container element');
  15243. }
  15244. background.appendChild(dom.box);
  15245. }
  15246. this.displayed = true;
  15247. // Update DOM when item is marked dirty. An item is marked dirty when:
  15248. // - the item is not yet rendered
  15249. // - the item's data is changed
  15250. // - the item is selected/deselected
  15251. if (this.dirty) {
  15252. this._updateContents(this.dom.content);
  15253. this._updateTitle(this.dom.content);
  15254. this._updateDataAttributes(this.dom.content);
  15255. this._updateStyle(this.dom.box);
  15256. // update class
  15257. var className = (this.data.className ? (' ' + this.data.className) : '') +
  15258. (this.selected ? ' selected' : '');
  15259. dom.box.className = this.baseClassName + className;
  15260. // determine from css whether this box has overflow
  15261. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  15262. // recalculate size
  15263. this.props.content.width = this.dom.content.offsetWidth;
  15264. this.height = 0; // set height zero, so this item will be ignored when stacking items
  15265. this.dirty = false;
  15266. }
  15267. };
  15268. /**
  15269. * Show the item in the DOM (when not already visible). The items DOM will
  15270. * be created when needed.
  15271. */
  15272. BackgroundItem.prototype.show = RangeItem.prototype.show;
  15273. /**
  15274. * Hide the item from the DOM (when visible)
  15275. * @return {Boolean} changed
  15276. */
  15277. BackgroundItem.prototype.hide = RangeItem.prototype.hide;
  15278. /**
  15279. * Reposition the item horizontally
  15280. * @Override
  15281. */
  15282. BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX;
  15283. /**
  15284. * Reposition the item vertically
  15285. * @Override
  15286. */
  15287. BackgroundItem.prototype.repositionY = function(margin) {
  15288. var onTop = this.options.orientation === 'top';
  15289. this.dom.content.style.top = onTop ? '' : '0';
  15290. this.dom.content.style.bottom = onTop ? '0' : '';
  15291. var height;
  15292. // special positioning for subgroups
  15293. if (this.data.subgroup !== undefined) {
  15294. var itemSubgroup = this.data.subgroup;
  15295. var subgroups = this.parent.subgroups;
  15296. var subgroupIndex = subgroups[itemSubgroup].index;
  15297. // if the orientation is top, we need to take the difference in height into account.
  15298. if (onTop == true) {
  15299. // the first subgroup will have to account for the distance from the top to the first item.
  15300. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  15301. height += subgroupIndex == 0 ? margin.axis - 0.5*margin.item.vertical : 0;
  15302. var newTop = this.parent.top;
  15303. for (var subgroup in subgroups) {
  15304. if (subgroups.hasOwnProperty(subgroup)) {
  15305. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) {
  15306. newTop += subgroups[subgroup].height + margin.item.vertical;
  15307. }
  15308. }
  15309. }
  15310. // the others will have to be offset downwards with this same distance.
  15311. newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0;
  15312. this.dom.box.style.top = newTop + 'px';
  15313. this.dom.box.style.bottom = '';
  15314. }
  15315. // and when the orientation is bottom:
  15316. else {
  15317. var newTop = this.parent.top;
  15318. for (var subgroup in subgroups) {
  15319. if (subgroups.hasOwnProperty(subgroup)) {
  15320. if (subgroups[subgroup].visible == true && subgroups[subgroup].index > subgroupIndex) {
  15321. newTop += subgroups[subgroup].height + margin.item.vertical;
  15322. }
  15323. }
  15324. }
  15325. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  15326. this.dom.box.style.top = newTop + 'px';
  15327. this.dom.box.style.bottom = '';
  15328. }
  15329. }
  15330. // and in the case of no subgroups:
  15331. else {
  15332. // we want backgrounds with groups to only show in groups.
  15333. if (this.parent instanceof BackgroundGroup) {
  15334. // if the item is not in a group:
  15335. height = Math.max(this.parent.height,
  15336. this.parent.itemSet.body.domProps.center.height,
  15337. this.parent.itemSet.body.domProps.centerContainer.height);
  15338. this.dom.box.style.top = onTop ? '0' : '';
  15339. this.dom.box.style.bottom = onTop ? '' : '0';
  15340. }
  15341. else {
  15342. height = this.parent.height;
  15343. // same alignment for items when orientation is top or bottom
  15344. this.dom.box.style.top = this.parent.top + 'px';
  15345. this.dom.box.style.bottom = '';
  15346. }
  15347. }
  15348. this.dom.box.style.height = height + 'px';
  15349. };
  15350. module.exports = BackgroundItem;
  15351. /***/ },
  15352. /* 35 */
  15353. /***/ function(module, exports, __webpack_require__) {
  15354. var keycharm = __webpack_require__(36);
  15355. var Emitter = __webpack_require__(11);
  15356. var Hammer = __webpack_require__(19);
  15357. var util = __webpack_require__(1);
  15358. /**
  15359. * Turn an element into an clickToUse element.
  15360. * When not active, the element has a transparent overlay. When the overlay is
  15361. * clicked, the mode is changed to active.
  15362. * When active, the element is displayed with a blue border around it, and
  15363. * the interactive contents of the element can be used. When clicked outside
  15364. * the element, the elements mode is changed to inactive.
  15365. * @param {Element} container
  15366. * @constructor
  15367. */
  15368. function Activator(container) {
  15369. this.active = false;
  15370. this.dom = {
  15371. container: container
  15372. };
  15373. this.dom.overlay = document.createElement('div');
  15374. this.dom.overlay.className = 'overlay';
  15375. this.dom.container.appendChild(this.dom.overlay);
  15376. this.hammer = Hammer(this.dom.overlay, {prevent_default: false});
  15377. this.hammer.on('tap', this._onTapOverlay.bind(this));
  15378. // block all touch events (except tap)
  15379. var me = this;
  15380. var events = [
  15381. 'touch', 'pinch',
  15382. 'doubletap', 'hold',
  15383. 'dragstart', 'drag', 'dragend',
  15384. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  15385. ];
  15386. events.forEach(function (event) {
  15387. me.hammer.on(event, function (event) {
  15388. event.stopPropagation();
  15389. });
  15390. });
  15391. // attach a tap event to the window, in order to deactivate when clicking outside the timeline
  15392. this.windowHammer = Hammer(window, {prevent_default: false});
  15393. this.windowHammer.on('tap', function (event) {
  15394. // deactivate when clicked outside the container
  15395. if (!_hasParent(event.target, container)) {
  15396. me.deactivate();
  15397. }
  15398. });
  15399. if (this.keycharm !== undefined) {
  15400. this.keycharm.destroy();
  15401. }
  15402. this.keycharm = keycharm();
  15403. // keycharm listener only bounded when active)
  15404. this.escListener = this.deactivate.bind(this);
  15405. }
  15406. // turn into an event emitter
  15407. Emitter(Activator.prototype);
  15408. // The currently active activator
  15409. Activator.current = null;
  15410. /**
  15411. * Destroy the activator. Cleans up all created DOM and event listeners
  15412. */
  15413. Activator.prototype.destroy = function () {
  15414. this.deactivate();
  15415. // remove dom
  15416. this.dom.overlay.parentNode.removeChild(this.dom.overlay);
  15417. // cleanup hammer instances
  15418. this.hammer = null;
  15419. this.windowHammer = null;
  15420. // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
  15421. };
  15422. /**
  15423. * Activate the element
  15424. * Overlay is hidden, element is decorated with a blue shadow border
  15425. */
  15426. Activator.prototype.activate = function () {
  15427. // we allow only one active activator at a time
  15428. if (Activator.current) {
  15429. Activator.current.deactivate();
  15430. }
  15431. Activator.current = this;
  15432. this.active = true;
  15433. this.dom.overlay.style.display = 'none';
  15434. util.addClassName(this.dom.container, 'vis-active');
  15435. this.emit('change');
  15436. this.emit('activate');
  15437. // ugly hack: bind ESC after emitting the events, as the Network rebinds all
  15438. // keyboard events on a 'change' event
  15439. this.keycharm.bind('esc', this.escListener);
  15440. };
  15441. /**
  15442. * Deactivate the element
  15443. * Overlay is displayed on top of the element
  15444. */
  15445. Activator.prototype.deactivate = function () {
  15446. this.active = false;
  15447. this.dom.overlay.style.display = '';
  15448. util.removeClassName(this.dom.container, 'vis-active');
  15449. this.keycharm.unbind('esc', this.escListener);
  15450. this.emit('change');
  15451. this.emit('deactivate');
  15452. };
  15453. /**
  15454. * Handle a tap event: activate the container
  15455. * @param event
  15456. * @private
  15457. */
  15458. Activator.prototype._onTapOverlay = function (event) {
  15459. // activate the container
  15460. this.activate();
  15461. event.stopPropagation();
  15462. };
  15463. /**
  15464. * Test whether the element has the requested parent element somewhere in
  15465. * its chain of parent nodes.
  15466. * @param {HTMLElement} element
  15467. * @param {HTMLElement} parent
  15468. * @returns {boolean} Returns true when the parent is found somewhere in the
  15469. * chain of parent nodes.
  15470. * @private
  15471. */
  15472. function _hasParent(element, parent) {
  15473. while (element) {
  15474. if (element === parent) {
  15475. return true
  15476. }
  15477. element = element.parentNode;
  15478. }
  15479. return false;
  15480. }
  15481. module.exports = Activator;
  15482. /***/ },
  15483. /* 36 */
  15484. /***/ function(module, exports, __webpack_require__) {
  15485. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
  15486. /**
  15487. * Created by Alex on 11/6/2014.
  15488. */
  15489. // https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
  15490. // if the module has no dependencies, the above pattern can be simplified to
  15491. (function (root, factory) {
  15492. if (true) {
  15493. // AMD. Register as an anonymous module.
  15494. !(__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__));
  15495. } else if (typeof exports === 'object') {
  15496. // Node. Does not work with strict CommonJS, but
  15497. // only CommonJS-like environments that support module.exports,
  15498. // like Node.
  15499. module.exports = factory();
  15500. } else {
  15501. // Browser globals (root is window)
  15502. root.keycharm = factory();
  15503. }
  15504. }(this, function () {
  15505. function keycharm(options) {
  15506. var preventDefault = options && options.preventDefault || false;
  15507. var _exportFunctions = {};
  15508. var _bound = {keydown:{}, keyup:{}};
  15509. var _keys = {};
  15510. var i;
  15511. // a - z
  15512. for (i = 97; i <= 122; i++) {_keys[String.fromCharCode(i)] = {code:65 + (i - 97), shift: false};}
  15513. // A - Z
  15514. for (i = 65; i <= 90; i++) {_keys[String.fromCharCode(i)] = {code:i, shift: true};}
  15515. // 0 - 9
  15516. for (i = 0; i <= 9; i++) {_keys['' + i] = {code:48 + i, shift: false};}
  15517. // F1 - F12
  15518. for (i = 1; i <= 12; i++) {_keys['F' + i] = {code:111 + i, shift: false};}
  15519. // num0 - num9
  15520. for (i = 0; i <= 9; i++) {_keys['num' + i] = {code:96 + i, shift: false};}
  15521. // numpad misc
  15522. _keys['num*'] = {code:106, shift: false};
  15523. _keys['num+'] = {code:107, shift: false};
  15524. _keys['num-'] = {code:109, shift: false};
  15525. _keys['num/'] = {code:111, shift: false};
  15526. _keys['num.'] = {code:110, shift: false};
  15527. // arrows
  15528. _keys['left'] = {code:37, shift: false};
  15529. _keys['up'] = {code:38, shift: false};
  15530. _keys['right'] = {code:39, shift: false};
  15531. _keys['down'] = {code:40, shift: false};
  15532. // extra keys
  15533. _keys['space'] = {code:32, shift: false};
  15534. _keys['enter'] = {code:13, shift: false};
  15535. _keys['shift'] = {code:16, shift: undefined};
  15536. _keys['esc'] = {code:27, shift: false};
  15537. _keys['backspace'] = {code:8, shift: false};
  15538. _keys['tab'] = {code:9, shift: false};
  15539. _keys['ctrl'] = {code:17, shift: false};
  15540. _keys['alt'] = {code:18, shift: false};
  15541. _keys['delete'] = {code:46, shift: false};
  15542. _keys['pageup'] = {code:33, shift: false};
  15543. _keys['pagedown'] = {code:34, shift: false};
  15544. // symbols
  15545. _keys['='] = {code:187, shift: false};
  15546. _keys['-'] = {code:189, shift: false};
  15547. _keys[']'] = {code:221, shift: false};
  15548. _keys['['] = {code:219, shift: false};
  15549. var down = function(event) {handleEvent(event,'keydown');};
  15550. var up = function(event) {handleEvent(event,'keyup');};
  15551. // handle the actualy bound key with the event
  15552. var handleEvent = function(event,type) {
  15553. if (_bound[type][event.keyCode] !== undefined) {
  15554. var bound = _bound[type][event.keyCode];
  15555. for (var i = 0; i < bound.length; i++) {
  15556. if (bound[i].shift === undefined) {
  15557. bound[i].fn(event);
  15558. }
  15559. else if (bound[i].shift == true && event.shiftKey == true) {
  15560. bound[i].fn(event);
  15561. }
  15562. else if (bound[i].shift == false && event.shiftKey == false) {
  15563. bound[i].fn(event);
  15564. }
  15565. }
  15566. if (preventDefault == true) {
  15567. event.preventDefault();
  15568. }
  15569. }
  15570. };
  15571. // bind a key to a callback
  15572. _exportFunctions.bind = function(key, callback, type) {
  15573. if (type === undefined) {
  15574. type = 'keydown';
  15575. }
  15576. if (_keys[key] === undefined) {
  15577. throw new Error("unsupported key: " + key);
  15578. }
  15579. if (_bound[type][_keys[key].code] === undefined) {
  15580. _bound[type][_keys[key].code] = [];
  15581. }
  15582. _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift});
  15583. };
  15584. // bind all keys to a call back (demo purposes)
  15585. _exportFunctions.bindAll = function(callback, type) {
  15586. if (type === undefined) {
  15587. type = 'keydown';
  15588. }
  15589. for (var key in _keys) {
  15590. if (_keys.hasOwnProperty(key)) {
  15591. _exportFunctions.bind(key,callback,type);
  15592. }
  15593. }
  15594. };
  15595. // get the key label from an event
  15596. _exportFunctions.getKey = function(event) {
  15597. for (var key in _keys) {
  15598. if (_keys.hasOwnProperty(key)) {
  15599. if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
  15600. return key;
  15601. }
  15602. else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
  15603. return key;
  15604. }
  15605. else if (event.keyCode == _keys[key].code && key == 'shift') {
  15606. return key;
  15607. }
  15608. }
  15609. }
  15610. return "unknown key, currently not supported";
  15611. };
  15612. // unbind either a specific callback from a key or all of them (by leaving callback undefined)
  15613. _exportFunctions.unbind = function(key, callback, type) {
  15614. if (type === undefined) {
  15615. type = 'keydown';
  15616. }
  15617. if (_keys[key] === undefined) {
  15618. throw new Error("unsupported key: " + key);
  15619. }
  15620. if (callback !== undefined) {
  15621. var newBindings = [];
  15622. var bound = _bound[type][_keys[key].code];
  15623. if (bound !== undefined) {
  15624. for (var i = 0; i < bound.length; i++) {
  15625. if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
  15626. newBindings.push(_bound[type][_keys[key].code][i]);
  15627. }
  15628. }
  15629. }
  15630. _bound[type][_keys[key].code] = newBindings;
  15631. }
  15632. else {
  15633. _bound[type][_keys[key].code] = [];
  15634. }
  15635. };
  15636. // reset all bound variables.
  15637. _exportFunctions.reset = function() {
  15638. _bound = {keydown:{}, keyup:{}};
  15639. };
  15640. // unbind all listeners and reset all variables.
  15641. _exportFunctions.destroy = function() {
  15642. _bound = {keydown:{}, keyup:{}};
  15643. window.removeEventListener('keydown', down, true);
  15644. window.removeEventListener('keyup', up, true);
  15645. };
  15646. // create listeners.
  15647. window.addEventListener('keydown',down,true);
  15648. window.addEventListener('keyup',up,true);
  15649. // return the public functions.
  15650. return _exportFunctions;
  15651. }
  15652. return keycharm;
  15653. }));
  15654. /***/ },
  15655. /* 37 */
  15656. /***/ function(module, exports, __webpack_require__) {
  15657. var util = __webpack_require__(1);
  15658. var Component = __webpack_require__(23);
  15659. var TimeStep = __webpack_require__(38);
  15660. var DateUtil = __webpack_require__(24);
  15661. var moment = __webpack_require__(2);
  15662. /**
  15663. * A horizontal time axis
  15664. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  15665. * @param {Object} [options] See TimeAxis.setOptions for the available
  15666. * options.
  15667. * @constructor TimeAxis
  15668. * @extends Component
  15669. */
  15670. function TimeAxis (body, options) {
  15671. this.dom = {
  15672. foreground: null,
  15673. majorLines: [],
  15674. majorTexts: [],
  15675. minorLines: [],
  15676. minorTexts: [],
  15677. redundant: {
  15678. majorLines: [],
  15679. majorTexts: [],
  15680. minorLines: [],
  15681. minorTexts: []
  15682. }
  15683. };
  15684. this.props = {
  15685. range: {
  15686. start: 0,
  15687. end: 0,
  15688. minimumStep: 0
  15689. },
  15690. lineTop: 0
  15691. };
  15692. this.defaultOptions = {
  15693. orientation: 'bottom', // supported: 'top', 'bottom'
  15694. // TODO: implement timeaxis orientations 'left' and 'right'
  15695. showMinorLabels: true,
  15696. showMajorLabels: true,
  15697. showMajorLines: true,
  15698. showMinorLines: true,
  15699. format: null
  15700. };
  15701. this.options = util.extend({}, this.defaultOptions);
  15702. this.body = body;
  15703. // create the HTML DOM
  15704. this._create();
  15705. this.setOptions(options);
  15706. }
  15707. TimeAxis.prototype = new Component();
  15708. /**
  15709. * Set options for the TimeAxis.
  15710. * Parameters will be merged in current options.
  15711. * @param {Object} options Available options:
  15712. * {string} [orientation]
  15713. * {boolean} [showMinorLabels]
  15714. * {boolean} [showMajorLabels]
  15715. */
  15716. TimeAxis.prototype.setOptions = function(options) {
  15717. if (options) {
  15718. // copy all options that we know
  15719. util.selectiveExtend(['orientation', 'showMinorLabels', 'showMajorLabels', 'showMinorLines', 'showMajorLines','hiddenDates', 'format'], this.options, options);
  15720. // apply locale to moment.js
  15721. // TODO: not so nice, this is applied globally to moment.js
  15722. if ('locale' in options) {
  15723. if (typeof moment.locale === 'function') {
  15724. // moment.js 2.8.1+
  15725. moment.locale(options.locale);
  15726. }
  15727. else {
  15728. moment.lang(options.locale);
  15729. }
  15730. }
  15731. }
  15732. };
  15733. /**
  15734. * Create the HTML DOM for the TimeAxis
  15735. */
  15736. TimeAxis.prototype._create = function() {
  15737. this.dom.foreground = document.createElement('div');
  15738. this.dom.background = document.createElement('div');
  15739. this.dom.foreground.className = 'timeaxis foreground';
  15740. this.dom.background.className = 'timeaxis background';
  15741. };
  15742. /**
  15743. * Destroy the TimeAxis
  15744. */
  15745. TimeAxis.prototype.destroy = function() {
  15746. // remove from DOM
  15747. if (this.dom.foreground.parentNode) {
  15748. this.dom.foreground.parentNode.removeChild(this.dom.foreground);
  15749. }
  15750. if (this.dom.background.parentNode) {
  15751. this.dom.background.parentNode.removeChild(this.dom.background);
  15752. }
  15753. this.body = null;
  15754. };
  15755. /**
  15756. * Repaint the component
  15757. * @return {boolean} Returns true if the component is resized
  15758. */
  15759. TimeAxis.prototype.redraw = function () {
  15760. var options = this.options;
  15761. var props = this.props;
  15762. var foreground = this.dom.foreground;
  15763. var background = this.dom.background;
  15764. // determine the correct parent DOM element (depending on option orientation)
  15765. var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom;
  15766. var parentChanged = (foreground.parentNode !== parent);
  15767. // calculate character width and height
  15768. this._calculateCharSize();
  15769. // TODO: recalculate sizes only needed when parent is resized or options is changed
  15770. var orientation = this.options.orientation,
  15771. showMinorLabels = this.options.showMinorLabels,
  15772. showMajorLabels = this.options.showMajorLabels;
  15773. // determine the width and height of the elemens for the axis
  15774. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  15775. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  15776. props.height = props.minorLabelHeight + props.majorLabelHeight;
  15777. props.width = foreground.offsetWidth;
  15778. props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight -
  15779. (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
  15780. props.minorLineWidth = 1; // TODO: really calculate width
  15781. props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
  15782. props.majorLineWidth = 1; // TODO: really calculate width
  15783. // take foreground and background offline while updating (is almost twice as fast)
  15784. var foregroundNextSibling = foreground.nextSibling;
  15785. var backgroundNextSibling = background.nextSibling;
  15786. foreground.parentNode && foreground.parentNode.removeChild(foreground);
  15787. background.parentNode && background.parentNode.removeChild(background);
  15788. foreground.style.height = this.props.height + 'px';
  15789. this._repaintLabels();
  15790. // put DOM online again (at the same place)
  15791. if (foregroundNextSibling) {
  15792. parent.insertBefore(foreground, foregroundNextSibling);
  15793. }
  15794. else {
  15795. parent.appendChild(foreground)
  15796. }
  15797. if (backgroundNextSibling) {
  15798. this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
  15799. }
  15800. else {
  15801. this.body.dom.backgroundVertical.appendChild(background)
  15802. }
  15803. return this._isResized() || parentChanged;
  15804. };
  15805. /**
  15806. * Repaint major and minor text labels and vertical grid lines
  15807. * @private
  15808. */
  15809. TimeAxis.prototype._repaintLabels = function () {
  15810. var orientation = this.options.orientation;
  15811. // calculate range and step (step such that we have space for 7 characters per label)
  15812. var start = util.convert(this.body.range.start, 'Number');
  15813. var end = util.convert(this.body.range.end, 'Number');
  15814. var timeLabelsize = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf();
  15815. var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this.body.range, timeLabelsize);
  15816. minimumStep -= this.body.util.toTime(0).valueOf();
  15817. var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates);
  15818. if (this.options.format) {
  15819. step.setFormat(this.options.format);
  15820. }
  15821. this.step = step;
  15822. // Move all DOM elements to a "redundant" list, where they
  15823. // can be picked for re-use, and clear the lists with lines and texts.
  15824. // At the end of the function _repaintLabels, left over elements will be cleaned up
  15825. var dom = this.dom;
  15826. dom.redundant.majorLines = dom.majorLines;
  15827. dom.redundant.majorTexts = dom.majorTexts;
  15828. dom.redundant.minorLines = dom.minorLines;
  15829. dom.redundant.minorTexts = dom.minorTexts;
  15830. dom.majorLines = [];
  15831. dom.majorTexts = [];
  15832. dom.minorLines = [];
  15833. dom.minorTexts = [];
  15834. step.first();
  15835. var xFirstMajorLabel = undefined;
  15836. var max = 0;
  15837. while (step.hasNext() && max < 1000) {
  15838. max++;
  15839. var cur = step.getCurrent();
  15840. var x = this.body.util.toScreen(cur);
  15841. var isMajor = step.isMajor();
  15842. // TODO: lines must have a width, such that we can create css backgrounds
  15843. if (this.options.showMinorLabels) {
  15844. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  15845. }
  15846. if (isMajor && this.options.showMajorLabels) {
  15847. if (x > 0) {
  15848. if (xFirstMajorLabel == undefined) {
  15849. xFirstMajorLabel = x;
  15850. }
  15851. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  15852. }
  15853. if (this.options.showMajorLines == true) {
  15854. this._repaintMajorLine(x, orientation);
  15855. }
  15856. }
  15857. else if (this.options.showMinorLines == true) {
  15858. this._repaintMinorLine(x, orientation);
  15859. }
  15860. step.next();
  15861. }
  15862. // create a major label on the left when needed
  15863. if (this.options.showMajorLabels) {
  15864. var leftTime = this.body.util.toTime(0),
  15865. leftText = step.getLabelMajor(leftTime),
  15866. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  15867. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  15868. this._repaintMajorText(0, leftText, orientation);
  15869. }
  15870. }
  15871. // Cleanup leftover DOM elements from the redundant list
  15872. util.forEach(this.dom.redundant, function (arr) {
  15873. while (arr.length) {
  15874. var elem = arr.pop();
  15875. if (elem && elem.parentNode) {
  15876. elem.parentNode.removeChild(elem);
  15877. }
  15878. }
  15879. });
  15880. };
  15881. /**
  15882. * Create a minor label for the axis at position x
  15883. * @param {Number} x
  15884. * @param {String} text
  15885. * @param {String} orientation "top" or "bottom" (default)
  15886. * @private
  15887. */
  15888. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  15889. // reuse redundant label
  15890. var label = this.dom.redundant.minorTexts.shift();
  15891. if (!label) {
  15892. // create new label
  15893. var content = document.createTextNode('');
  15894. label = document.createElement('div');
  15895. label.appendChild(content);
  15896. label.className = 'text minor';
  15897. this.dom.foreground.appendChild(label);
  15898. }
  15899. this.dom.minorTexts.push(label);
  15900. label.childNodes[0].nodeValue = text;
  15901. label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0';
  15902. label.style.left = x + 'px';
  15903. //label.title = title; // TODO: this is a heavy operation
  15904. };
  15905. /**
  15906. * Create a Major label for the axis at position x
  15907. * @param {Number} x
  15908. * @param {String} text
  15909. * @param {String} orientation "top" or "bottom" (default)
  15910. * @private
  15911. */
  15912. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  15913. // reuse redundant label
  15914. var label = this.dom.redundant.majorTexts.shift();
  15915. if (!label) {
  15916. // create label
  15917. var content = document.createTextNode(text);
  15918. label = document.createElement('div');
  15919. label.className = 'text major';
  15920. label.appendChild(content);
  15921. this.dom.foreground.appendChild(label);
  15922. }
  15923. this.dom.majorTexts.push(label);
  15924. label.childNodes[0].nodeValue = text;
  15925. //label.title = title; // TODO: this is a heavy operation
  15926. label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px');
  15927. label.style.left = x + 'px';
  15928. };
  15929. /**
  15930. * Create a minor line for the axis at position x
  15931. * @param {Number} x
  15932. * @param {String} orientation "top" or "bottom" (default)
  15933. * @private
  15934. */
  15935. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  15936. // reuse redundant line
  15937. var line = this.dom.redundant.minorLines.shift();
  15938. if (!line) {
  15939. // create vertical line
  15940. line = document.createElement('div');
  15941. line.className = 'grid vertical minor';
  15942. this.dom.background.appendChild(line);
  15943. }
  15944. this.dom.minorLines.push(line);
  15945. var props = this.props;
  15946. if (orientation == 'top') {
  15947. line.style.top = props.majorLabelHeight + 'px';
  15948. }
  15949. else {
  15950. line.style.top = this.body.domProps.top.height + 'px';
  15951. }
  15952. line.style.height = props.minorLineHeight + 'px';
  15953. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  15954. };
  15955. /**
  15956. * Create a Major line for the axis at position x
  15957. * @param {Number} x
  15958. * @param {String} orientation "top" or "bottom" (default)
  15959. * @private
  15960. */
  15961. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  15962. // reuse redundant line
  15963. var line = this.dom.redundant.majorLines.shift();
  15964. if (!line) {
  15965. // create vertical line
  15966. line = document.createElement('DIV');
  15967. line.className = 'grid vertical major';
  15968. this.dom.background.appendChild(line);
  15969. }
  15970. this.dom.majorLines.push(line);
  15971. var props = this.props;
  15972. if (orientation == 'top') {
  15973. line.style.top = '0';
  15974. }
  15975. else {
  15976. line.style.top = this.body.domProps.top.height + 'px';
  15977. }
  15978. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  15979. line.style.height = props.majorLineHeight + 'px';
  15980. };
  15981. /**
  15982. * Determine the size of text on the axis (both major and minor axis).
  15983. * The size is calculated only once and then cached in this.props.
  15984. * @private
  15985. */
  15986. TimeAxis.prototype._calculateCharSize = function () {
  15987. // Note: We calculate char size with every redraw. Size may change, for
  15988. // example when any of the timelines parents had display:none for example.
  15989. // determine the char width and height on the minor axis
  15990. if (!this.dom.measureCharMinor) {
  15991. this.dom.measureCharMinor = document.createElement('DIV');
  15992. this.dom.measureCharMinor.className = 'text minor measure';
  15993. this.dom.measureCharMinor.style.position = 'absolute';
  15994. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  15995. this.dom.foreground.appendChild(this.dom.measureCharMinor);
  15996. }
  15997. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  15998. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  15999. // determine the char width and height on the major axis
  16000. if (!this.dom.measureCharMajor) {
  16001. this.dom.measureCharMajor = document.createElement('DIV');
  16002. this.dom.measureCharMajor.className = 'text major measure';
  16003. this.dom.measureCharMajor.style.position = 'absolute';
  16004. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  16005. this.dom.foreground.appendChild(this.dom.measureCharMajor);
  16006. }
  16007. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  16008. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  16009. };
  16010. /**
  16011. * Snap a date to a rounded value.
  16012. * The snap intervals are dependent on the current scale and step.
  16013. * @param {Date} date the date to be snapped.
  16014. * @return {Date} snappedDate
  16015. */
  16016. TimeAxis.prototype.snap = function(date) {
  16017. return this.step.snap(date);
  16018. };
  16019. module.exports = TimeAxis;
  16020. /***/ },
  16021. /* 38 */
  16022. /***/ function(module, exports, __webpack_require__) {
  16023. var moment = __webpack_require__(2);
  16024. var DateUtil = __webpack_require__(24);
  16025. var util = __webpack_require__(1);
  16026. /**
  16027. * @constructor TimeStep
  16028. * The class TimeStep is an iterator for dates. You provide a start date and an
  16029. * end date. The class itself determines the best scale (step size) based on the
  16030. * provided start Date, end Date, and minimumStep.
  16031. *
  16032. * If minimumStep is provided, the step size is chosen as close as possible
  16033. * to the minimumStep but larger than minimumStep. If minimumStep is not
  16034. * provided, the scale is set to 1 DAY.
  16035. * The minimumStep should correspond with the onscreen size of about 6 characters
  16036. *
  16037. * Alternatively, you can set a scale by hand.
  16038. * After creation, you can initialize the class by executing first(). Then you
  16039. * can iterate from the start date to the end date via next(). You can check if
  16040. * the end date is reached with the function hasNext(). After each step, you can
  16041. * retrieve the current date via getCurrent().
  16042. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  16043. * days, to years.
  16044. *
  16045. * Version: 1.2
  16046. *
  16047. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  16048. * or new Date(2010, 9, 21, 23, 45, 00)
  16049. * @param {Date} [end] The end date
  16050. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  16051. */
  16052. function TimeStep(start, end, minimumStep, hiddenDates) {
  16053. // variables
  16054. this.current = new Date();
  16055. this._start = new Date();
  16056. this._end = new Date();
  16057. this.autoScale = true;
  16058. this.scale = 'day';
  16059. this.step = 1;
  16060. // initialize the range
  16061. this.setRange(start, end, minimumStep);
  16062. // hidden Dates options
  16063. this.switchedDay = false;
  16064. this.switchedMonth = false;
  16065. this.switchedYear = false;
  16066. this.hiddenDates = hiddenDates;
  16067. if (hiddenDates === undefined) {
  16068. this.hiddenDates = [];
  16069. }
  16070. this.format = TimeStep.FORMAT; // default formatting
  16071. }
  16072. // Time formatting
  16073. TimeStep.FORMAT = {
  16074. minorLabels: {
  16075. millisecond:'SSS',
  16076. second: 's',
  16077. minute: 'HH:mm',
  16078. hour: 'HH:mm',
  16079. weekday: 'ddd D',
  16080. day: 'D',
  16081. month: 'MMM',
  16082. year: 'YYYY'
  16083. },
  16084. majorLabels: {
  16085. millisecond:'HH:mm:ss',
  16086. second: 'D MMMM HH:mm',
  16087. minute: 'ddd D MMMM',
  16088. hour: 'ddd D MMMM',
  16089. weekday: 'MMMM YYYY',
  16090. day: 'MMMM YYYY',
  16091. month: 'YYYY',
  16092. year: ''
  16093. }
  16094. };
  16095. /**
  16096. * Set custom formatting for the minor an major labels of the TimeStep.
  16097. * Both `minorLabels` and `majorLabels` are an Object with properties:
  16098. * 'millisecond, 'second, 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  16099. * @param {{minorLabels: Object, majorLabels: Object}} format
  16100. */
  16101. TimeStep.prototype.setFormat = function (format) {
  16102. var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
  16103. this.format = util.deepExtend(defaultFormat, format);
  16104. };
  16105. /**
  16106. * Set a new range
  16107. * If minimumStep is provided, the step size is chosen as close as possible
  16108. * to the minimumStep but larger than minimumStep. If minimumStep is not
  16109. * provided, the scale is set to 1 DAY.
  16110. * The minimumStep should correspond with the onscreen size of about 6 characters
  16111. * @param {Date} [start] The start date and time.
  16112. * @param {Date} [end] The end date and time.
  16113. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  16114. */
  16115. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  16116. if (!(start instanceof Date) || !(end instanceof Date)) {
  16117. throw "No legal start or end date in method setRange";
  16118. }
  16119. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  16120. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  16121. if (this.autoScale) {
  16122. this.setMinimumStep(minimumStep);
  16123. }
  16124. };
  16125. /**
  16126. * Set the range iterator to the start date.
  16127. */
  16128. TimeStep.prototype.first = function() {
  16129. this.current = new Date(this._start.valueOf());
  16130. this.roundToMinor();
  16131. };
  16132. /**
  16133. * Round the current date to the first minor date value
  16134. * This must be executed once when the current date is set to start Date
  16135. */
  16136. TimeStep.prototype.roundToMinor = function() {
  16137. // round to floor
  16138. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  16139. //noinspection FallthroughInSwitchStatementJS
  16140. switch (this.scale) {
  16141. case 'year':
  16142. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  16143. this.current.setMonth(0);
  16144. case 'month': this.current.setDate(1);
  16145. case 'day': // intentional fall through
  16146. case 'weekday': this.current.setHours(0);
  16147. case 'hour': this.current.setMinutes(0);
  16148. case 'minute': this.current.setSeconds(0);
  16149. case 'second': this.current.setMilliseconds(0);
  16150. //case 'millisecond': // nothing to do for milliseconds
  16151. }
  16152. if (this.step != 1) {
  16153. // round down to the first minor value that is a multiple of the current step size
  16154. switch (this.scale) {
  16155. case 'millisecond': this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  16156. case 'second': this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  16157. case 'minute': this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  16158. case 'hour': this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  16159. case 'weekday': // intentional fall through
  16160. case 'day': this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  16161. case 'month': this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  16162. case 'year': this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  16163. default: break;
  16164. }
  16165. }
  16166. };
  16167. /**
  16168. * Check if the there is a next step
  16169. * @return {boolean} true if the current date has not passed the end date
  16170. */
  16171. TimeStep.prototype.hasNext = function () {
  16172. return (this.current.valueOf() <= this._end.valueOf());
  16173. };
  16174. /**
  16175. * Do the next step
  16176. */
  16177. TimeStep.prototype.next = function() {
  16178. var prev = this.current.valueOf();
  16179. // Two cases, needed to prevent issues with switching daylight savings
  16180. // (end of March and end of October)
  16181. if (this.current.getMonth() < 6) {
  16182. switch (this.scale) {
  16183. case 'millisecond':
  16184. this.current = new Date(this.current.valueOf() + this.step); break;
  16185. case 'second': this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  16186. case 'minute': this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  16187. case 'hour':
  16188. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  16189. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  16190. var h = this.current.getHours();
  16191. this.current.setHours(h - (h % this.step));
  16192. break;
  16193. case 'weekday': // intentional fall through
  16194. case 'day': this.current.setDate(this.current.getDate() + this.step); break;
  16195. case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
  16196. case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
  16197. default: break;
  16198. }
  16199. }
  16200. else {
  16201. switch (this.scale) {
  16202. case 'millisecond': this.current = new Date(this.current.valueOf() + this.step); break;
  16203. case 'second': this.current.setSeconds(this.current.getSeconds() + this.step); break;
  16204. case 'minute': this.current.setMinutes(this.current.getMinutes() + this.step); break;
  16205. case 'hour': this.current.setHours(this.current.getHours() + this.step); break;
  16206. case 'weekday': // intentional fall through
  16207. case 'day': this.current.setDate(this.current.getDate() + this.step); break;
  16208. case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
  16209. case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
  16210. default: break;
  16211. }
  16212. }
  16213. if (this.step != 1) {
  16214. // round down to the correct major value
  16215. switch (this.scale) {
  16216. case 'millisecond': if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  16217. case 'second': if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  16218. case 'minute': if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  16219. case 'hour': if(this.current.getHours() < this.step) this.current.setHours(0); break;
  16220. case 'weekday': // intentional fall through
  16221. case 'day': if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  16222. case 'month': if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  16223. case 'year': break; // nothing to do for year
  16224. default: break;
  16225. }
  16226. }
  16227. // safety mechanism: if current time is still unchanged, move to the end
  16228. if (this.current.valueOf() == prev) {
  16229. this.current = new Date(this._end.valueOf());
  16230. }
  16231. DateUtil.stepOverHiddenDates(this, prev);
  16232. };
  16233. /**
  16234. * Get the current datetime
  16235. * @return {Date} current The current date
  16236. */
  16237. TimeStep.prototype.getCurrent = function() {
  16238. return this.current;
  16239. };
  16240. /**
  16241. * Set a custom scale. Autoscaling will be disabled.
  16242. * For example setScale(SCALE.MINUTES, 5) will result
  16243. * in minor steps of 5 minutes, and major steps of an hour.
  16244. *
  16245. * @param {string} newScale
  16246. * A scale. Choose from 'millisecond, 'second,
  16247. * 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  16248. * @param {Number} newStep A step size, by default 1. Choose for
  16249. * example 1, 2, 5, or 10.
  16250. */
  16251. TimeStep.prototype.setScale = function(newScale, newStep) {
  16252. this.scale = newScale;
  16253. if (newStep > 0) {
  16254. this.step = newStep;
  16255. }
  16256. this.autoScale = false;
  16257. };
  16258. /**
  16259. * Enable or disable autoscaling
  16260. * @param {boolean} enable If true, autoascaling is set true
  16261. */
  16262. TimeStep.prototype.setAutoScale = function (enable) {
  16263. this.autoScale = enable;
  16264. };
  16265. /**
  16266. * Automatically determine the scale that bests fits the provided minimum step
  16267. * @param {Number} [minimumStep] The minimum step size in milliseconds
  16268. */
  16269. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  16270. if (minimumStep == undefined) {
  16271. return;
  16272. }
  16273. //var b = asc + ds;
  16274. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  16275. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  16276. var stepDay = (1000 * 60 * 60 * 24);
  16277. var stepHour = (1000 * 60 * 60);
  16278. var stepMinute = (1000 * 60);
  16279. var stepSecond = (1000);
  16280. var stepMillisecond= (1);
  16281. // find the smallest step that is larger than the provided minimumStep
  16282. if (stepYear*1000 > minimumStep) {this.scale = 'year'; this.step = 1000;}
  16283. if (stepYear*500 > minimumStep) {this.scale = 'year'; this.step = 500;}
  16284. if (stepYear*100 > minimumStep) {this.scale = 'year'; this.step = 100;}
  16285. if (stepYear*50 > minimumStep) {this.scale = 'year'; this.step = 50;}
  16286. if (stepYear*10 > minimumStep) {this.scale = 'year'; this.step = 10;}
  16287. if (stepYear*5 > minimumStep) {this.scale = 'year'; this.step = 5;}
  16288. if (stepYear > minimumStep) {this.scale = 'year'; this.step = 1;}
  16289. if (stepMonth*3 > minimumStep) {this.scale = 'month'; this.step = 3;}
  16290. if (stepMonth > minimumStep) {this.scale = 'month'; this.step = 1;}
  16291. if (stepDay*5 > minimumStep) {this.scale = 'day'; this.step = 5;}
  16292. if (stepDay*2 > minimumStep) {this.scale = 'day'; this.step = 2;}
  16293. if (stepDay > minimumStep) {this.scale = 'day'; this.step = 1;}
  16294. if (stepDay/2 > minimumStep) {this.scale = 'weekday'; this.step = 1;}
  16295. if (stepHour*4 > minimumStep) {this.scale = 'hour'; this.step = 4;}
  16296. if (stepHour > minimumStep) {this.scale = 'hour'; this.step = 1;}
  16297. if (stepMinute*15 > minimumStep) {this.scale = 'minute'; this.step = 15;}
  16298. if (stepMinute*10 > minimumStep) {this.scale = 'minute'; this.step = 10;}
  16299. if (stepMinute*5 > minimumStep) {this.scale = 'minute'; this.step = 5;}
  16300. if (stepMinute > minimumStep) {this.scale = 'minute'; this.step = 1;}
  16301. if (stepSecond*15 > minimumStep) {this.scale = 'second'; this.step = 15;}
  16302. if (stepSecond*10 > minimumStep) {this.scale = 'second'; this.step = 10;}
  16303. if (stepSecond*5 > minimumStep) {this.scale = 'second'; this.step = 5;}
  16304. if (stepSecond > minimumStep) {this.scale = 'second'; this.step = 1;}
  16305. if (stepMillisecond*200 > minimumStep) {this.scale = 'millisecond'; this.step = 200;}
  16306. if (stepMillisecond*100 > minimumStep) {this.scale = 'millisecond'; this.step = 100;}
  16307. if (stepMillisecond*50 > minimumStep) {this.scale = 'millisecond'; this.step = 50;}
  16308. if (stepMillisecond*10 > minimumStep) {this.scale = 'millisecond'; this.step = 10;}
  16309. if (stepMillisecond*5 > minimumStep) {this.scale = 'millisecond'; this.step = 5;}
  16310. if (stepMillisecond > minimumStep) {this.scale = 'millisecond'; this.step = 1;}
  16311. };
  16312. /**
  16313. * Snap a date to a rounded value.
  16314. * The snap intervals are dependent on the current scale and step.
  16315. * @param {Date} date the date to be snapped.
  16316. * @return {Date} snappedDate
  16317. */
  16318. TimeStep.prototype.snap = function(date) {
  16319. var clone = new Date(date.valueOf());
  16320. if (this.scale == 'year') {
  16321. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  16322. clone.setFullYear(Math.round(year / this.step) * this.step);
  16323. clone.setMonth(0);
  16324. clone.setDate(0);
  16325. clone.setHours(0);
  16326. clone.setMinutes(0);
  16327. clone.setSeconds(0);
  16328. clone.setMilliseconds(0);
  16329. }
  16330. else if (this.scale == 'month') {
  16331. if (clone.getDate() > 15) {
  16332. clone.setDate(1);
  16333. clone.setMonth(clone.getMonth() + 1);
  16334. // important: first set Date to 1, after that change the month.
  16335. }
  16336. else {
  16337. clone.setDate(1);
  16338. }
  16339. clone.setHours(0);
  16340. clone.setMinutes(0);
  16341. clone.setSeconds(0);
  16342. clone.setMilliseconds(0);
  16343. }
  16344. else if (this.scale == 'day') {
  16345. //noinspection FallthroughInSwitchStatementJS
  16346. switch (this.step) {
  16347. case 5:
  16348. case 2:
  16349. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  16350. default:
  16351. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  16352. }
  16353. clone.setMinutes(0);
  16354. clone.setSeconds(0);
  16355. clone.setMilliseconds(0);
  16356. }
  16357. else if (this.scale == 'weekday') {
  16358. //noinspection FallthroughInSwitchStatementJS
  16359. switch (this.step) {
  16360. case 5:
  16361. case 2:
  16362. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  16363. default:
  16364. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  16365. }
  16366. clone.setMinutes(0);
  16367. clone.setSeconds(0);
  16368. clone.setMilliseconds(0);
  16369. }
  16370. else if (this.scale == 'hour') {
  16371. switch (this.step) {
  16372. case 4:
  16373. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  16374. default:
  16375. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  16376. }
  16377. clone.setSeconds(0);
  16378. clone.setMilliseconds(0);
  16379. } else if (this.scale == 'minute') {
  16380. //noinspection FallthroughInSwitchStatementJS
  16381. switch (this.step) {
  16382. case 15:
  16383. case 10:
  16384. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  16385. clone.setSeconds(0);
  16386. break;
  16387. case 5:
  16388. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  16389. default:
  16390. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  16391. }
  16392. clone.setMilliseconds(0);
  16393. }
  16394. else if (this.scale == 'second') {
  16395. //noinspection FallthroughInSwitchStatementJS
  16396. switch (this.step) {
  16397. case 15:
  16398. case 10:
  16399. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  16400. clone.setMilliseconds(0);
  16401. break;
  16402. case 5:
  16403. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  16404. default:
  16405. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  16406. }
  16407. }
  16408. else if (this.scale == 'millisecond') {
  16409. var step = this.step > 5 ? this.step / 2 : 1;
  16410. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  16411. }
  16412. return clone;
  16413. };
  16414. /**
  16415. * Check if the current value is a major value (for example when the step
  16416. * is DAY, a major value is each first day of the MONTH)
  16417. * @return {boolean} true if current date is major, else false.
  16418. */
  16419. TimeStep.prototype.isMajor = function() {
  16420. if (this.switchedYear == true) {
  16421. this.switchedYear = false;
  16422. switch (this.scale) {
  16423. case 'year':
  16424. case 'month':
  16425. case 'weekday':
  16426. case 'day':
  16427. case 'hour':
  16428. case 'minute':
  16429. case 'second':
  16430. case 'millisecond':
  16431. return true;
  16432. default:
  16433. return false;
  16434. }
  16435. }
  16436. else if (this.switchedMonth == true) {
  16437. this.switchedMonth = false;
  16438. switch (this.scale) {
  16439. case 'weekday':
  16440. case 'day':
  16441. case 'hour':
  16442. case 'minute':
  16443. case 'second':
  16444. case 'millisecond':
  16445. return true;
  16446. default:
  16447. return false;
  16448. }
  16449. }
  16450. else if (this.switchedDay == true) {
  16451. this.switchedDay = false;
  16452. switch (this.scale) {
  16453. case 'millisecond':
  16454. case 'second':
  16455. case 'minute':
  16456. case 'hour':
  16457. return true;
  16458. default:
  16459. return false;
  16460. }
  16461. }
  16462. switch (this.scale) {
  16463. case 'millisecond':
  16464. return (this.current.getMilliseconds() == 0);
  16465. case 'second':
  16466. return (this.current.getSeconds() == 0);
  16467. case 'minute':
  16468. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  16469. case 'hour':
  16470. return (this.current.getHours() == 0);
  16471. case 'weekday': // intentional fall through
  16472. case 'day':
  16473. return (this.current.getDate() == 1);
  16474. case 'month':
  16475. return (this.current.getMonth() == 0);
  16476. case 'year':
  16477. return false;
  16478. default:
  16479. return false;
  16480. }
  16481. };
  16482. /**
  16483. * Returns formatted text for the minor axislabel, depending on the current
  16484. * date and the scale. For example when scale is MINUTE, the current time is
  16485. * formatted as "hh:mm".
  16486. * @param {Date} [date] custom date. if not provided, current date is taken
  16487. */
  16488. TimeStep.prototype.getLabelMinor = function(date) {
  16489. if (date == undefined) {
  16490. date = this.current;
  16491. }
  16492. var format = this.format.minorLabels[this.scale];
  16493. return (format && format.length > 0) ? moment(date).format(format) : '';
  16494. };
  16495. /**
  16496. * Returns formatted text for the major axis label, depending on the current
  16497. * date and the scale. For example when scale is MINUTE, the major scale is
  16498. * hours, and the hour will be formatted as "hh".
  16499. * @param {Date} [date] custom date. if not provided, current date is taken
  16500. */
  16501. TimeStep.prototype.getLabelMajor = function(date) {
  16502. if (date == undefined) {
  16503. date = this.current;
  16504. }
  16505. var format = this.format.majorLabels[this.scale];
  16506. return (format && format.length > 0) ? moment(date).format(format) : '';
  16507. };
  16508. module.exports = TimeStep;
  16509. /***/ },
  16510. /* 39 */
  16511. /***/ function(module, exports, __webpack_require__) {
  16512. var util = __webpack_require__(1);
  16513. var Component = __webpack_require__(23);
  16514. var moment = __webpack_require__(2);
  16515. var locales = __webpack_require__(40);
  16516. /**
  16517. * A current time bar
  16518. * @param {{range: Range, dom: Object, domProps: Object}} body
  16519. * @param {Object} [options] Available parameters:
  16520. * {Boolean} [showCurrentTime]
  16521. * @constructor CurrentTime
  16522. * @extends Component
  16523. */
  16524. function CurrentTime (body, options) {
  16525. this.body = body;
  16526. // default options
  16527. this.defaultOptions = {
  16528. showCurrentTime: true,
  16529. locales: locales,
  16530. locale: 'en'
  16531. };
  16532. this.options = util.extend({}, this.defaultOptions);
  16533. this.offset = 0;
  16534. this._create();
  16535. this.setOptions(options);
  16536. }
  16537. CurrentTime.prototype = new Component();
  16538. /**
  16539. * Create the HTML DOM for the current time bar
  16540. * @private
  16541. */
  16542. CurrentTime.prototype._create = function() {
  16543. var bar = document.createElement('div');
  16544. bar.className = 'currenttime';
  16545. bar.style.position = 'absolute';
  16546. bar.style.top = '0px';
  16547. bar.style.height = '100%';
  16548. this.bar = bar;
  16549. };
  16550. /**
  16551. * Destroy the CurrentTime bar
  16552. */
  16553. CurrentTime.prototype.destroy = function () {
  16554. this.options.showCurrentTime = false;
  16555. this.redraw(); // will remove the bar from the DOM and stop refreshing
  16556. this.body = null;
  16557. };
  16558. /**
  16559. * Set options for the component. Options will be merged in current options.
  16560. * @param {Object} options Available parameters:
  16561. * {boolean} [showCurrentTime]
  16562. */
  16563. CurrentTime.prototype.setOptions = function(options) {
  16564. if (options) {
  16565. // copy all options that we know
  16566. util.selectiveExtend(['showCurrentTime', 'locale', 'locales'], this.options, options);
  16567. }
  16568. };
  16569. /**
  16570. * Repaint the component
  16571. * @return {boolean} Returns true if the component is resized
  16572. */
  16573. CurrentTime.prototype.redraw = function() {
  16574. if (this.options.showCurrentTime) {
  16575. var parent = this.body.dom.backgroundVertical;
  16576. if (this.bar.parentNode != parent) {
  16577. // attach to the dom
  16578. if (this.bar.parentNode) {
  16579. this.bar.parentNode.removeChild(this.bar);
  16580. }
  16581. parent.appendChild(this.bar);
  16582. this.start();
  16583. }
  16584. var now = new Date(new Date().valueOf() + this.offset);
  16585. var x = this.body.util.toScreen(now);
  16586. var locale = this.options.locales[this.options.locale];
  16587. var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss');
  16588. title = title.charAt(0).toUpperCase() + title.substring(1);
  16589. this.bar.style.left = x + 'px';
  16590. this.bar.title = title;
  16591. }
  16592. else {
  16593. // remove the line from the DOM
  16594. if (this.bar.parentNode) {
  16595. this.bar.parentNode.removeChild(this.bar);
  16596. }
  16597. this.stop();
  16598. }
  16599. return false;
  16600. };
  16601. /**
  16602. * Start auto refreshing the current time bar
  16603. */
  16604. CurrentTime.prototype.start = function() {
  16605. var me = this;
  16606. function update () {
  16607. me.stop();
  16608. // determine interval to refresh
  16609. var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
  16610. var interval = 1 / scale / 10;
  16611. if (interval < 30) interval = 30;
  16612. if (interval > 1000) interval = 1000;
  16613. me.redraw();
  16614. // start a timer to adjust for the new time
  16615. me.currentTimeTimer = setTimeout(update, interval);
  16616. }
  16617. update();
  16618. };
  16619. /**
  16620. * Stop auto refreshing the current time bar
  16621. */
  16622. CurrentTime.prototype.stop = function() {
  16623. if (this.currentTimeTimer !== undefined) {
  16624. clearTimeout(this.currentTimeTimer);
  16625. delete this.currentTimeTimer;
  16626. }
  16627. };
  16628. /**
  16629. * Set a current time. This can be used for example to ensure that a client's
  16630. * time is synchronized with a shared server time.
  16631. * @param {Date | String | Number} time A Date, unix timestamp, or
  16632. * ISO date string.
  16633. */
  16634. CurrentTime.prototype.setCurrentTime = function(time) {
  16635. var t = util.convert(time, 'Date').valueOf();
  16636. var now = new Date().valueOf();
  16637. this.offset = t - now;
  16638. this.redraw();
  16639. };
  16640. /**
  16641. * Get the current time.
  16642. * @return {Date} Returns the current time.
  16643. */
  16644. CurrentTime.prototype.getCurrentTime = function() {
  16645. return new Date(new Date().valueOf() + this.offset);
  16646. };
  16647. module.exports = CurrentTime;
  16648. /***/ },
  16649. /* 40 */
  16650. /***/ function(module, exports, __webpack_require__) {
  16651. // English
  16652. exports['en'] = {
  16653. current: 'current',
  16654. time: 'time'
  16655. };
  16656. exports['en_EN'] = exports['en'];
  16657. exports['en_US'] = exports['en'];
  16658. // Dutch
  16659. exports['nl'] = {
  16660. custom: 'aangepaste',
  16661. time: 'tijd'
  16662. };
  16663. exports['nl_NL'] = exports['nl'];
  16664. exports['nl_BE'] = exports['nl'];
  16665. /***/ },
  16666. /* 41 */
  16667. /***/ function(module, exports, __webpack_require__) {
  16668. var Hammer = __webpack_require__(19);
  16669. var util = __webpack_require__(1);
  16670. var Component = __webpack_require__(23);
  16671. var moment = __webpack_require__(2);
  16672. var locales = __webpack_require__(40);
  16673. /**
  16674. * A custom time bar
  16675. * @param {{range: Range, dom: Object}} body
  16676. * @param {Object} [options] Available parameters:
  16677. * {Boolean} [showCustomTime]
  16678. * @constructor CustomTime
  16679. * @extends Component
  16680. */
  16681. function CustomTime (body, options) {
  16682. this.body = body;
  16683. // default options
  16684. this.defaultOptions = {
  16685. showCustomTime: false,
  16686. locales: locales,
  16687. locale: 'en'
  16688. };
  16689. this.options = util.extend({}, this.defaultOptions);
  16690. this.customTime = new Date();
  16691. this.eventParams = {}; // stores state parameters while dragging the bar
  16692. // create the DOM
  16693. this._create();
  16694. this.setOptions(options);
  16695. }
  16696. CustomTime.prototype = new Component();
  16697. /**
  16698. * Set options for the component. Options will be merged in current options.
  16699. * @param {Object} options Available parameters:
  16700. * {boolean} [showCustomTime]
  16701. */
  16702. CustomTime.prototype.setOptions = function(options) {
  16703. if (options) {
  16704. // copy all options that we know
  16705. util.selectiveExtend(['showCustomTime', 'locale', 'locales'], this.options, options);
  16706. }
  16707. };
  16708. /**
  16709. * Create the DOM for the custom time
  16710. * @private
  16711. */
  16712. CustomTime.prototype._create = function() {
  16713. var bar = document.createElement('div');
  16714. bar.className = 'customtime';
  16715. bar.style.position = 'absolute';
  16716. bar.style.top = '0px';
  16717. bar.style.height = '100%';
  16718. this.bar = bar;
  16719. var drag = document.createElement('div');
  16720. drag.style.position = 'relative';
  16721. drag.style.top = '0px';
  16722. drag.style.left = '-10px';
  16723. drag.style.height = '100%';
  16724. drag.style.width = '20px';
  16725. bar.appendChild(drag);
  16726. // attach event listeners
  16727. this.hammer = Hammer(bar, {
  16728. prevent_default: true
  16729. });
  16730. this.hammer.on('dragstart', this._onDragStart.bind(this));
  16731. this.hammer.on('drag', this._onDrag.bind(this));
  16732. this.hammer.on('dragend', this._onDragEnd.bind(this));
  16733. };
  16734. /**
  16735. * Destroy the CustomTime bar
  16736. */
  16737. CustomTime.prototype.destroy = function () {
  16738. this.options.showCustomTime = false;
  16739. this.redraw(); // will remove the bar from the DOM
  16740. this.hammer.enable(false);
  16741. this.hammer = null;
  16742. this.body = null;
  16743. };
  16744. /**
  16745. * Repaint the component
  16746. * @return {boolean} Returns true if the component is resized
  16747. */
  16748. CustomTime.prototype.redraw = function () {
  16749. if (this.options.showCustomTime) {
  16750. var parent = this.body.dom.backgroundVertical;
  16751. if (this.bar.parentNode != parent) {
  16752. // attach to the dom
  16753. if (this.bar.parentNode) {
  16754. this.bar.parentNode.removeChild(this.bar);
  16755. }
  16756. parent.appendChild(this.bar);
  16757. }
  16758. var x = this.body.util.toScreen(this.customTime);
  16759. var locale = this.options.locales[this.options.locale];
  16760. var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
  16761. title = title.charAt(0).toUpperCase() + title.substring(1);
  16762. this.bar.style.left = x + 'px';
  16763. this.bar.title = title;
  16764. }
  16765. else {
  16766. // remove the line from the DOM
  16767. if (this.bar.parentNode) {
  16768. this.bar.parentNode.removeChild(this.bar);
  16769. }
  16770. }
  16771. return false;
  16772. };
  16773. /**
  16774. * Set custom time.
  16775. * @param {Date | number | string} time
  16776. */
  16777. CustomTime.prototype.setCustomTime = function(time) {
  16778. this.customTime = util.convert(time, 'Date');
  16779. this.redraw();
  16780. };
  16781. /**
  16782. * Retrieve the current custom time.
  16783. * @return {Date} customTime
  16784. */
  16785. CustomTime.prototype.getCustomTime = function() {
  16786. return new Date(this.customTime.valueOf());
  16787. };
  16788. /**
  16789. * Start moving horizontally
  16790. * @param {Event} event
  16791. * @private
  16792. */
  16793. CustomTime.prototype._onDragStart = function(event) {
  16794. this.eventParams.dragging = true;
  16795. this.eventParams.customTime = this.customTime;
  16796. event.stopPropagation();
  16797. event.preventDefault();
  16798. };
  16799. /**
  16800. * Perform moving operating.
  16801. * @param {Event} event
  16802. * @private
  16803. */
  16804. CustomTime.prototype._onDrag = function (event) {
  16805. if (!this.eventParams.dragging) return;
  16806. var deltaX = event.gesture.deltaX,
  16807. x = this.body.util.toScreen(this.eventParams.customTime) + deltaX,
  16808. time = this.body.util.toTime(x);
  16809. this.setCustomTime(time);
  16810. // fire a timechange event
  16811. this.body.emitter.emit('timechange', {
  16812. time: new Date(this.customTime.valueOf())
  16813. });
  16814. event.stopPropagation();
  16815. event.preventDefault();
  16816. };
  16817. /**
  16818. * Stop moving operating.
  16819. * @param {event} event
  16820. * @private
  16821. */
  16822. CustomTime.prototype._onDragEnd = function (event) {
  16823. if (!this.eventParams.dragging) return;
  16824. // fire a timechanged event
  16825. this.body.emitter.emit('timechanged', {
  16826. time: new Date(this.customTime.valueOf())
  16827. });
  16828. event.stopPropagation();
  16829. event.preventDefault();
  16830. };
  16831. module.exports = CustomTime;
  16832. /***/ },
  16833. /* 42 */
  16834. /***/ function(module, exports, __webpack_require__) {
  16835. var Emitter = __webpack_require__(11);
  16836. var Hammer = __webpack_require__(19);
  16837. var util = __webpack_require__(1);
  16838. var DataSet = __webpack_require__(7);
  16839. var DataView = __webpack_require__(9);
  16840. var Range = __webpack_require__(21);
  16841. var Core = __webpack_require__(25);
  16842. var TimeAxis = __webpack_require__(37);
  16843. var CurrentTime = __webpack_require__(39);
  16844. var CustomTime = __webpack_require__(41);
  16845. var LineGraph = __webpack_require__(43);
  16846. /**
  16847. * Create a timeline visualization
  16848. * @param {HTMLElement} container
  16849. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  16850. * @param {Object} [options] See Graph2d.setOptions for the available options.
  16851. * @constructor
  16852. * @extends Core
  16853. */
  16854. function Graph2d (container, items, groups, options) {
  16855. // if the third element is options, the forth is groups (optionally);
  16856. if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) {
  16857. var forthArgument = options;
  16858. options = groups;
  16859. groups = forthArgument;
  16860. }
  16861. var me = this;
  16862. this.defaultOptions = {
  16863. start: null,
  16864. end: null,
  16865. autoResize: true,
  16866. orientation: 'bottom',
  16867. width: null,
  16868. height: null,
  16869. maxHeight: null,
  16870. minHeight: null
  16871. };
  16872. this.options = util.deepExtend({}, this.defaultOptions);
  16873. // Create the DOM, props, and emitter
  16874. this._create(container);
  16875. // all components listed here will be repainted automatically
  16876. this.components = [];
  16877. this.body = {
  16878. dom: this.dom,
  16879. domProps: this.props,
  16880. emitter: {
  16881. on: this.on.bind(this),
  16882. off: this.off.bind(this),
  16883. emit: this.emit.bind(this)
  16884. },
  16885. hiddenDates: [],
  16886. util: {
  16887. snap: null, // will be specified after TimeAxis is created
  16888. toScreen: me._toScreen.bind(me),
  16889. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  16890. toTime: me._toTime.bind(me),
  16891. toGlobalTime : me._toGlobalTime.bind(me)
  16892. }
  16893. };
  16894. // range
  16895. this.range = new Range(this.body);
  16896. this.components.push(this.range);
  16897. this.body.range = this.range;
  16898. // time axis
  16899. this.timeAxis = new TimeAxis(this.body);
  16900. this.components.push(this.timeAxis);
  16901. this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  16902. // current time bar
  16903. this.currentTime = new CurrentTime(this.body);
  16904. this.components.push(this.currentTime);
  16905. // custom time bar
  16906. // Note: time bar will be attached in this.setOptions when selected
  16907. this.customTime = new CustomTime(this.body);
  16908. this.components.push(this.customTime);
  16909. // item set
  16910. this.linegraph = new LineGraph(this.body);
  16911. this.components.push(this.linegraph);
  16912. this.itemsData = null; // DataSet
  16913. this.groupsData = null; // DataSet
  16914. // apply options
  16915. if (options) {
  16916. this.setOptions(options);
  16917. }
  16918. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  16919. if (groups) {
  16920. this.setGroups(groups);
  16921. }
  16922. // create itemset
  16923. if (items) {
  16924. this.setItems(items);
  16925. }
  16926. else {
  16927. this.redraw();
  16928. }
  16929. }
  16930. // Extend the functionality from Core
  16931. Graph2d.prototype = new Core();
  16932. /**
  16933. * Set items
  16934. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  16935. */
  16936. Graph2d.prototype.setItems = function(items) {
  16937. var initialLoad = (this.itemsData == null);
  16938. // convert to type DataSet when needed
  16939. var newDataSet;
  16940. if (!items) {
  16941. newDataSet = null;
  16942. }
  16943. else if (items instanceof DataSet || items instanceof DataView) {
  16944. newDataSet = items;
  16945. }
  16946. else {
  16947. // turn an array into a dataset
  16948. newDataSet = new DataSet(items, {
  16949. type: {
  16950. start: 'Date',
  16951. end: 'Date'
  16952. }
  16953. });
  16954. }
  16955. // set items
  16956. this.itemsData = newDataSet;
  16957. this.linegraph && this.linegraph.setItems(newDataSet);
  16958. if (initialLoad) {
  16959. if (this.options.start != undefined || this.options.end != undefined) {
  16960. var start = this.options.start != undefined ? this.options.start : null;
  16961. var end = this.options.end != undefined ? this.options.end : null;
  16962. this.setWindow(start, end, {animate: false});
  16963. }
  16964. else {
  16965. this.fit({animate: false});
  16966. }
  16967. }
  16968. };
  16969. /**
  16970. * Set groups
  16971. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  16972. */
  16973. Graph2d.prototype.setGroups = function(groups) {
  16974. // convert to type DataSet when needed
  16975. var newDataSet;
  16976. if (!groups) {
  16977. newDataSet = null;
  16978. }
  16979. else if (groups instanceof DataSet || groups instanceof DataView) {
  16980. newDataSet = groups;
  16981. }
  16982. else {
  16983. // turn an array into a dataset
  16984. newDataSet = new DataSet(groups);
  16985. }
  16986. this.groupsData = newDataSet;
  16987. this.linegraph.setGroups(newDataSet);
  16988. };
  16989. /**
  16990. * 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).
  16991. * @param groupId
  16992. * @param width
  16993. * @param height
  16994. */
  16995. Graph2d.prototype.getLegend = function(groupId, width, height) {
  16996. if (width === undefined) {width = 15;}
  16997. if (height === undefined) {height = 15;}
  16998. if (this.linegraph.groups[groupId] !== undefined) {
  16999. return this.linegraph.groups[groupId].getLegend(width,height);
  17000. }
  17001. else {
  17002. return "cannot find group:" + groupId;
  17003. }
  17004. }
  17005. /**
  17006. * This checks if the visible option of the supplied group (by ID) is true or false.
  17007. * @param groupId
  17008. * @returns {*}
  17009. */
  17010. Graph2d.prototype.isGroupVisible = function(groupId) {
  17011. if (this.linegraph.groups[groupId] !== undefined) {
  17012. return (this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true));
  17013. }
  17014. else {
  17015. return false;
  17016. }
  17017. }
  17018. /**
  17019. * Get the data range of the item set.
  17020. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  17021. * When no minimum is found, min==null
  17022. * When no maximum is found, max==null
  17023. */
  17024. Graph2d.prototype.getItemRange = function() {
  17025. var min = null;
  17026. var max = null;
  17027. // calculate min from start filed
  17028. for (var groupId in this.linegraph.groups) {
  17029. if (this.linegraph.groups.hasOwnProperty(groupId)) {
  17030. if (this.linegraph.groups[groupId].visible == true) {
  17031. for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
  17032. var item = this.linegraph.groups[groupId].itemsData[i];
  17033. var value = util.convert(item.x, 'Date').valueOf();
  17034. min = min == null ? value : min > value ? value : min;
  17035. max = max == null ? value : max < value ? value : max;
  17036. }
  17037. }
  17038. }
  17039. }
  17040. return {
  17041. min: (min != null) ? new Date(min) : null,
  17042. max: (max != null) ? new Date(max) : null
  17043. };
  17044. };
  17045. module.exports = Graph2d;
  17046. /***/ },
  17047. /* 43 */
  17048. /***/ function(module, exports, __webpack_require__) {
  17049. var util = __webpack_require__(1);
  17050. var DOMutil = __webpack_require__(6);
  17051. var DataSet = __webpack_require__(7);
  17052. var DataView = __webpack_require__(9);
  17053. var Component = __webpack_require__(23);
  17054. var DataAxis = __webpack_require__(44);
  17055. var GraphGroup = __webpack_require__(46);
  17056. var Legend = __webpack_require__(50);
  17057. var BarGraphFunctions = __webpack_require__(49);
  17058. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  17059. /**
  17060. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  17061. *
  17062. * @param body
  17063. * @param options
  17064. * @constructor
  17065. */
  17066. function LineGraph(body, options) {
  17067. this.id = util.randomUUID();
  17068. this.body = body;
  17069. this.defaultOptions = {
  17070. yAxisOrientation: 'left',
  17071. defaultGroup: 'default',
  17072. sort: true,
  17073. sampling: true,
  17074. graphHeight: '400px',
  17075. shaded: {
  17076. enabled: false,
  17077. orientation: 'bottom' // top, bottom
  17078. },
  17079. style: 'line', // line, bar
  17080. barChart: {
  17081. width: 50,
  17082. handleOverlap: 'overlap',
  17083. align: 'center' // left, center, right
  17084. },
  17085. catmullRom: {
  17086. enabled: true,
  17087. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  17088. alpha: 0.5
  17089. },
  17090. drawPoints: {
  17091. enabled: true,
  17092. size: 6,
  17093. style: 'square' // square, circle
  17094. },
  17095. dataAxis: {
  17096. showMinorLabels: true,
  17097. showMajorLabels: true,
  17098. showMinorLines: true,
  17099. showMajorLines: true,
  17100. icons: false,
  17101. width: '40px',
  17102. visible: true,
  17103. alignZeros: true,
  17104. customRange: {
  17105. left: {min:undefined, max:undefined},
  17106. right: {min:undefined, max:undefined}
  17107. }
  17108. //, these options are not set by default, but this shows the format they will be in
  17109. //format: {
  17110. // left: {decimals: 2},
  17111. // right: {decimals: 2}
  17112. //},
  17113. //title: {
  17114. // left: {
  17115. // text: 'left',
  17116. // style: 'color:black;'
  17117. // },
  17118. // right: {
  17119. // text: 'right',
  17120. // style: 'color:black;'
  17121. // }
  17122. //}
  17123. },
  17124. legend: {
  17125. enabled: false,
  17126. icons: true,
  17127. left: {
  17128. visible: true,
  17129. position: 'top-left' // top/bottom - left,right
  17130. },
  17131. right: {
  17132. visible: true,
  17133. position: 'top-right' // top/bottom - left,right
  17134. }
  17135. },
  17136. groups: {
  17137. visibility: {}
  17138. }
  17139. };
  17140. // options is shared by this ItemSet and all its items
  17141. this.options = util.extend({}, this.defaultOptions);
  17142. this.dom = {};
  17143. this.props = {};
  17144. this.hammer = null;
  17145. this.groups = {};
  17146. this.abortedGraphUpdate = false;
  17147. this.autoSizeSVG = false;
  17148. var me = this;
  17149. this.itemsData = null; // DataSet
  17150. this.groupsData = null; // DataSet
  17151. // listeners for the DataSet of the items
  17152. this.itemListeners = {
  17153. 'add': function (event, params, senderId) {
  17154. me._onAdd(params.items);
  17155. },
  17156. 'update': function (event, params, senderId) {
  17157. me._onUpdate(params.items);
  17158. },
  17159. 'remove': function (event, params, senderId) {
  17160. me._onRemove(params.items);
  17161. }
  17162. };
  17163. // listeners for the DataSet of the groups
  17164. this.groupListeners = {
  17165. 'add': function (event, params, senderId) {
  17166. me._onAddGroups(params.items);
  17167. },
  17168. 'update': function (event, params, senderId) {
  17169. me._onUpdateGroups(params.items);
  17170. },
  17171. 'remove': function (event, params, senderId) {
  17172. me._onRemoveGroups(params.items);
  17173. }
  17174. };
  17175. this.items = {}; // object with an Item for every data item
  17176. this.selection = []; // list with the ids of all selected nodes
  17177. this.lastStart = this.body.range.start;
  17178. this.touchParams = {}; // stores properties while dragging
  17179. this.svgElements = {};
  17180. this.setOptions(options);
  17181. this.groupsUsingDefaultStyles = [0];
  17182. this.COUNTER = 0;
  17183. this.body.emitter.on('rangechanged', function() {
  17184. me.lastStart = me.body.range.start;
  17185. me.svg.style.left = util.option.asSize(-me.width);
  17186. me.redraw.call(me,true);
  17187. });
  17188. // create the HTML DOM
  17189. this._create();
  17190. this.framework = {svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups};
  17191. this.body.emitter.emit('change');
  17192. }
  17193. LineGraph.prototype = new Component();
  17194. /**
  17195. * Create the HTML DOM for the ItemSet
  17196. */
  17197. LineGraph.prototype._create = function(){
  17198. var frame = document.createElement('div');
  17199. frame.className = 'LineGraph';
  17200. this.dom.frame = frame;
  17201. // create svg element for graph drawing.
  17202. this.svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
  17203. this.svg.style.position = 'relative';
  17204. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  17205. this.svg.style.display = 'block';
  17206. frame.appendChild(this.svg);
  17207. // data axis
  17208. this.options.dataAxis.orientation = 'left';
  17209. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  17210. this.options.dataAxis.orientation = 'right';
  17211. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  17212. delete this.options.dataAxis.orientation;
  17213. // legends
  17214. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  17215. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  17216. this.show();
  17217. };
  17218. /**
  17219. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  17220. * @param {object} options
  17221. */
  17222. LineGraph.prototype.setOptions = function(options) {
  17223. if (options) {
  17224. var fields = ['sampling','defaultGroup','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups'];
  17225. if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) {
  17226. this.autoSizeSVG = true;
  17227. }
  17228. else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  17229. if (parseInt((options.graphHeight + '').replace("px",'')) < this.body.domProps.centerContainer.height) {
  17230. this.autoSizeSVG = true;
  17231. }
  17232. }
  17233. util.selectiveDeepExtend(fields, this.options, options);
  17234. util.mergeOptions(this.options, options,'catmullRom');
  17235. util.mergeOptions(this.options, options,'drawPoints');
  17236. util.mergeOptions(this.options, options,'shaded');
  17237. util.mergeOptions(this.options, options,'legend');
  17238. if (options.catmullRom) {
  17239. if (typeof options.catmullRom == 'object') {
  17240. if (options.catmullRom.parametrization) {
  17241. if (options.catmullRom.parametrization == 'uniform') {
  17242. this.options.catmullRom.alpha = 0;
  17243. }
  17244. else if (options.catmullRom.parametrization == 'chordal') {
  17245. this.options.catmullRom.alpha = 1.0;
  17246. }
  17247. else {
  17248. this.options.catmullRom.parametrization = 'centripetal';
  17249. this.options.catmullRom.alpha = 0.5;
  17250. }
  17251. }
  17252. }
  17253. }
  17254. if (this.yAxisLeft) {
  17255. if (options.dataAxis !== undefined) {
  17256. this.yAxisLeft.setOptions(this.options.dataAxis);
  17257. this.yAxisRight.setOptions(this.options.dataAxis);
  17258. }
  17259. }
  17260. if (this.legendLeft) {
  17261. if (options.legend !== undefined) {
  17262. this.legendLeft.setOptions(this.options.legend);
  17263. this.legendRight.setOptions(this.options.legend);
  17264. }
  17265. }
  17266. if (this.groups.hasOwnProperty(UNGROUPED)) {
  17267. this.groups[UNGROUPED].setOptions(options);
  17268. }
  17269. }
  17270. // this is used to redraw the graph if the visibility of the groups is changed.
  17271. if (this.dom.frame) {
  17272. this.redraw(true);
  17273. }
  17274. };
  17275. /**
  17276. * Hide the component from the DOM
  17277. */
  17278. LineGraph.prototype.hide = function() {
  17279. // remove the frame containing the items
  17280. if (this.dom.frame.parentNode) {
  17281. this.dom.frame.parentNode.removeChild(this.dom.frame);
  17282. }
  17283. };
  17284. /**
  17285. * Show the component in the DOM (when not already visible).
  17286. * @return {Boolean} changed
  17287. */
  17288. LineGraph.prototype.show = function() {
  17289. // show frame containing the items
  17290. if (!this.dom.frame.parentNode) {
  17291. this.body.dom.center.appendChild(this.dom.frame);
  17292. }
  17293. };
  17294. /**
  17295. * Set items
  17296. * @param {vis.DataSet | null} items
  17297. */
  17298. LineGraph.prototype.setItems = function(items) {
  17299. var me = this,
  17300. ids,
  17301. oldItemsData = this.itemsData;
  17302. // replace the dataset
  17303. if (!items) {
  17304. this.itemsData = null;
  17305. }
  17306. else if (items instanceof DataSet || items instanceof DataView) {
  17307. this.itemsData = items;
  17308. }
  17309. else {
  17310. throw new TypeError('Data must be an instance of DataSet or DataView');
  17311. }
  17312. if (oldItemsData) {
  17313. // unsubscribe from old dataset
  17314. util.forEach(this.itemListeners, function (callback, event) {
  17315. oldItemsData.off(event, callback);
  17316. });
  17317. // remove all drawn items
  17318. ids = oldItemsData.getIds();
  17319. this._onRemove(ids);
  17320. }
  17321. if (this.itemsData) {
  17322. // subscribe to new dataset
  17323. var id = this.id;
  17324. util.forEach(this.itemListeners, function (callback, event) {
  17325. me.itemsData.on(event, callback, id);
  17326. });
  17327. // add all new items
  17328. ids = this.itemsData.getIds();
  17329. this._onAdd(ids);
  17330. }
  17331. this._updateUngrouped();
  17332. //this._updateGraph();
  17333. this.redraw(true);
  17334. };
  17335. /**
  17336. * Set groups
  17337. * @param {vis.DataSet} groups
  17338. */
  17339. LineGraph.prototype.setGroups = function(groups) {
  17340. var me = this;
  17341. var ids;
  17342. // unsubscribe from current dataset
  17343. if (this.groupsData) {
  17344. util.forEach(this.groupListeners, function (callback, event) {
  17345. me.groupsData.unsubscribe(event, callback);
  17346. });
  17347. // remove all drawn groups
  17348. ids = this.groupsData.getIds();
  17349. this.groupsData = null;
  17350. this._onRemoveGroups(ids); // note: this will cause a redraw
  17351. }
  17352. // replace the dataset
  17353. if (!groups) {
  17354. this.groupsData = null;
  17355. }
  17356. else if (groups instanceof DataSet || groups instanceof DataView) {
  17357. this.groupsData = groups;
  17358. }
  17359. else {
  17360. throw new TypeError('Data must be an instance of DataSet or DataView');
  17361. }
  17362. if (this.groupsData) {
  17363. // subscribe to new dataset
  17364. var id = this.id;
  17365. util.forEach(this.groupListeners, function (callback, event) {
  17366. me.groupsData.on(event, callback, id);
  17367. });
  17368. // draw all ms
  17369. ids = this.groupsData.getIds();
  17370. this._onAddGroups(ids);
  17371. }
  17372. this._onUpdate();
  17373. };
  17374. /**
  17375. * Update the data
  17376. * @param [ids]
  17377. * @private
  17378. */
  17379. LineGraph.prototype._onUpdate = function(ids) {
  17380. this._updateUngrouped();
  17381. this._updateAllGroupData();
  17382. //this._updateGraph();
  17383. this.redraw(true);
  17384. };
  17385. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  17386. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  17387. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  17388. for (var i = 0; i < groupIds.length; i++) {
  17389. var group = this.groupsData.get(groupIds[i]);
  17390. this._updateGroup(group, groupIds[i]);
  17391. }
  17392. //this._updateGraph();
  17393. this.redraw(true);
  17394. };
  17395. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  17396. /**
  17397. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  17398. * @param {Array} groupIds
  17399. * @private
  17400. */
  17401. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  17402. for (var i = 0; i < groupIds.length; i++) {
  17403. if (this.groups.hasOwnProperty(groupIds[i])) {
  17404. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  17405. this.yAxisRight.removeGroup(groupIds[i]);
  17406. this.legendRight.removeGroup(groupIds[i]);
  17407. this.legendRight.redraw();
  17408. }
  17409. else {
  17410. this.yAxisLeft.removeGroup(groupIds[i]);
  17411. this.legendLeft.removeGroup(groupIds[i]);
  17412. this.legendLeft.redraw();
  17413. }
  17414. delete this.groups[groupIds[i]];
  17415. }
  17416. }
  17417. this._updateUngrouped();
  17418. //this._updateGraph();
  17419. this.redraw(true);
  17420. };
  17421. /**
  17422. * update a group object with the group dataset entree
  17423. *
  17424. * @param group
  17425. * @param groupId
  17426. * @private
  17427. */
  17428. LineGraph.prototype._updateGroup = function (group, groupId) {
  17429. if (!this.groups.hasOwnProperty(groupId)) {
  17430. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  17431. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  17432. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  17433. this.legendRight.addGroup(groupId, this.groups[groupId]);
  17434. }
  17435. else {
  17436. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  17437. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  17438. }
  17439. }
  17440. else {
  17441. this.groups[groupId].update(group);
  17442. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  17443. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  17444. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  17445. }
  17446. else {
  17447. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  17448. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  17449. }
  17450. }
  17451. this.legendLeft.redraw();
  17452. this.legendRight.redraw();
  17453. };
  17454. /**
  17455. * this updates all groups, it is used when there is an update the the itemset.
  17456. *
  17457. * @private
  17458. */
  17459. LineGraph.prototype._updateAllGroupData = function () {
  17460. if (this.itemsData != null) {
  17461. var groupsContent = {};
  17462. var groupId;
  17463. for (groupId in this.groups) {
  17464. if (this.groups.hasOwnProperty(groupId)) {
  17465. groupsContent[groupId] = [];
  17466. }
  17467. }
  17468. for (var itemId in this.itemsData._data) {
  17469. if (this.itemsData._data.hasOwnProperty(itemId)) {
  17470. var item = this.itemsData._data[itemId];
  17471. if (groupsContent[item.group] === undefined) {
  17472. 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.')
  17473. }
  17474. item.x = util.convert(item.x,'Date');
  17475. groupsContent[item.group].push(item);
  17476. }
  17477. }
  17478. for (groupId in this.groups) {
  17479. if (this.groups.hasOwnProperty(groupId)) {
  17480. this.groups[groupId].setItems(groupsContent[groupId]);
  17481. }
  17482. }
  17483. }
  17484. };
  17485. /**
  17486. * Create or delete the group holding all ungrouped items. This group is used when
  17487. * there are no groups specified. This anonymous group is called 'graph'.
  17488. * @protected
  17489. */
  17490. LineGraph.prototype._updateUngrouped = function() {
  17491. if (this.itemsData && this.itemsData != null) {
  17492. var ungroupedCounter = 0;
  17493. for (var itemId in this.itemsData._data) {
  17494. if (this.itemsData._data.hasOwnProperty(itemId)) {
  17495. var item = this.itemsData._data[itemId];
  17496. if (item != undefined) {
  17497. if (item.hasOwnProperty('group')) {
  17498. if (item.group === undefined) {
  17499. item.group = UNGROUPED;
  17500. }
  17501. }
  17502. else {
  17503. item.group = UNGROUPED;
  17504. }
  17505. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  17506. }
  17507. }
  17508. }
  17509. if (ungroupedCounter == 0) {
  17510. delete this.groups[UNGROUPED];
  17511. this.legendLeft.removeGroup(UNGROUPED);
  17512. this.legendRight.removeGroup(UNGROUPED);
  17513. this.yAxisLeft.removeGroup(UNGROUPED);
  17514. this.yAxisRight.removeGroup(UNGROUPED);
  17515. }
  17516. else {
  17517. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  17518. this._updateGroup(group, UNGROUPED);
  17519. }
  17520. }
  17521. else {
  17522. delete this.groups[UNGROUPED];
  17523. this.legendLeft.removeGroup(UNGROUPED);
  17524. this.legendRight.removeGroup(UNGROUPED);
  17525. this.yAxisLeft.removeGroup(UNGROUPED);
  17526. this.yAxisRight.removeGroup(UNGROUPED);
  17527. }
  17528. this.legendLeft.redraw();
  17529. this.legendRight.redraw();
  17530. };
  17531. /**
  17532. * Redraw the component, mandatory function
  17533. * @return {boolean} Returns true if the component is resized
  17534. */
  17535. LineGraph.prototype.redraw = function(forceGraphUpdate) {
  17536. var resized = false;
  17537. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  17538. if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) {
  17539. resized = true;
  17540. }
  17541. // check if this component is resized
  17542. resized = this._isResized() || resized;
  17543. // check whether zoomed (in that case we need to re-stack everything)
  17544. var visibleInterval = this.body.range.end - this.body.range.start;
  17545. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth); // we get this from the range changed event
  17546. this.lastVisibleInterval = visibleInterval;
  17547. this.lastWidth = this.width;
  17548. // calculate actual size and position
  17549. this.width = this.dom.frame.offsetWidth;
  17550. // the svg element is three times as big as the width, this allows for fully dragging left and right
  17551. // without reloading the graph. the controls for this are bound to events in the constructor
  17552. if (resized == true) {
  17553. this.svg.style.width = util.option.asSize(3*this.width);
  17554. this.svg.style.left = util.option.asSize(-this.width);
  17555. }
  17556. // zoomed is here to ensure that animations are shown correctly.
  17557. if (zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) {
  17558. resized = resized || this._updateGraph();
  17559. }
  17560. else {
  17561. // move the whole svg while dragging
  17562. if (this.lastStart != 0) {
  17563. var offset = this.body.range.start - this.lastStart;
  17564. var range = this.body.range.end - this.body.range.start;
  17565. if (this.width != 0) {
  17566. var rangePerPixelInv = this.width/range;
  17567. var xOffset = offset * rangePerPixelInv;
  17568. this.svg.style.left = (-this.width - xOffset) + 'px';
  17569. }
  17570. }
  17571. }
  17572. this.legendLeft.redraw();
  17573. this.legendRight.redraw();
  17574. return resized;
  17575. };
  17576. /**
  17577. * Update and redraw the graph.
  17578. *
  17579. */
  17580. LineGraph.prototype._updateGraph = function () {
  17581. // reset the svg elements
  17582. DOMutil.prepareElements(this.svgElements);
  17583. if (this.width != 0 && this.itemsData != null) {
  17584. var group, i;
  17585. var preprocessedGroupData = {};
  17586. var processedGroupData = {};
  17587. var groupRanges = {};
  17588. var changeCalled = false;
  17589. // update the height of the graph on each redraw of the graph.
  17590. if (this.autoSizeSVG == true) {
  17591. if (this.options.graphHeight != this.body.domProps.centerContainer.height + 'px') {
  17592. this.options.graphHeight = this.body.domProps.centerContainer.height + 'px';
  17593. this.svg.style.height = this.body.domProps.centerContainer.height + 'px';
  17594. }
  17595. this.autoSizeSVG = false;
  17596. }
  17597. // getting group Ids
  17598. var groupIds = [];
  17599. for (var groupId in this.groups) {
  17600. if (this.groups.hasOwnProperty(groupId)) {
  17601. group = this.groups[groupId];
  17602. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  17603. groupIds.push(groupId);
  17604. }
  17605. }
  17606. }
  17607. if (groupIds.length > 0) {
  17608. // this is the range of the SVG canvas
  17609. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  17610. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  17611. var groupsData = {};
  17612. // fill groups data, this only loads the data we require based on the timewindow
  17613. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  17614. // apply sampling, if disabled, it will pass through this function.
  17615. this._applySampling(groupIds, groupsData);
  17616. // we transform the X coordinates to detect collisions
  17617. for (i = 0; i < groupIds.length; i++) {
  17618. preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]);
  17619. }
  17620. // now all needed data has been collected we start the processing.
  17621. this._getYRanges(groupIds, preprocessedGroupData, groupRanges);
  17622. // update the Y axis first, we use this data to draw at the correct Y points
  17623. // changeCalled is required to clean the SVG on a change emit.
  17624. changeCalled = this._updateYAxis(groupIds, groupRanges);
  17625. var MAX_CYCLES = 5;
  17626. if (changeCalled == true && this.COUNTER < MAX_CYCLES) {
  17627. DOMutil.cleanupElements(this.svgElements);
  17628. this.abortedGraphUpdate = true;
  17629. this.COUNTER++;
  17630. this.body.emitter.emit('change');
  17631. return true;
  17632. }
  17633. else {
  17634. if (this.COUNTER > MAX_CYCLES) {
  17635. console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle.")
  17636. }
  17637. this.COUNTER = 0;
  17638. this.abortedGraphUpdate = false;
  17639. // With the yAxis scaled correctly, use this to get the Y values of the points.
  17640. for (i = 0; i < groupIds.length; i++) {
  17641. group = this.groups[groupIds[i]];
  17642. processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group);
  17643. }
  17644. // draw the groups
  17645. for (i = 0; i < groupIds.length; i++) {
  17646. group = this.groups[groupIds[i]];
  17647. if (group.options.style != 'bar') { // bar needs to be drawn enmasse
  17648. group.draw(processedGroupData[groupIds[i]], group, this.framework);
  17649. }
  17650. }
  17651. BarGraphFunctions.draw(groupIds, processedGroupData, this.framework);
  17652. }
  17653. }
  17654. }
  17655. // cleanup unused svg elements
  17656. DOMutil.cleanupElements(this.svgElements);
  17657. return false;
  17658. };
  17659. /**
  17660. * first select and preprocess the data from the datasets.
  17661. * the groups have their preselection of data, we now loop over this data to see
  17662. * what data we need to draw. Sorted data is much faster.
  17663. * more optimization is possible by doing the sampling before and using the binary search
  17664. * to find the end date to determine the increment.
  17665. *
  17666. * @param {array} groupIds
  17667. * @param {object} groupsData
  17668. * @param {date} minDate
  17669. * @param {date} maxDate
  17670. * @private
  17671. */
  17672. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  17673. var group, i, j, item;
  17674. if (groupIds.length > 0) {
  17675. for (i = 0; i < groupIds.length; i++) {
  17676. group = this.groups[groupIds[i]];
  17677. groupsData[groupIds[i]] = [];
  17678. var dataContainer = groupsData[groupIds[i]];
  17679. // optimization for sorted data
  17680. if (group.options.sort == true) {
  17681. var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before'));
  17682. for (j = guess; j < group.itemsData.length; j++) {
  17683. item = group.itemsData[j];
  17684. if (item !== undefined) {
  17685. if (item.x > maxDate) {
  17686. dataContainer.push(item);
  17687. break;
  17688. }
  17689. else {
  17690. dataContainer.push(item);
  17691. }
  17692. }
  17693. }
  17694. }
  17695. else {
  17696. for (j = 0; j < group.itemsData.length; j++) {
  17697. item = group.itemsData[j];
  17698. if (item !== undefined) {
  17699. if (item.x > minDate && item.x < maxDate) {
  17700. dataContainer.push(item);
  17701. }
  17702. }
  17703. }
  17704. }
  17705. }
  17706. }
  17707. };
  17708. /**
  17709. *
  17710. * @param groupIds
  17711. * @param groupsData
  17712. * @private
  17713. */
  17714. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  17715. var group;
  17716. if (groupIds.length > 0) {
  17717. for (var i = 0; i < groupIds.length; i++) {
  17718. group = this.groups[groupIds[i]];
  17719. if (group.options.sampling == true) {
  17720. var dataContainer = groupsData[groupIds[i]];
  17721. if (dataContainer.length > 0) {
  17722. var increment = 1;
  17723. var amountOfPoints = dataContainer.length;
  17724. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  17725. // of width changing of the yAxis.
  17726. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  17727. var pointsPerPixel = amountOfPoints / xDistance;
  17728. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  17729. var sampledData = [];
  17730. for (var j = 0; j < amountOfPoints; j += increment) {
  17731. sampledData.push(dataContainer[j]);
  17732. }
  17733. groupsData[groupIds[i]] = sampledData;
  17734. }
  17735. }
  17736. }
  17737. }
  17738. };
  17739. /**
  17740. *
  17741. *
  17742. * @param {array} groupIds
  17743. * @param {object} groupsData
  17744. * @param {object} groupRanges | this is being filled here
  17745. * @private
  17746. */
  17747. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  17748. var groupData, group, i;
  17749. var barCombinedDataLeft = [];
  17750. var barCombinedDataRight = [];
  17751. var options;
  17752. if (groupIds.length > 0) {
  17753. for (i = 0; i < groupIds.length; i++) {
  17754. groupData = groupsData[groupIds[i]];
  17755. options = this.groups[groupIds[i]].options;
  17756. if (groupData.length > 0) {
  17757. group = this.groups[groupIds[i]];
  17758. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  17759. if (options.barChart.handleOverlap == 'stack' && options.style == 'bar') {
  17760. if (options.yAxisOrientation == 'left') {barCombinedDataLeft = barCombinedDataLeft.concat(group.getYRange(groupData)) ;}
  17761. else {barCombinedDataRight = barCombinedDataRight.concat(group.getYRange(groupData));}
  17762. }
  17763. else {
  17764. groupRanges[groupIds[i]] = group.getYRange(groupData,groupIds[i]);
  17765. }
  17766. }
  17767. }
  17768. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  17769. BarGraphFunctions.getStackedBarYRange(barCombinedDataLeft , groupRanges, groupIds, '__barchartLeft' , 'left' );
  17770. BarGraphFunctions.getStackedBarYRange(barCombinedDataRight, groupRanges, groupIds, '__barchartRight', 'right');
  17771. }
  17772. };
  17773. /**
  17774. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  17775. * @param {Array} groupIds
  17776. * @param {Object} groupRanges
  17777. * @private
  17778. */
  17779. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  17780. var changeCalled = false;
  17781. var yAxisLeftUsed = false;
  17782. var yAxisRightUsed = false;
  17783. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  17784. // if groups are present
  17785. if (groupIds.length > 0) {
  17786. // 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.
  17787. for (var i = 0; i < groupIds.length; i++) {
  17788. var group = this.groups[groupIds[i]];
  17789. if (group && group.options.yAxisOrientation == 'left') {
  17790. yAxisLeftUsed = true;
  17791. minLeft = 0;
  17792. maxLeft = 0;
  17793. }
  17794. else {
  17795. yAxisRightUsed = true;
  17796. minRight = 0;
  17797. maxRight = 0;
  17798. }
  17799. }
  17800. // if there are items:
  17801. for (var i = 0; i < groupIds.length; i++) {
  17802. if (groupRanges.hasOwnProperty(groupIds[i])) {
  17803. if (groupRanges[groupIds[i]].ignore !== true) {
  17804. minVal = groupRanges[groupIds[i]].min;
  17805. maxVal = groupRanges[groupIds[i]].max;
  17806. if (groupRanges[groupIds[i]].yAxisOrientation == 'left') {
  17807. yAxisLeftUsed = true;
  17808. minLeft = minLeft > minVal ? minVal : minLeft;
  17809. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  17810. }
  17811. else {
  17812. yAxisRightUsed = true;
  17813. minRight = minRight > minVal ? minVal : minRight;
  17814. maxRight = maxRight < maxVal ? maxVal : maxRight;
  17815. }
  17816. }
  17817. }
  17818. }
  17819. if (yAxisLeftUsed == true) {
  17820. this.yAxisLeft.setRange(minLeft, maxLeft);
  17821. }
  17822. if (yAxisRightUsed == true) {
  17823. this.yAxisRight.setRange(minRight, maxRight);
  17824. }
  17825. }
  17826. changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled;
  17827. changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled;
  17828. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  17829. this.yAxisLeft.drawIcons = true;
  17830. this.yAxisRight.drawIcons = true;
  17831. }
  17832. else {
  17833. this.yAxisLeft.drawIcons = false;
  17834. this.yAxisRight.drawIcons = false;
  17835. }
  17836. this.yAxisRight.master = !yAxisLeftUsed;
  17837. if (this.yAxisRight.master == false) {
  17838. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  17839. else {this.yAxisLeft.lineOffset = 0;}
  17840. changeCalled = this.yAxisLeft.redraw() || changeCalled;
  17841. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  17842. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  17843. changeCalled = this.yAxisRight.redraw() || changeCalled;
  17844. }
  17845. else {
  17846. changeCalled = this.yAxisRight.redraw() || changeCalled;
  17847. }
  17848. // clean the accumulated lists
  17849. if (groupIds.indexOf('__barchartLeft') != -1) {
  17850. groupIds.splice(groupIds.indexOf('__barchartLeft'),1);
  17851. }
  17852. if (groupIds.indexOf('__barchartRight') != -1) {
  17853. groupIds.splice(groupIds.indexOf('__barchartRight'),1);
  17854. }
  17855. return changeCalled;
  17856. };
  17857. /**
  17858. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  17859. *
  17860. * @param {boolean} axisUsed
  17861. * @returns {boolean}
  17862. * @private
  17863. * @param axis
  17864. */
  17865. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  17866. var changed = false;
  17867. if (axisUsed == false) {
  17868. if (axis.dom.frame.parentNode && axis.hidden == false) {
  17869. axis.hide()
  17870. changed = true;
  17871. }
  17872. }
  17873. else {
  17874. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  17875. axis.show();
  17876. changed = true;
  17877. }
  17878. }
  17879. return changed;
  17880. };
  17881. /**
  17882. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  17883. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  17884. * the yAxis.
  17885. *
  17886. * @param datapoints
  17887. * @returns {Array}
  17888. * @private
  17889. */
  17890. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  17891. var extractedData = [];
  17892. var xValue, yValue;
  17893. var toScreen = this.body.util.toScreen;
  17894. for (var i = 0; i < datapoints.length; i++) {
  17895. xValue = toScreen(datapoints[i].x) + this.width;
  17896. yValue = datapoints[i].y;
  17897. extractedData.push({x: xValue, y: yValue});
  17898. }
  17899. return extractedData;
  17900. };
  17901. /**
  17902. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  17903. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  17904. * the yAxis.
  17905. *
  17906. * @param datapoints
  17907. * @param group
  17908. * @returns {Array}
  17909. * @private
  17910. */
  17911. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  17912. var extractedData = [];
  17913. var xValue, yValue;
  17914. var toScreen = this.body.util.toScreen;
  17915. var axis = this.yAxisLeft;
  17916. var svgHeight = Number(this.svg.style.height.replace('px',''));
  17917. if (group.options.yAxisOrientation == 'right') {
  17918. axis = this.yAxisRight;
  17919. }
  17920. for (var i = 0; i < datapoints.length; i++) {
  17921. xValue = toScreen(datapoints[i].x) + this.width;
  17922. yValue = Math.round(axis.convertValue(datapoints[i].y));
  17923. extractedData.push({x: xValue, y: yValue});
  17924. }
  17925. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  17926. return extractedData;
  17927. };
  17928. module.exports = LineGraph;
  17929. /***/ },
  17930. /* 44 */
  17931. /***/ function(module, exports, __webpack_require__) {
  17932. var util = __webpack_require__(1);
  17933. var DOMutil = __webpack_require__(6);
  17934. var Component = __webpack_require__(23);
  17935. var DataStep = __webpack_require__(45);
  17936. /**
  17937. * A horizontal time axis
  17938. * @param {Object} [options] See DataAxis.setOptions for the available
  17939. * options.
  17940. * @constructor DataAxis
  17941. * @extends Component
  17942. * @param body
  17943. */
  17944. function DataAxis (body, options, svg, linegraphOptions) {
  17945. this.id = util.randomUUID();
  17946. this.body = body;
  17947. this.defaultOptions = {
  17948. orientation: 'left', // supported: 'left', 'right'
  17949. showMinorLabels: true,
  17950. showMajorLabels: true,
  17951. showMinorLines: true,
  17952. showMajorLines: true,
  17953. icons: true,
  17954. majorLinesOffset: 7,
  17955. minorLinesOffset: 4,
  17956. labelOffsetX: 10,
  17957. labelOffsetY: 2,
  17958. iconWidth: 20,
  17959. width: '40px',
  17960. visible: true,
  17961. alignZeros: true,
  17962. customRange: {
  17963. left: {min:undefined, max:undefined},
  17964. right: {min:undefined, max:undefined}
  17965. },
  17966. title: {
  17967. left: {text:undefined},
  17968. right: {text:undefined}
  17969. },
  17970. format: {
  17971. left: {decimals: undefined},
  17972. right: {decimals: undefined}
  17973. }
  17974. };
  17975. this.linegraphOptions = linegraphOptions;
  17976. this.linegraphSVG = svg;
  17977. this.props = {};
  17978. this.DOMelements = { // dynamic elements
  17979. lines: {},
  17980. labels: {},
  17981. title: {}
  17982. };
  17983. this.dom = {};
  17984. this.range = {start:0, end:0};
  17985. this.options = util.extend({}, this.defaultOptions);
  17986. this.conversionFactor = 1;
  17987. this.setOptions(options);
  17988. this.width = Number(('' + this.options.width).replace("px",""));
  17989. this.minWidth = this.width;
  17990. this.height = this.linegraphSVG.offsetHeight;
  17991. this.hidden = false;
  17992. this.stepPixels = 25;
  17993. this.stepPixelsForced = 25;
  17994. this.zeroCrossing = -1;
  17995. this.lineOffset = 0;
  17996. this.master = true;
  17997. this.svgElements = {};
  17998. this.iconsRemoved = false;
  17999. this.groups = {};
  18000. this.amountOfGroups = 0;
  18001. // create the HTML DOM
  18002. this._create();
  18003. var me = this;
  18004. this.body.emitter.on("verticalDrag", function() {
  18005. me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px';
  18006. });
  18007. }
  18008. DataAxis.prototype = new Component();
  18009. DataAxis.prototype.addGroup = function(label, graphOptions) {
  18010. if (!this.groups.hasOwnProperty(label)) {
  18011. this.groups[label] = graphOptions;
  18012. }
  18013. this.amountOfGroups += 1;
  18014. };
  18015. DataAxis.prototype.updateGroup = function(label, graphOptions) {
  18016. this.groups[label] = graphOptions;
  18017. };
  18018. DataAxis.prototype.removeGroup = function(label) {
  18019. if (this.groups.hasOwnProperty(label)) {
  18020. delete this.groups[label];
  18021. this.amountOfGroups -= 1;
  18022. }
  18023. };
  18024. DataAxis.prototype.setOptions = function (options) {
  18025. if (options) {
  18026. var redraw = false;
  18027. if (this.options.orientation != options.orientation && options.orientation !== undefined) {
  18028. redraw = true;
  18029. }
  18030. var fields = [
  18031. 'orientation',
  18032. 'showMinorLabels',
  18033. 'showMajorLabels',
  18034. 'showMajorLines',
  18035. 'showMinorLines',
  18036. 'icons',
  18037. 'majorLinesOffset',
  18038. 'minorLinesOffset',
  18039. 'labelOffsetX',
  18040. 'labelOffsetY',
  18041. 'iconWidth',
  18042. 'width',
  18043. 'visible',
  18044. 'customRange',
  18045. 'title',
  18046. 'format',
  18047. 'alignZeros'
  18048. ];
  18049. util.selectiveExtend(fields, this.options, options);
  18050. this.minWidth = Number(('' + this.options.width).replace("px",""));
  18051. if (redraw == true && this.dom.frame) {
  18052. this.hide();
  18053. this.show();
  18054. }
  18055. }
  18056. };
  18057. /**
  18058. * Create the HTML DOM for the DataAxis
  18059. */
  18060. DataAxis.prototype._create = function() {
  18061. this.dom.frame = document.createElement('div');
  18062. this.dom.frame.style.width = this.options.width;
  18063. this.dom.frame.style.height = this.height;
  18064. this.dom.lineContainer = document.createElement('div');
  18065. this.dom.lineContainer.style.width = '100%';
  18066. this.dom.lineContainer.style.height = this.height;
  18067. this.dom.lineContainer.style.position = 'relative';
  18068. // create svg element for graph drawing.
  18069. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  18070. this.svg.style.position = "absolute";
  18071. this.svg.style.top = '0px';
  18072. this.svg.style.height = '100%';
  18073. this.svg.style.width = '100%';
  18074. this.svg.style.display = "block";
  18075. this.dom.frame.appendChild(this.svg);
  18076. };
  18077. DataAxis.prototype._redrawGroupIcons = function () {
  18078. DOMutil.prepareElements(this.svgElements);
  18079. var x;
  18080. var iconWidth = this.options.iconWidth;
  18081. var iconHeight = 15;
  18082. var iconOffset = 4;
  18083. var y = iconOffset + 0.5 * iconHeight;
  18084. if (this.options.orientation == 'left') {
  18085. x = iconOffset;
  18086. }
  18087. else {
  18088. x = this.width - iconWidth - iconOffset;
  18089. }
  18090. for (var groupId in this.groups) {
  18091. if (this.groups.hasOwnProperty(groupId)) {
  18092. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  18093. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  18094. y += iconHeight + iconOffset;
  18095. }
  18096. }
  18097. }
  18098. DOMutil.cleanupElements(this.svgElements);
  18099. this.iconsRemoved = false;
  18100. };
  18101. DataAxis.prototype._cleanupIcons = function() {
  18102. if (this.iconsRemoved == false) {
  18103. DOMutil.prepareElements(this.svgElements);
  18104. DOMutil.cleanupElements(this.svgElements);
  18105. this.iconsRemoved = true;
  18106. }
  18107. }
  18108. /**
  18109. * Create the HTML DOM for the DataAxis
  18110. */
  18111. DataAxis.prototype.show = function() {
  18112. this.hidden = false;
  18113. if (!this.dom.frame.parentNode) {
  18114. if (this.options.orientation == 'left') {
  18115. this.body.dom.left.appendChild(this.dom.frame);
  18116. }
  18117. else {
  18118. this.body.dom.right.appendChild(this.dom.frame);
  18119. }
  18120. }
  18121. if (!this.dom.lineContainer.parentNode) {
  18122. this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
  18123. }
  18124. };
  18125. /**
  18126. * Create the HTML DOM for the DataAxis
  18127. */
  18128. DataAxis.prototype.hide = function() {
  18129. this.hidden = true;
  18130. if (this.dom.frame.parentNode) {
  18131. this.dom.frame.parentNode.removeChild(this.dom.frame);
  18132. }
  18133. if (this.dom.lineContainer.parentNode) {
  18134. this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
  18135. }
  18136. };
  18137. /**
  18138. * Set a range (start and end)
  18139. * @param end
  18140. * @param start
  18141. * @param end
  18142. */
  18143. DataAxis.prototype.setRange = function (start, end) {
  18144. if (this.master == false && this.options.alignZeros == true && this.zeroCrossing != -1) {
  18145. if (start > 0) {
  18146. start = 0;
  18147. }
  18148. }
  18149. this.range.start = start;
  18150. this.range.end = end;
  18151. };
  18152. /**
  18153. * Repaint the component
  18154. * @return {boolean} Returns true if the component is resized
  18155. */
  18156. DataAxis.prototype.redraw = function () {
  18157. var changeCalled = false;
  18158. var activeGroups = 0;
  18159. // Make sure the line container adheres to the vertical scrolling.
  18160. this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px';
  18161. for (var groupId in this.groups) {
  18162. if (this.groups.hasOwnProperty(groupId)) {
  18163. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  18164. activeGroups++;
  18165. }
  18166. }
  18167. }
  18168. if (this.amountOfGroups == 0 || activeGroups == 0) {
  18169. this.hide();
  18170. }
  18171. else {
  18172. this.show();
  18173. this.height = Number(this.linegraphSVG.style.height.replace("px",""));
  18174. // svg offsetheight did not work in firefox and explorer...
  18175. this.dom.lineContainer.style.height = this.height + 'px';
  18176. this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0;
  18177. var props = this.props;
  18178. var frame = this.dom.frame;
  18179. // update classname
  18180. frame.className = 'dataaxis';
  18181. // calculate character width and height
  18182. this._calculateCharSize();
  18183. var orientation = this.options.orientation;
  18184. var showMinorLabels = this.options.showMinorLabels;
  18185. var showMajorLabels = this.options.showMajorLabels;
  18186. // determine the width and height of the elements for the axis
  18187. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  18188. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  18189. props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
  18190. props.minorLineHeight = 1;
  18191. props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
  18192. props.majorLineHeight = 1;
  18193. // take frame offline while updating (is almost twice as fast)
  18194. if (orientation == 'left') {
  18195. frame.style.top = '0';
  18196. frame.style.left = '0';
  18197. frame.style.bottom = '';
  18198. frame.style.width = this.width + 'px';
  18199. frame.style.height = this.height + "px";
  18200. }
  18201. else { // right
  18202. frame.style.top = '';
  18203. frame.style.bottom = '0';
  18204. frame.style.left = '0';
  18205. frame.style.width = this.width + 'px';
  18206. frame.style.height = this.height + "px";
  18207. }
  18208. changeCalled = this._redrawLabels();
  18209. if (this.options.icons == true) {
  18210. this._redrawGroupIcons();
  18211. }
  18212. else {
  18213. this._cleanupIcons();
  18214. }
  18215. this._redrawTitle(orientation);
  18216. }
  18217. return changeCalled;
  18218. };
  18219. /**
  18220. * Repaint major and minor text labels and vertical grid lines
  18221. * @private
  18222. */
  18223. DataAxis.prototype._redrawLabels = function () {
  18224. DOMutil.prepareElements(this.DOMelements.lines);
  18225. DOMutil.prepareElements(this.DOMelements.labels);
  18226. var orientation = this.options['orientation'];
  18227. // calculate range and step (step such that we have space for 7 characters per label)
  18228. var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced;
  18229. var step = new DataStep(
  18230. this.range.start,
  18231. this.range.end,
  18232. minimumStep,
  18233. this.dom.frame.offsetHeight,
  18234. this.options.customRange[this.options.orientation],
  18235. this.master == false && this.options.alignZeros // doess the step have to align zeros? only if not master and the options is on
  18236. );
  18237. this.step = step;
  18238. // get the distance in pixels for a step
  18239. // dead space is space that is "left over" after a step
  18240. var stepPixels = (this.dom.frame.offsetHeight - (step.deadSpace * (this.dom.frame.offsetHeight / step.marginRange))) / (((step.marginRange - step.deadSpace) / step.step));
  18241. this.stepPixels = stepPixels;
  18242. var amountOfSteps = this.height / stepPixels;
  18243. var stepDifference = 0;
  18244. // the slave axis needs to use the same horizontal lines as the master axis.
  18245. if (this.master == false) {
  18246. stepPixels = this.stepPixelsForced;
  18247. stepDifference = Math.round((this.dom.frame.offsetHeight / stepPixels) - amountOfSteps);
  18248. for (var i = 0; i < 0.5 * stepDifference; i++) {
  18249. step.previous();
  18250. }
  18251. amountOfSteps = this.height / stepPixels;
  18252. if (this.zeroCrossing != -1 && this.options.alignZeros == true) {
  18253. var zeroStepDifference = (step.marginEnd / step.step) - this.zeroCrossing;
  18254. if (zeroStepDifference > 0) {
  18255. for (var i = 0; i < zeroStepDifference; i++) {step.next();}
  18256. }
  18257. else if (zeroStepDifference < 0) {
  18258. for (var i = 0; i < -zeroStepDifference; i++) {step.previous();}
  18259. }
  18260. }
  18261. }
  18262. else {
  18263. amountOfSteps += 0.25;
  18264. }
  18265. this.valueAtZero = step.marginEnd;
  18266. var marginStartPos = 0;
  18267. // do not draw the first label
  18268. var max = 1;
  18269. // Get the number of decimal places
  18270. var decimals;
  18271. if(this.options.format[orientation] !== undefined) {
  18272. decimals = this.options.format[orientation].decimals;
  18273. }
  18274. this.maxLabelSize = 0;
  18275. var y = 0;
  18276. while (max < Math.round(amountOfSteps)) {
  18277. step.next();
  18278. y = Math.round(max * stepPixels);
  18279. marginStartPos = max * stepPixels;
  18280. var isMajor = step.isMajor();
  18281. if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) {
  18282. this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis minor', this.props.minorCharHeight);
  18283. }
  18284. if (isMajor && this.options['showMajorLabels'] && this.master == true ||
  18285. this.options['showMinorLabels'] == false && this.master == false && isMajor == true) {
  18286. if (y >= 0) {
  18287. this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis major', this.props.majorCharHeight);
  18288. }
  18289. if (this.options.showMajorLines == true) {
  18290. this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth);
  18291. }
  18292. }
  18293. else if (this.options.showMinorLines == true) {
  18294. this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth);
  18295. }
  18296. if (this.master == true && step.current == 0) {
  18297. this.zeroCrossing = max;
  18298. }
  18299. max++;
  18300. }
  18301. if (this.master == false) {
  18302. this.conversionFactor = y / (this.valueAtZero - step.current);
  18303. }
  18304. else {
  18305. this.conversionFactor = this.dom.frame.offsetHeight / step.marginRange;
  18306. }
  18307. // Note that title is rotated, so we're using the height, not width!
  18308. var titleWidth = 0;
  18309. if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
  18310. titleWidth = this.props.titleCharHeight;
  18311. }
  18312. var offset = this.options.icons == true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15;
  18313. // this will resize the yAxis to accommodate the labels.
  18314. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) {
  18315. this.width = this.maxLabelSize + offset;
  18316. this.options.width = this.width + "px";
  18317. DOMutil.cleanupElements(this.DOMelements.lines);
  18318. DOMutil.cleanupElements(this.DOMelements.labels);
  18319. this.redraw();
  18320. return true;
  18321. }
  18322. // this will resize the yAxis if it is too big for the labels.
  18323. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) {
  18324. this.width = Math.max(this.minWidth,this.maxLabelSize + offset);
  18325. this.options.width = this.width + "px";
  18326. DOMutil.cleanupElements(this.DOMelements.lines);
  18327. DOMutil.cleanupElements(this.DOMelements.labels);
  18328. this.redraw();
  18329. return true;
  18330. }
  18331. else {
  18332. DOMutil.cleanupElements(this.DOMelements.lines);
  18333. DOMutil.cleanupElements(this.DOMelements.labels);
  18334. return false;
  18335. }
  18336. };
  18337. DataAxis.prototype.convertValue = function (value) {
  18338. var invertedValue = this.valueAtZero - value;
  18339. var convertedValue = invertedValue * this.conversionFactor;
  18340. return convertedValue;
  18341. };
  18342. /**
  18343. * Create a label for the axis at position x
  18344. * @private
  18345. * @param y
  18346. * @param text
  18347. * @param orientation
  18348. * @param className
  18349. * @param characterHeight
  18350. */
  18351. DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
  18352. // reuse redundant label
  18353. var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
  18354. label.className = className;
  18355. label.innerHTML = text;
  18356. if (orientation == 'left') {
  18357. label.style.left = '-' + this.options.labelOffsetX + 'px';
  18358. label.style.textAlign = "right";
  18359. }
  18360. else {
  18361. label.style.right = '-' + this.options.labelOffsetX + 'px';
  18362. label.style.textAlign = "left";
  18363. }
  18364. label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
  18365. text += '';
  18366. var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth);
  18367. if (this.maxLabelSize < text.length * largestWidth) {
  18368. this.maxLabelSize = text.length * largestWidth;
  18369. }
  18370. };
  18371. /**
  18372. * Create a minor line for the axis at position y
  18373. * @param y
  18374. * @param orientation
  18375. * @param className
  18376. * @param offset
  18377. * @param width
  18378. */
  18379. DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
  18380. if (this.master == true) {
  18381. var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift();
  18382. line.className = className;
  18383. line.innerHTML = '';
  18384. if (orientation == 'left') {
  18385. line.style.left = (this.width - offset) + 'px';
  18386. }
  18387. else {
  18388. line.style.right = (this.width - offset) + 'px';
  18389. }
  18390. line.style.width = width + 'px';
  18391. line.style.top = y + 'px';
  18392. }
  18393. };
  18394. /**
  18395. * Create a title for the axis
  18396. * @private
  18397. * @param orientation
  18398. */
  18399. DataAxis.prototype._redrawTitle = function (orientation) {
  18400. DOMutil.prepareElements(this.DOMelements.title);
  18401. // Check if the title is defined for this axes
  18402. if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
  18403. var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame);
  18404. title.className = 'yAxis title ' + orientation;
  18405. title.innerHTML = this.options.title[orientation].text;
  18406. // Add style - if provided
  18407. if (this.options.title[orientation].style !== undefined) {
  18408. util.addCssText(title, this.options.title[orientation].style);
  18409. }
  18410. if (orientation == 'left') {
  18411. title.style.left = this.props.titleCharHeight + 'px';
  18412. }
  18413. else {
  18414. title.style.right = this.props.titleCharHeight + 'px';
  18415. }
  18416. title.style.width = this.height + 'px';
  18417. }
  18418. // we need to clean up in case we did not use all elements.
  18419. DOMutil.cleanupElements(this.DOMelements.title);
  18420. };
  18421. /**
  18422. * Determine the size of text on the axis (both major and minor axis).
  18423. * The size is calculated only once and then cached in this.props.
  18424. * @private
  18425. */
  18426. DataAxis.prototype._calculateCharSize = function () {
  18427. // determine the char width and height on the minor axis
  18428. if (!('minorCharHeight' in this.props)) {
  18429. var textMinor = document.createTextNode('0');
  18430. var measureCharMinor = document.createElement('div');
  18431. measureCharMinor.className = 'yAxis minor measure';
  18432. measureCharMinor.appendChild(textMinor);
  18433. this.dom.frame.appendChild(measureCharMinor);
  18434. this.props.minorCharHeight = measureCharMinor.clientHeight;
  18435. this.props.minorCharWidth = measureCharMinor.clientWidth;
  18436. this.dom.frame.removeChild(measureCharMinor);
  18437. }
  18438. if (!('majorCharHeight' in this.props)) {
  18439. var textMajor = document.createTextNode('0');
  18440. var measureCharMajor = document.createElement('div');
  18441. measureCharMajor.className = 'yAxis major measure';
  18442. measureCharMajor.appendChild(textMajor);
  18443. this.dom.frame.appendChild(measureCharMajor);
  18444. this.props.majorCharHeight = measureCharMajor.clientHeight;
  18445. this.props.majorCharWidth = measureCharMajor.clientWidth;
  18446. this.dom.frame.removeChild(measureCharMajor);
  18447. }
  18448. if (!('titleCharHeight' in this.props)) {
  18449. var textTitle = document.createTextNode('0');
  18450. var measureCharTitle = document.createElement('div');
  18451. measureCharTitle.className = 'yAxis title measure';
  18452. measureCharTitle.appendChild(textTitle);
  18453. this.dom.frame.appendChild(measureCharTitle);
  18454. this.props.titleCharHeight = measureCharTitle.clientHeight;
  18455. this.props.titleCharWidth = measureCharTitle.clientWidth;
  18456. this.dom.frame.removeChild(measureCharTitle);
  18457. }
  18458. };
  18459. /**
  18460. * Snap a date to a rounded value.
  18461. * The snap intervals are dependent on the current scale and step.
  18462. * @param {Date} date the date to be snapped.
  18463. * @return {Date} snappedDate
  18464. */
  18465. DataAxis.prototype.snap = function(date) {
  18466. return this.step.snap(date);
  18467. };
  18468. module.exports = DataAxis;
  18469. /***/ },
  18470. /* 45 */
  18471. /***/ function(module, exports, __webpack_require__) {
  18472. /**
  18473. * @constructor DataStep
  18474. * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
  18475. * end data point. The class itself determines the best scale (step size) based on the
  18476. * provided start Date, end Date, and minimumStep.
  18477. *
  18478. * If minimumStep is provided, the step size is chosen as close as possible
  18479. * to the minimumStep but larger than minimumStep. If minimumStep is not
  18480. * provided, the scale is set to 1 DAY.
  18481. * The minimumStep should correspond with the onscreen size of about 6 characters
  18482. *
  18483. * Alternatively, you can set a scale by hand.
  18484. * After creation, you can initialize the class by executing first(). Then you
  18485. * can iterate from the start date to the end date via next(). You can check if
  18486. * the end date is reached with the function hasNext(). After each step, you can
  18487. * retrieve the current date via getCurrent().
  18488. * The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
  18489. * days, to years.
  18490. *
  18491. * Version: 1.2
  18492. *
  18493. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  18494. * or new Date(2010, 9, 21, 23, 45, 00)
  18495. * @param {Date} [end] The end date
  18496. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  18497. */
  18498. function DataStep(start, end, minimumStep, containerHeight, customRange, alignZeros) {
  18499. // variables
  18500. this.current = 0;
  18501. this.autoScale = true;
  18502. this.stepIndex = 0;
  18503. this.step = 1;
  18504. this.scale = 1;
  18505. this.marginStart;
  18506. this.marginEnd;
  18507. this.deadSpace = 0;
  18508. this.majorSteps = [1, 2, 5, 10];
  18509. this.minorSteps = [0.25, 0.5, 1, 2];
  18510. this.alignZeros = alignZeros;
  18511. this.setRange(start, end, minimumStep, containerHeight, customRange);
  18512. }
  18513. /**
  18514. * Set a new range
  18515. * If minimumStep is provided, the step size is chosen as close as possible
  18516. * to the minimumStep but larger than minimumStep. If minimumStep is not
  18517. * provided, the scale is set to 1 DAY.
  18518. * The minimumStep should correspond with the onscreen size of about 6 characters
  18519. * @param {Number} [start] The start date and time.
  18520. * @param {Number} [end] The end date and time.
  18521. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  18522. */
  18523. DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, customRange) {
  18524. this._start = customRange.min === undefined ? start : customRange.min;
  18525. this._end = customRange.max === undefined ? end : customRange.max;
  18526. if (this._start == this._end) {
  18527. this._start -= 0.75;
  18528. this._end += 1;
  18529. }
  18530. if (this.autoScale == true) {
  18531. this.setMinimumStep(minimumStep, containerHeight);
  18532. }
  18533. this.setFirst(customRange);
  18534. };
  18535. /**
  18536. * Automatically determine the scale that bests fits the provided minimum step
  18537. * @param {Number} [minimumStep] The minimum step size in milliseconds
  18538. */
  18539. DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
  18540. // round to floor
  18541. var size = this._end - this._start;
  18542. var safeSize = size * 1.2;
  18543. var minimumStepValue = minimumStep * (safeSize / containerHeight);
  18544. var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
  18545. var minorStepIdx = -1;
  18546. var magnitudefactor = Math.pow(10,orderOfMagnitude);
  18547. var start = 0;
  18548. if (orderOfMagnitude < 0) {
  18549. start = orderOfMagnitude;
  18550. }
  18551. var solutionFound = false;
  18552. for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) {
  18553. magnitudefactor = Math.pow(10,i);
  18554. for (var j = 0; j < this.minorSteps.length; j++) {
  18555. var stepSize = magnitudefactor * this.minorSteps[j];
  18556. if (stepSize >= minimumStepValue) {
  18557. solutionFound = true;
  18558. minorStepIdx = j;
  18559. break;
  18560. }
  18561. }
  18562. if (solutionFound == true) {
  18563. break;
  18564. }
  18565. }
  18566. this.stepIndex = minorStepIdx;
  18567. this.scale = magnitudefactor;
  18568. this.step = magnitudefactor * this.minorSteps[minorStepIdx];
  18569. };
  18570. /**
  18571. * Round the current date to the first minor date value
  18572. * This must be executed once when the current date is set to start Date
  18573. */
  18574. DataStep.prototype.setFirst = function(customRange) {
  18575. if (customRange === undefined) {
  18576. customRange = {};
  18577. }
  18578. var niceStart = customRange.min === undefined ? this._start - (this.scale * 2 * this.minorSteps[this.stepIndex]) : customRange.min;
  18579. var niceEnd = customRange.max === undefined ? this._end + (this.scale * this.minorSteps[this.stepIndex]) : customRange.max;
  18580. this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max;
  18581. this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min;
  18582. // if we need to align the zero's we need to make sure that there is a zero to use.
  18583. if (this.alignZeros == true && (this.marginEnd - this.marginStart) % this.step != 0) {
  18584. this.marginEnd += this.marginEnd % this.step;
  18585. }
  18586. this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart;
  18587. this.marginRange = this.marginEnd - this.marginStart;
  18588. this.current = this.marginEnd;
  18589. };
  18590. DataStep.prototype.roundToMinor = function(value) {
  18591. var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
  18592. if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
  18593. return rounded + (this.scale * this.minorSteps[this.stepIndex]);
  18594. }
  18595. else {
  18596. return rounded;
  18597. }
  18598. }
  18599. /**
  18600. * Check if the there is a next step
  18601. * @return {boolean} true if the current date has not passed the end date
  18602. */
  18603. DataStep.prototype.hasNext = function () {
  18604. return (this.current >= this.marginStart);
  18605. };
  18606. /**
  18607. * Do the next step
  18608. */
  18609. DataStep.prototype.next = function() {
  18610. var prev = this.current;
  18611. this.current -= this.step;
  18612. // safety mechanism: if current time is still unchanged, move to the end
  18613. if (this.current == prev) {
  18614. this.current = this._end;
  18615. }
  18616. };
  18617. /**
  18618. * Do the next step
  18619. */
  18620. DataStep.prototype.previous = function() {
  18621. this.current += this.step;
  18622. this.marginEnd += this.step;
  18623. this.marginRange = this.marginEnd - this.marginStart;
  18624. };
  18625. /**
  18626. * Get the current datetime
  18627. * @return {String} current The current date
  18628. */
  18629. DataStep.prototype.getCurrent = function(decimals) {
  18630. // prevent round-off errors when close to zero
  18631. var current = (Math.abs(this.current) < this.step / 2) ? 0 : this.current;
  18632. var toPrecision = '' + Number(current).toPrecision(5);
  18633. // If decimals is specified, then limit or extend the string as required
  18634. if(decimals !== undefined && !isNaN(Number(decimals))) {
  18635. // If string includes exponent, then we need to add it to the end
  18636. var exp = "";
  18637. var index = toPrecision.indexOf("e");
  18638. if(index != -1) {
  18639. // Get the exponent
  18640. exp = toPrecision.slice(index);
  18641. // Remove the exponent in case we need to zero-extend
  18642. toPrecision = toPrecision.slice(0, index);
  18643. }
  18644. index = Math.max(toPrecision.indexOf(","), toPrecision.indexOf("."));
  18645. if(index === -1) {
  18646. // No decimal found - if we want decimals, then we need to add it
  18647. if(decimals !== 0) {
  18648. toPrecision += '.';
  18649. }
  18650. // Calculate how long the string should be
  18651. index = toPrecision.length + decimals;
  18652. }
  18653. else if(decimals !== 0) {
  18654. // Calculate how long the string should be - accounting for the decimal place
  18655. index += decimals + 1;
  18656. }
  18657. if(index > toPrecision.length) {
  18658. // We need to add zeros!
  18659. for(var cnt = index - toPrecision.length; cnt > 0; cnt--) {
  18660. toPrecision += '0';
  18661. }
  18662. }
  18663. else {
  18664. // we need to remove characters
  18665. toPrecision = toPrecision.slice(0, index);
  18666. }
  18667. // Add the exponent if there is one
  18668. toPrecision += exp;
  18669. }
  18670. else {
  18671. if (toPrecision.indexOf(",") != -1 || toPrecision.indexOf(".") != -1) {
  18672. // If no decimal is specified, and there are decimal places, remove trailing zeros
  18673. for (var i = toPrecision.length - 1; i > 0; i--) {
  18674. if (toPrecision[i] == "0") {
  18675. toPrecision = toPrecision.slice(0, i);
  18676. }
  18677. else if (toPrecision[i] == "." || toPrecision[i] == ",") {
  18678. toPrecision = toPrecision.slice(0, i);
  18679. break;
  18680. }
  18681. else {
  18682. break;
  18683. }
  18684. }
  18685. }
  18686. }
  18687. return toPrecision;
  18688. };
  18689. /**
  18690. * Snap a date to a rounded value.
  18691. * The snap intervals are dependent on the current scale and step.
  18692. * @param {Date} date the date to be snapped.
  18693. * @return {Date} snappedDate
  18694. */
  18695. DataStep.prototype.snap = function(date) {
  18696. };
  18697. /**
  18698. * Check if the current value is a major value (for example when the step
  18699. * is DAY, a major value is each first day of the MONTH)
  18700. * @return {boolean} true if current date is major, else false.
  18701. */
  18702. DataStep.prototype.isMajor = function() {
  18703. return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
  18704. };
  18705. module.exports = DataStep;
  18706. /***/ },
  18707. /* 46 */
  18708. /***/ function(module, exports, __webpack_require__) {
  18709. var util = __webpack_require__(1);
  18710. var DOMutil = __webpack_require__(6);
  18711. var Line = __webpack_require__(47);
  18712. var Bar = __webpack_require__(49);
  18713. var Points = __webpack_require__(48);
  18714. /**
  18715. * /**
  18716. * @param {object} group | the object of the group from the dataset
  18717. * @param {string} groupId | ID of the group
  18718. * @param {object} options | the default options
  18719. * @param {array} groupsUsingDefaultStyles | this array has one entree.
  18720. * It is passed as an array so it is passed by reference.
  18721. * It enumerates through the default styles
  18722. * @constructor
  18723. */
  18724. function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) {
  18725. this.id = groupId;
  18726. var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom']
  18727. this.options = util.selectiveBridgeObject(fields,options);
  18728. this.usingDefaultStyle = group.className === undefined;
  18729. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  18730. this.zeroPosition = 0;
  18731. this.update(group);
  18732. if (this.usingDefaultStyle == true) {
  18733. this.groupsUsingDefaultStyles[0] += 1;
  18734. }
  18735. this.itemsData = [];
  18736. this.visible = group.visible === undefined ? true : group.visible;
  18737. }
  18738. /**
  18739. * this loads a reference to all items in this group into this group.
  18740. * @param {array} items
  18741. */
  18742. GraphGroup.prototype.setItems = function(items) {
  18743. if (items != null) {
  18744. this.itemsData = items;
  18745. if (this.options.sort == true) {
  18746. this.itemsData.sort(function (a,b) {return a.x - b.x;})
  18747. }
  18748. }
  18749. else {
  18750. this.itemsData = [];
  18751. }
  18752. };
  18753. /**
  18754. * this is used for plotting barcharts, this way, we only have to calculate it once.
  18755. * @param pos
  18756. */
  18757. GraphGroup.prototype.setZeroPosition = function(pos) {
  18758. this.zeroPosition = pos;
  18759. };
  18760. /**
  18761. * set the options of the graph group over the default options.
  18762. * @param options
  18763. */
  18764. GraphGroup.prototype.setOptions = function(options) {
  18765. if (options !== undefined) {
  18766. var fields = ['sampling','style','sort','yAxisOrientation','barChart'];
  18767. util.selectiveDeepExtend(fields, this.options, options);
  18768. util.mergeOptions(this.options, options,'catmullRom');
  18769. util.mergeOptions(this.options, options,'drawPoints');
  18770. util.mergeOptions(this.options, options,'shaded');
  18771. if (options.catmullRom) {
  18772. if (typeof options.catmullRom == 'object') {
  18773. if (options.catmullRom.parametrization) {
  18774. if (options.catmullRom.parametrization == 'uniform') {
  18775. this.options.catmullRom.alpha = 0;
  18776. }
  18777. else if (options.catmullRom.parametrization == 'chordal') {
  18778. this.options.catmullRom.alpha = 1.0;
  18779. }
  18780. else {
  18781. this.options.catmullRom.parametrization = 'centripetal';
  18782. this.options.catmullRom.alpha = 0.5;
  18783. }
  18784. }
  18785. }
  18786. }
  18787. }
  18788. if (this.options.style == 'line') {
  18789. this.type = new Line(this.id, this.options);
  18790. }
  18791. else if (this.options.style == 'bar') {
  18792. this.type = new Bar(this.id, this.options);
  18793. }
  18794. else if (this.options.style == 'points') {
  18795. this.type = new Points(this.id, this.options);
  18796. }
  18797. };
  18798. /**
  18799. * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
  18800. * @param group
  18801. */
  18802. GraphGroup.prototype.update = function(group) {
  18803. this.group = group;
  18804. this.content = group.content || 'graph';
  18805. this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10;
  18806. this.visible = group.visible === undefined ? true : group.visible;
  18807. this.style = group.style;
  18808. this.setOptions(group.options);
  18809. };
  18810. /**
  18811. * draw the icon for the legend.
  18812. *
  18813. * @param x
  18814. * @param y
  18815. * @param JSONcontainer
  18816. * @param SVGcontainer
  18817. * @param iconWidth
  18818. * @param iconHeight
  18819. */
  18820. GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) {
  18821. var fillHeight = iconHeight * 0.5;
  18822. var path, fillPath;
  18823. var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer);
  18824. outline.setAttributeNS(null, "x", x);
  18825. outline.setAttributeNS(null, "y", y - fillHeight);
  18826. outline.setAttributeNS(null, "width", iconWidth);
  18827. outline.setAttributeNS(null, "height", 2*fillHeight);
  18828. outline.setAttributeNS(null, "class", "outline");
  18829. if (this.options.style == 'line') {
  18830. path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  18831. path.setAttributeNS(null, "class", this.className);
  18832. if(this.style !== undefined) {
  18833. path.setAttributeNS(null, "style", this.style);
  18834. }
  18835. path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+"");
  18836. if (this.options.shaded.enabled == true) {
  18837. fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  18838. if (this.options.shaded.orientation == 'top') {
  18839. fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) +
  18840. "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight));
  18841. }
  18842. else {
  18843. fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " +
  18844. "L"+x+"," + (y + fillHeight) + " " +
  18845. "L"+ (x + iconWidth) + "," + (y + fillHeight) +
  18846. "L"+ (x + iconWidth) + ","+y);
  18847. }
  18848. fillPath.setAttributeNS(null, "class", this.className + " iconFill");
  18849. }
  18850. if (this.options.drawPoints.enabled == true) {
  18851. DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer);
  18852. }
  18853. }
  18854. else {
  18855. var barWidth = Math.round(0.3 * iconWidth);
  18856. var bar1Height = Math.round(0.4 * iconHeight);
  18857. var bar2Height = Math.round(0.75 * iconHeight);
  18858. var offset = Math.round((iconWidth - (2 * barWidth))/3);
  18859. DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  18860. DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  18861. }
  18862. };
  18863. /**
  18864. * return the legend entree for this group.
  18865. *
  18866. * @param iconWidth
  18867. * @param iconHeight
  18868. * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
  18869. */
  18870. GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) {
  18871. var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  18872. this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight);
  18873. return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation};
  18874. }
  18875. GraphGroup.prototype.getYRange = function(groupData) {
  18876. return this.type.getYRange(groupData);
  18877. }
  18878. GraphGroup.prototype.draw = function(dataset, group, framework) {
  18879. this.type.draw(dataset, group, framework);
  18880. }
  18881. module.exports = GraphGroup;
  18882. /***/ },
  18883. /* 47 */
  18884. /***/ function(module, exports, __webpack_require__) {
  18885. /**
  18886. * Created by Alex on 11/11/2014.
  18887. */
  18888. var DOMutil = __webpack_require__(6);
  18889. var Points = __webpack_require__(48);
  18890. function Line(groupId, options) {
  18891. this.groupId = groupId;
  18892. this.options = options;
  18893. }
  18894. Line.prototype.getYRange = function(groupData) {
  18895. var yMin = groupData[0].y;
  18896. var yMax = groupData[0].y;
  18897. for (var j = 0; j < groupData.length; j++) {
  18898. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  18899. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  18900. }
  18901. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  18902. };
  18903. /**
  18904. * draw a line graph
  18905. *
  18906. * @param dataset
  18907. * @param group
  18908. */
  18909. Line.prototype.draw = function (dataset, group, framework) {
  18910. if (dataset != null) {
  18911. if (dataset.length > 0) {
  18912. var path, d;
  18913. var svgHeight = Number(framework.svg.style.height.replace('px',''));
  18914. path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  18915. path.setAttributeNS(null, "class", group.className);
  18916. if(group.style !== undefined) {
  18917. path.setAttributeNS(null, "style", group.style);
  18918. }
  18919. // construct path from dataset
  18920. if (group.options.catmullRom.enabled == true) {
  18921. d = Line._catmullRom(dataset, group);
  18922. }
  18923. else {
  18924. d = Line._linear(dataset);
  18925. }
  18926. // append with points for fill and finalize the path
  18927. if (group.options.shaded.enabled == true) {
  18928. var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  18929. var dFill;
  18930. if (group.options.shaded.orientation == 'top') {
  18931. dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0;
  18932. }
  18933. else {
  18934. dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight;
  18935. }
  18936. fillPath.setAttributeNS(null, "class", group.className + " fill");
  18937. if(group.options.shaded.style !== undefined) {
  18938. fillPath.setAttributeNS(null, "style", group.options.shaded.style);
  18939. }
  18940. fillPath.setAttributeNS(null, "d", dFill);
  18941. }
  18942. // copy properties to path for drawing.
  18943. path.setAttributeNS(null, 'd', 'M' + d);
  18944. // draw points
  18945. if (group.options.drawPoints.enabled == true) {
  18946. Points.draw(dataset, group, framework);
  18947. }
  18948. }
  18949. }
  18950. };
  18951. /**
  18952. * This uses an uniform parametrization of the CatmullRom algorithm:
  18953. * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
  18954. * @param data
  18955. * @returns {string}
  18956. * @private
  18957. */
  18958. Line._catmullRomUniform = function(data) {
  18959. // catmull rom
  18960. var p0, p1, p2, p3, bp1, bp2;
  18961. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  18962. var normalization = 1/6;
  18963. var length = data.length;
  18964. for (var i = 0; i < length - 1; i++) {
  18965. p0 = (i == 0) ? data[0] : data[i-1];
  18966. p1 = data[i];
  18967. p2 = data[i+1];
  18968. p3 = (i + 2 < length) ? data[i+2] : p2;
  18969. // Catmull-Rom to Cubic Bezier conversion matrix
  18970. // 0 1 0 0
  18971. // -1/6 1 1/6 0
  18972. // 0 1/6 1 -1/6
  18973. // 0 0 1 0
  18974. // bp0 = { x: p1.x, y: p1.y };
  18975. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  18976. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  18977. // bp0 = { x: p2.x, y: p2.y };
  18978. d += 'C' +
  18979. bp1.x + ',' +
  18980. bp1.y + ' ' +
  18981. bp2.x + ',' +
  18982. bp2.y + ' ' +
  18983. p2.x + ',' +
  18984. p2.y + ' ';
  18985. }
  18986. return d;
  18987. };
  18988. /**
  18989. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  18990. * By default, the centripetal parameterization is used because this gives the nicest results.
  18991. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  18992. *
  18993. * One optimization can be used to reuse distances since this is a sliding window approach.
  18994. * @param data
  18995. * @param group
  18996. * @returns {string}
  18997. * @private
  18998. */
  18999. Line._catmullRom = function(data, group) {
  19000. var alpha = group.options.catmullRom.alpha;
  19001. if (alpha == 0 || alpha === undefined) {
  19002. return this._catmullRomUniform(data);
  19003. }
  19004. else {
  19005. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  19006. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  19007. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  19008. var length = data.length;
  19009. for (var i = 0; i < length - 1; i++) {
  19010. p0 = (i == 0) ? data[0] : data[i-1];
  19011. p1 = data[i];
  19012. p2 = data[i+1];
  19013. p3 = (i + 2 < length) ? data[i+2] : p2;
  19014. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  19015. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  19016. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  19017. // Catmull-Rom to Cubic Bezier conversion matrix
  19018. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  19019. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  19020. // [ 0 1 0 0 ]
  19021. // [ -d2^2a /N A/N d1^2a /N 0 ]
  19022. // [ 0 d3^2a /M B/M -d2^2a /M ]
  19023. // [ 0 0 1 0 ]
  19024. d3powA = Math.pow(d3, alpha);
  19025. d3pow2A = Math.pow(d3,2*alpha);
  19026. d2powA = Math.pow(d2, alpha);
  19027. d2pow2A = Math.pow(d2,2*alpha);
  19028. d1powA = Math.pow(d1, alpha);
  19029. d1pow2A = Math.pow(d1,2*alpha);
  19030. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  19031. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  19032. N = 3*d1powA * (d1powA + d2powA);
  19033. if (N > 0) {N = 1 / N;}
  19034. M = 3*d3powA * (d3powA + d2powA);
  19035. if (M > 0) {M = 1 / M;}
  19036. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  19037. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  19038. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  19039. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  19040. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  19041. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  19042. d += 'C' +
  19043. bp1.x + ',' +
  19044. bp1.y + ' ' +
  19045. bp2.x + ',' +
  19046. bp2.y + ' ' +
  19047. p2.x + ',' +
  19048. p2.y + ' ';
  19049. }
  19050. return d;
  19051. }
  19052. };
  19053. /**
  19054. * this generates the SVG path for a linear drawing between datapoints.
  19055. * @param data
  19056. * @returns {string}
  19057. * @private
  19058. */
  19059. Line._linear = function(data) {
  19060. // linear
  19061. var d = '';
  19062. for (var i = 0; i < data.length; i++) {
  19063. if (i == 0) {
  19064. d += data[i].x + ',' + data[i].y;
  19065. }
  19066. else {
  19067. d += ' ' + data[i].x + ',' + data[i].y;
  19068. }
  19069. }
  19070. return d;
  19071. };
  19072. module.exports = Line;
  19073. /***/ },
  19074. /* 48 */
  19075. /***/ function(module, exports, __webpack_require__) {
  19076. /**
  19077. * Created by Alex on 11/11/2014.
  19078. */
  19079. var DOMutil = __webpack_require__(6);
  19080. function Points(groupId, options) {
  19081. this.groupId = groupId;
  19082. this.options = options;
  19083. }
  19084. Points.prototype.getYRange = function(groupData) {
  19085. var yMin = groupData[0].y;
  19086. var yMax = groupData[0].y;
  19087. for (var j = 0; j < groupData.length; j++) {
  19088. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  19089. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  19090. }
  19091. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  19092. };
  19093. Points.prototype.draw = function(dataset, group, framework, offset) {
  19094. Points.draw(dataset, group, framework, offset);
  19095. }
  19096. /**
  19097. * draw the data points
  19098. *
  19099. * @param {Array} dataset
  19100. * @param {Object} JSONcontainer
  19101. * @param {Object} svg | SVG DOM element
  19102. * @param {GraphGroup} group
  19103. * @param {Number} [offset]
  19104. */
  19105. Points.draw = function (dataset, group, framework, offset) {
  19106. if (offset === undefined) {offset = 0;}
  19107. for (var i = 0; i < dataset.length; i++) {
  19108. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg);
  19109. }
  19110. };
  19111. module.exports = Points;
  19112. /***/ },
  19113. /* 49 */
  19114. /***/ function(module, exports, __webpack_require__) {
  19115. /**
  19116. * Created by Alex on 11/11/2014.
  19117. */
  19118. var DOMutil = __webpack_require__(6);
  19119. var Points = __webpack_require__(48);
  19120. function Bargraph(groupId, options) {
  19121. this.groupId = groupId;
  19122. this.options = options;
  19123. }
  19124. Bargraph.prototype.getYRange = function(groupData) {
  19125. if (this.options.barChart.handleOverlap != 'stack') {
  19126. var yMin = groupData[0].y;
  19127. var yMax = groupData[0].y;
  19128. for (var j = 0; j < groupData.length; j++) {
  19129. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  19130. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  19131. }
  19132. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  19133. }
  19134. else {
  19135. var barCombinedData = [];
  19136. for (var j = 0; j < groupData.length; j++) {
  19137. barCombinedData.push({
  19138. x: groupData[j].x,
  19139. y: groupData[j].y,
  19140. groupId: this.groupId
  19141. });
  19142. }
  19143. return barCombinedData;
  19144. }
  19145. };
  19146. /**
  19147. * draw a bar graph
  19148. *
  19149. * @param groupIds
  19150. * @param processedGroupData
  19151. */
  19152. Bargraph.draw = function (groupIds, processedGroupData, framework) {
  19153. var combinedData = [];
  19154. var intersections = {};
  19155. var coreDistance;
  19156. var key, drawData;
  19157. var group;
  19158. var i,j;
  19159. var barPoints = 0;
  19160. // combine all barchart data
  19161. for (i = 0; i < groupIds.length; i++) {
  19162. group = framework.groups[groupIds[i]];
  19163. if (group.options.style == 'bar') {
  19164. if (group.visible == true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] == true)) {
  19165. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  19166. combinedData.push({
  19167. x: processedGroupData[groupIds[i]][j].x,
  19168. y: processedGroupData[groupIds[i]][j].y,
  19169. groupId: groupIds[i]
  19170. });
  19171. barPoints += 1;
  19172. }
  19173. }
  19174. }
  19175. }
  19176. if (barPoints == 0) {return;}
  19177. // sort by time and by group
  19178. combinedData.sort(function (a, b) {
  19179. if (a.x == b.x) {
  19180. return a.groupId - b.groupId;
  19181. } else {
  19182. return a.x - b.x;
  19183. }
  19184. });
  19185. // get intersections
  19186. Bargraph._getDataIntersections(intersections, combinedData);
  19187. // plot barchart
  19188. for (i = 0; i < combinedData.length; i++) {
  19189. group = framework.groups[combinedData[i].groupId];
  19190. var minWidth = 0.1 * group.options.barChart.width;
  19191. key = combinedData[i].x;
  19192. var heightOffset = 0;
  19193. if (intersections[key] === undefined) {
  19194. if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);}
  19195. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));}
  19196. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  19197. }
  19198. else {
  19199. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  19200. var prevKey = i - (intersections[key].resolved + 1);
  19201. if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);}
  19202. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));}
  19203. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  19204. intersections[key].resolved += 1;
  19205. if (group.options.barChart.handleOverlap == 'stack') {
  19206. heightOffset = intersections[key].accumulated;
  19207. intersections[key].accumulated += group.zeroPosition - combinedData[i].y;
  19208. }
  19209. else if (group.options.barChart.handleOverlap == 'sideBySide') {
  19210. drawData.width = drawData.width / intersections[key].amount;
  19211. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  19212. if (group.options.barChart.align == 'left') {drawData.offset -= 0.5*drawData.width;}
  19213. else if (group.options.barChart.align == 'right') {drawData.offset += 0.5*drawData.width;}
  19214. }
  19215. }
  19216. 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);
  19217. // draw points
  19218. if (group.options.drawPoints.enabled == true) {
  19219. DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg);
  19220. }
  19221. }
  19222. };
  19223. /**
  19224. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  19225. * @param intersections
  19226. * @param combinedData
  19227. * @private
  19228. */
  19229. Bargraph._getDataIntersections = function (intersections, combinedData) {
  19230. // get intersections
  19231. var coreDistance;
  19232. for (var i = 0; i < combinedData.length; i++) {
  19233. if (i + 1 < combinedData.length) {
  19234. coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x);
  19235. }
  19236. if (i > 0) {
  19237. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x));
  19238. }
  19239. if (coreDistance == 0) {
  19240. if (intersections[combinedData[i].x] === undefined) {
  19241. intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0};
  19242. }
  19243. intersections[combinedData[i].x].amount += 1;
  19244. }
  19245. }
  19246. };
  19247. /**
  19248. * Get the width and offset for bargraphs based on the coredistance between datapoints
  19249. *
  19250. * @param coreDistance
  19251. * @param group
  19252. * @param minWidth
  19253. * @returns {{width: Number, offset: Number}}
  19254. * @private
  19255. */
  19256. Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) {
  19257. var width, offset;
  19258. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  19259. width = coreDistance < minWidth ? minWidth : coreDistance;
  19260. offset = 0; // recalculate offset with the new width;
  19261. if (group.options.barChart.align == 'left') {
  19262. offset -= 0.5 * coreDistance;
  19263. }
  19264. else if (group.options.barChart.align == 'right') {
  19265. offset += 0.5 * coreDistance;
  19266. }
  19267. }
  19268. else {
  19269. // default settings
  19270. width = group.options.barChart.width;
  19271. offset = 0;
  19272. if (group.options.barChart.align == 'left') {
  19273. offset -= 0.5 * group.options.barChart.width;
  19274. }
  19275. else if (group.options.barChart.align == 'right') {
  19276. offset += 0.5 * group.options.barChart.width;
  19277. }
  19278. }
  19279. return {width: width, offset: offset};
  19280. };
  19281. Bargraph.getStackedBarYRange = function(barCombinedData, groupRanges, groupIds, groupLabel, orientation) {
  19282. if (barCombinedData.length > 0) {
  19283. // sort by time and by group
  19284. barCombinedData.sort(function (a, b) {
  19285. if (a.x == b.x) {
  19286. return a.groupId - b.groupId;
  19287. } else {
  19288. return a.x - b.x;
  19289. }
  19290. });
  19291. var intersections = {};
  19292. Bargraph._getDataIntersections(intersections, barCombinedData);
  19293. groupRanges[groupLabel] = Bargraph._getStackedBarYRange(intersections, barCombinedData);
  19294. groupRanges[groupLabel].yAxisOrientation = orientation;
  19295. groupIds.push(groupLabel);
  19296. }
  19297. }
  19298. Bargraph._getStackedBarYRange = function (intersections, combinedData) {
  19299. var key;
  19300. var yMin = combinedData[0].y;
  19301. var yMax = combinedData[0].y;
  19302. for (var i = 0; i < combinedData.length; i++) {
  19303. key = combinedData[i].x;
  19304. if (intersections[key] === undefined) {
  19305. yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin;
  19306. yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax;
  19307. }
  19308. else {
  19309. intersections[key].accumulated += combinedData[i].y;
  19310. }
  19311. }
  19312. for (var xpos in intersections) {
  19313. if (intersections.hasOwnProperty(xpos)) {
  19314. yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin;
  19315. yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax;
  19316. }
  19317. }
  19318. return {min: yMin, max: yMax};
  19319. };
  19320. module.exports = Bargraph;
  19321. /***/ },
  19322. /* 50 */
  19323. /***/ function(module, exports, __webpack_require__) {
  19324. var util = __webpack_require__(1);
  19325. var DOMutil = __webpack_require__(6);
  19326. var Component = __webpack_require__(23);
  19327. /**
  19328. * Legend for Graph2d
  19329. */
  19330. function Legend(body, options, side, linegraphOptions) {
  19331. this.body = body;
  19332. this.defaultOptions = {
  19333. enabled: true,
  19334. icons: true,
  19335. iconSize: 20,
  19336. iconSpacing: 6,
  19337. left: {
  19338. visible: true,
  19339. position: 'top-left' // top/bottom - left,center,right
  19340. },
  19341. right: {
  19342. visible: true,
  19343. position: 'top-left' // top/bottom - left,center,right
  19344. }
  19345. }
  19346. this.side = side;
  19347. this.options = util.extend({},this.defaultOptions);
  19348. this.linegraphOptions = linegraphOptions;
  19349. this.svgElements = {};
  19350. this.dom = {};
  19351. this.groups = {};
  19352. this.amountOfGroups = 0;
  19353. this._create();
  19354. this.setOptions(options);
  19355. }
  19356. Legend.prototype = new Component();
  19357. Legend.prototype.clear = function() {
  19358. this.groups = {};
  19359. this.amountOfGroups = 0;
  19360. }
  19361. Legend.prototype.addGroup = function(label, graphOptions) {
  19362. if (!this.groups.hasOwnProperty(label)) {
  19363. this.groups[label] = graphOptions;
  19364. }
  19365. this.amountOfGroups += 1;
  19366. };
  19367. Legend.prototype.updateGroup = function(label, graphOptions) {
  19368. this.groups[label] = graphOptions;
  19369. };
  19370. Legend.prototype.removeGroup = function(label) {
  19371. if (this.groups.hasOwnProperty(label)) {
  19372. delete this.groups[label];
  19373. this.amountOfGroups -= 1;
  19374. }
  19375. };
  19376. Legend.prototype._create = function() {
  19377. this.dom.frame = document.createElement('div');
  19378. this.dom.frame.className = 'legend';
  19379. this.dom.frame.style.position = "absolute";
  19380. this.dom.frame.style.top = "10px";
  19381. this.dom.frame.style.display = "block";
  19382. this.dom.textArea = document.createElement('div');
  19383. this.dom.textArea.className = 'legendText';
  19384. this.dom.textArea.style.position = "relative";
  19385. this.dom.textArea.style.top = "0px";
  19386. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  19387. this.svg.style.position = 'absolute';
  19388. this.svg.style.top = 0 +'px';
  19389. this.svg.style.width = this.options.iconSize + 5 + 'px';
  19390. this.svg.style.height = '100%';
  19391. this.dom.frame.appendChild(this.svg);
  19392. this.dom.frame.appendChild(this.dom.textArea);
  19393. };
  19394. /**
  19395. * Hide the component from the DOM
  19396. */
  19397. Legend.prototype.hide = function() {
  19398. // remove the frame containing the items
  19399. if (this.dom.frame.parentNode) {
  19400. this.dom.frame.parentNode.removeChild(this.dom.frame);
  19401. }
  19402. };
  19403. /**
  19404. * Show the component in the DOM (when not already visible).
  19405. * @return {Boolean} changed
  19406. */
  19407. Legend.prototype.show = function() {
  19408. // show frame containing the items
  19409. if (!this.dom.frame.parentNode) {
  19410. this.body.dom.center.appendChild(this.dom.frame);
  19411. }
  19412. };
  19413. Legend.prototype.setOptions = function(options) {
  19414. var fields = ['enabled','orientation','icons','left','right'];
  19415. util.selectiveDeepExtend(fields, this.options, options);
  19416. };
  19417. Legend.prototype.redraw = function() {
  19418. var activeGroups = 0;
  19419. for (var groupId in this.groups) {
  19420. if (this.groups.hasOwnProperty(groupId)) {
  19421. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  19422. activeGroups++;
  19423. }
  19424. }
  19425. }
  19426. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  19427. this.hide();
  19428. }
  19429. else {
  19430. this.show();
  19431. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  19432. this.dom.frame.style.left = '4px';
  19433. this.dom.frame.style.textAlign = "left";
  19434. this.dom.textArea.style.textAlign = "left";
  19435. this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px';
  19436. this.dom.textArea.style.right = '';
  19437. this.svg.style.left = 0 +'px';
  19438. this.svg.style.right = '';
  19439. }
  19440. else {
  19441. this.dom.frame.style.right = '4px';
  19442. this.dom.frame.style.textAlign = "right";
  19443. this.dom.textArea.style.textAlign = "right";
  19444. this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px';
  19445. this.dom.textArea.style.left = '';
  19446. this.svg.style.right = 0 +'px';
  19447. this.svg.style.left = '';
  19448. }
  19449. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  19450. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  19451. this.dom.frame.style.bottom = '';
  19452. }
  19453. else {
  19454. var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height;
  19455. this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  19456. this.dom.frame.style.top = '';
  19457. }
  19458. if (this.options.icons == false) {
  19459. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  19460. this.dom.textArea.style.right = '';
  19461. this.dom.textArea.style.left = '';
  19462. this.svg.style.width = '0px';
  19463. }
  19464. else {
  19465. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'
  19466. this.drawLegendIcons();
  19467. }
  19468. var content = '';
  19469. for (var groupId in this.groups) {
  19470. if (this.groups.hasOwnProperty(groupId)) {
  19471. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  19472. content += this.groups[groupId].content + '<br />';
  19473. }
  19474. }
  19475. }
  19476. this.dom.textArea.innerHTML = content;
  19477. this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px';
  19478. }
  19479. };
  19480. Legend.prototype.drawLegendIcons = function() {
  19481. if (this.dom.frame.parentNode) {
  19482. DOMutil.prepareElements(this.svgElements);
  19483. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  19484. var iconOffset = Number(padding.replace('px',''));
  19485. var x = iconOffset;
  19486. var iconWidth = this.options.iconSize;
  19487. var iconHeight = 0.75 * this.options.iconSize;
  19488. var y = iconOffset + 0.5 * iconHeight + 3;
  19489. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  19490. for (var groupId in this.groups) {
  19491. if (this.groups.hasOwnProperty(groupId)) {
  19492. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  19493. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  19494. y += iconHeight + this.options.iconSpacing;
  19495. }
  19496. }
  19497. }
  19498. DOMutil.cleanupElements(this.svgElements);
  19499. }
  19500. };
  19501. module.exports = Legend;
  19502. /***/ },
  19503. /* 51 */
  19504. /***/ function(module, exports, __webpack_require__) {
  19505. var Emitter = __webpack_require__(11);
  19506. var Hammer = __webpack_require__(19);
  19507. var keycharm = __webpack_require__(36);
  19508. var util = __webpack_require__(1);
  19509. var hammerUtil = __webpack_require__(22);
  19510. var DataSet = __webpack_require__(7);
  19511. var DataView = __webpack_require__(9);
  19512. var dotparser = __webpack_require__(57);
  19513. var gephiParser = __webpack_require__(58);
  19514. var Groups = __webpack_require__(54);
  19515. var Images = __webpack_require__(55);
  19516. var Node = __webpack_require__(53);
  19517. var Edge = __webpack_require__(52);
  19518. var Popup = __webpack_require__(56);
  19519. var MixinLoader = __webpack_require__(59);
  19520. var Activator = __webpack_require__(35);
  19521. var locales = __webpack_require__(60);
  19522. // Load custom shapes into CanvasRenderingContext2D
  19523. __webpack_require__(61);
  19524. /**
  19525. * @constructor Network
  19526. * Create a network visualization, displaying nodes and edges.
  19527. *
  19528. * @param {Element} container The DOM element in which the Network will
  19529. * be created. Normally a div element.
  19530. * @param {Object} data An object containing parameters
  19531. * {Array} nodes
  19532. * {Array} edges
  19533. * @param {Object} options Options
  19534. */
  19535. function Network (container, data, options) {
  19536. if (!(this instanceof Network)) {
  19537. throw new SyntaxError('Constructor must be called with the new operator');
  19538. }
  19539. this._initializeMixinLoaders();
  19540. // create variables and set default values
  19541. this.containerElement = container;
  19542. // render and calculation settings
  19543. this.renderRefreshRate = 60; // hz (fps)
  19544. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  19545. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  19546. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  19547. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation
  19548. this.initializing = true;
  19549. this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null};
  19550. // set constant values
  19551. this.defaultOptions = {
  19552. nodes: {
  19553. mass: 1,
  19554. radiusMin: 10,
  19555. radiusMax: 30,
  19556. radius: 10,
  19557. shape: 'ellipse',
  19558. image: undefined,
  19559. widthMin: 16, // px
  19560. widthMax: 64, // px
  19561. fontColor: 'black',
  19562. fontSize: 14, // px
  19563. fontFace: 'verdana',
  19564. fontFill: undefined,
  19565. level: -1,
  19566. color: {
  19567. border: '#2B7CE9',
  19568. background: '#97C2FC',
  19569. highlight: {
  19570. border: '#2B7CE9',
  19571. background: '#D2E5FF'
  19572. },
  19573. hover: {
  19574. border: '#2B7CE9',
  19575. background: '#D2E5FF'
  19576. }
  19577. },
  19578. borderColor: '#2B7CE9',
  19579. backgroundColor: '#97C2FC',
  19580. highlightColor: '#D2E5FF',
  19581. group: undefined,
  19582. borderWidth: 1,
  19583. borderWidthSelected: undefined
  19584. },
  19585. edges: {
  19586. widthMin: 1, //
  19587. widthMax: 15,//
  19588. width: 1,
  19589. widthSelectionMultiplier: 2,
  19590. hoverWidth: 1.5,
  19591. style: 'line',
  19592. color: {
  19593. color:'#848484',
  19594. highlight:'#848484',
  19595. hover: '#848484'
  19596. },
  19597. fontColor: '#343434',
  19598. fontSize: 14, // px
  19599. fontFace: 'arial',
  19600. fontFill: 'white',
  19601. arrowScaleFactor: 1,
  19602. dash: {
  19603. length: 10,
  19604. gap: 5,
  19605. altLength: undefined
  19606. },
  19607. inheritColor: "from" // to, from, false, true (== from)
  19608. },
  19609. configurePhysics:false,
  19610. physics: {
  19611. barnesHut: {
  19612. enabled: true,
  19613. theta: 1 / 0.6, // inverted to save time during calculation
  19614. gravitationalConstant: -2000,
  19615. centralGravity: 0.3,
  19616. springLength: 95,
  19617. springConstant: 0.04,
  19618. damping: 0.09
  19619. },
  19620. repulsion: {
  19621. centralGravity: 0.0,
  19622. springLength: 200,
  19623. springConstant: 0.05,
  19624. nodeDistance: 100,
  19625. damping: 0.09
  19626. },
  19627. hierarchicalRepulsion: {
  19628. enabled: false,
  19629. centralGravity: 0.0,
  19630. springLength: 100,
  19631. springConstant: 0.01,
  19632. nodeDistance: 150,
  19633. damping: 0.09
  19634. },
  19635. damping: null,
  19636. centralGravity: null,
  19637. springLength: null,
  19638. springConstant: null
  19639. },
  19640. clustering: { // Per Node in Cluster = PNiC
  19641. enabled: false, // (Boolean) | global on/off switch for clustering.
  19642. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  19643. 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
  19644. 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
  19645. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  19646. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  19647. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  19648. 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.
  19649. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  19650. maxFontSize: 1000,
  19651. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  19652. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  19653. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  19654. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  19655. height: 1, // (px PNiC) | growth of the height per node in cluster.
  19656. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  19657. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  19658. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  19659. clusterLevelDifference: 2
  19660. },
  19661. navigation: {
  19662. enabled: false
  19663. },
  19664. keyboard: {
  19665. enabled: false,
  19666. speed: {x: 10, y: 10, zoom: 0.02}
  19667. },
  19668. dataManipulation: {
  19669. enabled: false,
  19670. initiallyVisible: false
  19671. },
  19672. hierarchicalLayout: {
  19673. enabled:false,
  19674. levelSeparation: 150,
  19675. nodeSpacing: 100,
  19676. direction: "UD", // UD, DU, LR, RL
  19677. layout: "hubsize" // hubsize, directed
  19678. },
  19679. freezeForStabilization: false,
  19680. smoothCurves: {
  19681. enabled: true,
  19682. dynamic: true,
  19683. type: "continuous",
  19684. roundness: 0.5
  19685. },
  19686. maxVelocity: 30,
  19687. minVelocity: 0.1, // px/s
  19688. stabilize: true, // stabilize before displaying the network
  19689. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  19690. zoomExtentOnStabilize: true,
  19691. locale: 'en',
  19692. locales: locales,
  19693. tooltip: {
  19694. delay: 300,
  19695. fontColor: 'black',
  19696. fontSize: 14, // px
  19697. fontFace: 'verdana',
  19698. color: {
  19699. border: '#666',
  19700. background: '#FFFFC6'
  19701. }
  19702. },
  19703. dragNetwork: true,
  19704. dragNodes: true,
  19705. zoomable: true,
  19706. hover: false,
  19707. hideEdgesOnDrag: false,
  19708. hideNodesOnDrag: false,
  19709. width : '100%',
  19710. height : '100%',
  19711. selectable: true
  19712. };
  19713. this.constants = util.extend({}, this.defaultOptions);
  19714. this.pixelRatio = 1;
  19715. this.hoverObj = {nodes:{},edges:{}};
  19716. this.controlNodesActive = false;
  19717. this.navigationHammers = {existing:[], _new: []};
  19718. // animation properties
  19719. this.animationSpeed = 1/this.renderRefreshRate;
  19720. this.animationEasingFunction = "easeInOutQuint";
  19721. this.easingTime = 0;
  19722. this.sourceScale = 0;
  19723. this.targetScale = 0;
  19724. this.sourceTranslation = 0;
  19725. this.targetTranslation = 0;
  19726. this.lockedOnNodeId = null;
  19727. this.lockedOnNodeOffset = null;
  19728. this.touchTime = 0;
  19729. // Node variables
  19730. var network = this;
  19731. this.groups = new Groups(); // object with groups
  19732. this.images = new Images(); // object with images
  19733. this.images.setOnloadCallback(function () {
  19734. network._redraw();
  19735. });
  19736. // keyboard navigation variables
  19737. this.xIncrement = 0;
  19738. this.yIncrement = 0;
  19739. this.zoomIncrement = 0;
  19740. // loading all the mixins:
  19741. // load the force calculation functions, grouped under the physics system.
  19742. this._loadPhysicsSystem();
  19743. // create a frame and canvas
  19744. this._create();
  19745. // load the sector system. (mandatory, fully integrated with Network)
  19746. this._loadSectorSystem();
  19747. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  19748. this._loadClusterSystem();
  19749. // load the selection system. (mandatory, required by Network)
  19750. this._loadSelectionSystem();
  19751. // load the selection system. (mandatory, required by Network)
  19752. this._loadHierarchySystem();
  19753. // apply options
  19754. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  19755. this._setScale(1);
  19756. this.setOptions(options);
  19757. // other vars
  19758. this.freezeSimulation = false;// freeze the simulation
  19759. this.cachedFunctions = {};
  19760. this.startedStabilization = false;
  19761. this.stabilized = false;
  19762. this.stabilizationIterations = null;
  19763. this.draggingNodes = false;
  19764. // containers for nodes and edges
  19765. this.calculationNodes = {};
  19766. this.calculationNodeIndices = [];
  19767. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  19768. this.nodes = {}; // object with Node objects
  19769. this.edges = {}; // object with Edge objects
  19770. // position and scale variables and objects
  19771. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  19772. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  19773. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  19774. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  19775. this.scale = 1; // defining the global scale variable in the constructor
  19776. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  19777. // datasets or dataviews
  19778. this.nodesData = null; // A DataSet or DataView
  19779. this.edgesData = null; // A DataSet or DataView
  19780. // create event listeners used to subscribe on the DataSets of the nodes and edges
  19781. this.nodesListeners = {
  19782. 'add': function (event, params) {
  19783. network._addNodes(params.items);
  19784. network.start();
  19785. },
  19786. 'update': function (event, params) {
  19787. network._updateNodes(params.items, params.data);
  19788. network.start();
  19789. },
  19790. 'remove': function (event, params) {
  19791. network._removeNodes(params.items);
  19792. network.start();
  19793. }
  19794. };
  19795. this.edgesListeners = {
  19796. 'add': function (event, params) {
  19797. network._addEdges(params.items);
  19798. network.start();
  19799. },
  19800. 'update': function (event, params) {
  19801. network._updateEdges(params.items);
  19802. network.start();
  19803. },
  19804. 'remove': function (event, params) {
  19805. network._removeEdges(params.items);
  19806. network.start();
  19807. }
  19808. };
  19809. // properties for the animation
  19810. this.moving = true;
  19811. this.timer = undefined; // Scheduling function. Is definded in this.start();
  19812. // load data (the disable start variable will be the same as the enabled clustering)
  19813. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  19814. // hierarchical layout
  19815. this.initializing = false;
  19816. if (this.constants.hierarchicalLayout.enabled == true) {
  19817. this._setupHierarchicalLayout();
  19818. }
  19819. else {
  19820. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  19821. if (this.constants.stabilize == false) {
  19822. this.zoomExtent(undefined, true,this.constants.clustering.enabled);
  19823. }
  19824. }
  19825. // if clustering is disabled, the simulation will have started in the setData function
  19826. if (this.constants.clustering.enabled) {
  19827. this.startWithClustering();
  19828. }
  19829. }
  19830. // Extend Network with an Emitter mixin
  19831. Emitter(Network.prototype);
  19832. /**
  19833. * Get the script path where the vis.js library is located
  19834. *
  19835. * @returns {string | null} path Path or null when not found. Path does not
  19836. * end with a slash.
  19837. * @private
  19838. */
  19839. Network.prototype._getScriptPath = function() {
  19840. var scripts = document.getElementsByTagName( 'script' );
  19841. // find script named vis.js or vis.min.js
  19842. for (var i = 0; i < scripts.length; i++) {
  19843. var src = scripts[i].src;
  19844. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  19845. if (match) {
  19846. // return path without the script name
  19847. return src.substring(0, src.length - match[0].length);
  19848. }
  19849. }
  19850. return null;
  19851. };
  19852. /**
  19853. * Find the center position of the network
  19854. * @private
  19855. */
  19856. Network.prototype._getRange = function() {
  19857. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  19858. for (var nodeId in this.nodes) {
  19859. if (this.nodes.hasOwnProperty(nodeId)) {
  19860. node = this.nodes[nodeId];
  19861. if (minX > (node.x)) {minX = node.x;}
  19862. if (maxX < (node.x)) {maxX = node.x;}
  19863. if (minY > (node.y)) {minY = node.y;}
  19864. if (maxY < (node.y)) {maxY = node.y;}
  19865. }
  19866. }
  19867. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  19868. minY = 0, maxY = 0, minX = 0, maxX = 0;
  19869. }
  19870. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  19871. };
  19872. /**
  19873. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  19874. * @returns {{x: number, y: number}}
  19875. * @private
  19876. */
  19877. Network.prototype._findCenter = function(range) {
  19878. return {x: (0.5 * (range.maxX + range.minX)),
  19879. y: (0.5 * (range.maxY + range.minY))};
  19880. };
  19881. /**
  19882. * This function zooms out to fit all data on screen based on amount of nodes
  19883. *
  19884. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  19885. * @param {Boolean} [disableStart] | If true, start is not called.
  19886. */
  19887. Network.prototype.zoomExtent = function(animationOptions, initialZoom, disableStart) {
  19888. if (initialZoom === undefined) {
  19889. initialZoom = false;
  19890. }
  19891. if (disableStart === undefined) {
  19892. disableStart = false;
  19893. }
  19894. if (animationOptions === undefined) {
  19895. animationOptions = false;
  19896. }
  19897. var range = this._getRange();
  19898. var zoomLevel;
  19899. if (initialZoom == true) {
  19900. var numberOfNodes = this.nodeIndices.length;
  19901. if (this.constants.smoothCurves == true) {
  19902. if (this.constants.clustering.enabled == true &&
  19903. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  19904. 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.
  19905. }
  19906. else {
  19907. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  19908. }
  19909. }
  19910. else {
  19911. if (this.constants.clustering.enabled == true &&
  19912. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  19913. 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.
  19914. }
  19915. else {
  19916. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  19917. }
  19918. }
  19919. // correct for larger canvasses.
  19920. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  19921. zoomLevel *= factor;
  19922. }
  19923. else {
  19924. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  19925. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  19926. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  19927. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  19928. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  19929. }
  19930. if (zoomLevel > 1.0) {
  19931. zoomLevel = 1.0;
  19932. }
  19933. var center = this._findCenter(range);
  19934. if (disableStart == false) {
  19935. var options = {position: center, scale: zoomLevel, animation: animationOptions};
  19936. this.moveTo(options);
  19937. this.moving = true;
  19938. this.start();
  19939. }
  19940. else {
  19941. center.x *= zoomLevel;
  19942. center.y *= zoomLevel;
  19943. center.x -= 0.5 * this.frame.canvas.clientWidth;
  19944. center.y -= 0.5 * this.frame.canvas.clientHeight;
  19945. this._setScale(zoomLevel);
  19946. this._setTranslation(-center.x,-center.y);
  19947. }
  19948. };
  19949. /**
  19950. * Update the this.nodeIndices with the most recent node index list
  19951. * @private
  19952. */
  19953. Network.prototype._updateNodeIndexList = function() {
  19954. this._clearNodeIndexList();
  19955. for (var idx in this.nodes) {
  19956. if (this.nodes.hasOwnProperty(idx)) {
  19957. this.nodeIndices.push(idx);
  19958. }
  19959. }
  19960. };
  19961. /**
  19962. * Set nodes and edges, and optionally options as well.
  19963. *
  19964. * @param {Object} data Object containing parameters:
  19965. * {Array | DataSet | DataView} [nodes] Array with nodes
  19966. * {Array | DataSet | DataView} [edges] Array with edges
  19967. * {String} [dot] String containing data in DOT format
  19968. * {String} [gephi] String containing data in gephi JSON format
  19969. * {Options} [options] Object with options
  19970. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  19971. */
  19972. Network.prototype.setData = function(data, disableStart) {
  19973. if (disableStart === undefined) {
  19974. disableStart = false;
  19975. }
  19976. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  19977. this.initializing = true;
  19978. if (data && data.dot && (data.nodes || data.edges)) {
  19979. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  19980. ' parameter pair "nodes" and "edges", but not both.');
  19981. }
  19982. // set options
  19983. this.setOptions(data && data.options);
  19984. // set all data
  19985. if (data && data.dot) {
  19986. // parse DOT file
  19987. if(data && data.dot) {
  19988. var dotData = dotparser.DOTToGraph(data.dot);
  19989. this.setData(dotData);
  19990. return;
  19991. }
  19992. }
  19993. else if (data && data.gephi) {
  19994. // parse DOT file
  19995. if(data && data.gephi) {
  19996. var gephiData = gephiParser.parseGephi(data.gephi);
  19997. this.setData(gephiData);
  19998. return;
  19999. }
  20000. }
  20001. else {
  20002. this._setNodes(data && data.nodes);
  20003. this._setEdges(data && data.edges);
  20004. }
  20005. this._putDataInSector();
  20006. if (disableStart == false) {
  20007. if (this.constants.hierarchicalLayout.enabled == true) {
  20008. this._resetLevels();
  20009. this._setupHierarchicalLayout();
  20010. }
  20011. else {
  20012. // find a stable position or start animating to a stable position
  20013. if (this.constants.stabilize) {
  20014. this._stabilize();
  20015. }
  20016. }
  20017. this.start();
  20018. }
  20019. this.initializing = false;
  20020. };
  20021. /**
  20022. * Set options
  20023. * @param {Object} options
  20024. */
  20025. Network.prototype.setOptions = function (options) {
  20026. if (options) {
  20027. var prop;
  20028. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation',
  20029. 'keyboard','dataManipulation','onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  20030. ];
  20031. // extend all but the values in fields
  20032. util.selectiveNotDeepExtend(fields,this.constants, options);
  20033. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  20034. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  20035. if (options.physics) {
  20036. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  20037. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  20038. if (options.physics.hierarchicalRepulsion) {
  20039. this.constants.hierarchicalLayout.enabled = true;
  20040. this.constants.physics.hierarchicalRepulsion.enabled = true;
  20041. this.constants.physics.barnesHut.enabled = false;
  20042. for (prop in options.physics.hierarchicalRepulsion) {
  20043. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  20044. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  20045. }
  20046. }
  20047. }
  20048. }
  20049. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  20050. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  20051. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  20052. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  20053. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  20054. util.mergeOptions(this.constants, options,'smoothCurves');
  20055. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  20056. util.mergeOptions(this.constants, options,'clustering');
  20057. util.mergeOptions(this.constants, options,'navigation');
  20058. util.mergeOptions(this.constants, options,'keyboard');
  20059. util.mergeOptions(this.constants, options,'dataManipulation');
  20060. if (options.dataManipulation) {
  20061. this.editMode = this.constants.dataManipulation.initiallyVisible;
  20062. }
  20063. // TODO: work out these options and document them
  20064. if (options.edges) {
  20065. if (options.edges.color !== undefined) {
  20066. if (util.isString(options.edges.color)) {
  20067. this.constants.edges.color = {};
  20068. this.constants.edges.color.color = options.edges.color;
  20069. this.constants.edges.color.highlight = options.edges.color;
  20070. this.constants.edges.color.hover = options.edges.color;
  20071. }
  20072. else {
  20073. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  20074. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  20075. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  20076. }
  20077. }
  20078. if (!options.edges.fontColor) {
  20079. if (options.edges.color !== undefined) {
  20080. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  20081. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  20082. }
  20083. }
  20084. }
  20085. if (options.nodes) {
  20086. if (options.nodes.color) {
  20087. var newColorObj = util.parseColor(options.nodes.color);
  20088. this.constants.nodes.color.background = newColorObj.background;
  20089. this.constants.nodes.color.border = newColorObj.border;
  20090. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  20091. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  20092. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  20093. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  20094. }
  20095. }
  20096. if (options.groups) {
  20097. for (var groupname in options.groups) {
  20098. if (options.groups.hasOwnProperty(groupname)) {
  20099. var group = options.groups[groupname];
  20100. this.groups.add(groupname, group);
  20101. }
  20102. }
  20103. }
  20104. if (options.tooltip) {
  20105. for (prop in options.tooltip) {
  20106. if (options.tooltip.hasOwnProperty(prop)) {
  20107. this.constants.tooltip[prop] = options.tooltip[prop];
  20108. }
  20109. }
  20110. if (options.tooltip.color) {
  20111. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  20112. }
  20113. }
  20114. if ('clickToUse' in options) {
  20115. if (options.clickToUse) {
  20116. this.activator = new Activator(this.frame);
  20117. this.activator.on('change', this._createKeyBinds.bind(this));
  20118. }
  20119. else {
  20120. if (this.activator) {
  20121. this.activator.destroy();
  20122. delete this.activator;
  20123. }
  20124. }
  20125. }
  20126. if (options.labels) {
  20127. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  20128. }
  20129. }
  20130. // (Re)loading the mixins that can be enabled or disabled in the options.
  20131. // load the force calculation functions, grouped under the physics system.
  20132. this._loadPhysicsSystem();
  20133. // load the navigation system.
  20134. this._loadNavigationControls();
  20135. // load the data manipulation system
  20136. this._loadManipulationSystem();
  20137. // configure the smooth curves
  20138. this._configureSmoothCurves();
  20139. // bind keys. If disabled, this will not do anything;
  20140. this._createKeyBinds();
  20141. this.setSize(this.constants.width, this.constants.height);
  20142. this.moving = true;
  20143. this.start();
  20144. };
  20145. /**
  20146. * Create the main frame for the Network.
  20147. * This function is executed once when a Network object is created. The frame
  20148. * contains a canvas, and this canvas contains all objects like the axis and
  20149. * nodes.
  20150. * @private
  20151. */
  20152. Network.prototype._create = function () {
  20153. // remove all elements from the container element.
  20154. while (this.containerElement.hasChildNodes()) {
  20155. this.containerElement.removeChild(this.containerElement.firstChild);
  20156. }
  20157. this.frame = document.createElement('div');
  20158. this.frame.className = 'vis network-frame';
  20159. this.frame.style.position = 'relative';
  20160. this.frame.style.overflow = 'hidden';
  20161. //////////////////////////////////////////////////////////////////
  20162. this.frame.canvas = document.createElement("canvas");
  20163. this.frame.canvas.style.position = 'relative';
  20164. this.frame.appendChild(this.frame.canvas);
  20165. if (!this.frame.canvas.getContext) {
  20166. var noCanvas = document.createElement( 'DIV' );
  20167. noCanvas.style.color = 'red';
  20168. noCanvas.style.fontWeight = 'bold' ;
  20169. noCanvas.style.padding = '10px';
  20170. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  20171. this.frame.canvas.appendChild(noCanvas);
  20172. }
  20173. else {
  20174. var ctx = this.frame.canvas.getContext("2d");
  20175. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  20176. ctx.mozBackingStorePixelRatio ||
  20177. ctx.msBackingStorePixelRatio ||
  20178. ctx.oBackingStorePixelRatio ||
  20179. ctx.backingStorePixelRatio || 1);
  20180. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  20181. }
  20182. //////////////////////////////////////////////////////////////////
  20183. var me = this;
  20184. this.drag = {};
  20185. this.pinch = {};
  20186. this.hammer = Hammer(this.frame.canvas, {
  20187. prevent_default: true
  20188. });
  20189. this.hammer.on('tap', me._onTap.bind(me) );
  20190. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  20191. this.hammer.on('hold', me._onHold.bind(me) );
  20192. this.hammer.on('pinch', me._onPinch.bind(me) );
  20193. this.hammer.on('touch', me._onTouch.bind(me) );
  20194. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  20195. this.hammer.on('drag', me._onDrag.bind(me) );
  20196. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  20197. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  20198. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  20199. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  20200. this.hammerFrame = Hammer(this.frame, {
  20201. prevent_default: true
  20202. });
  20203. this.hammerFrame.on('release', me._onRelease.bind(me) );
  20204. // add the frame to the container element
  20205. this.containerElement.appendChild(this.frame);
  20206. };
  20207. /**
  20208. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  20209. * @private
  20210. */
  20211. Network.prototype._createKeyBinds = function() {
  20212. var me = this;
  20213. if (this.keycharm !== undefined) {
  20214. this.keycharm.destroy();
  20215. }
  20216. this.keycharm = keycharm();
  20217. this.keycharm.reset();
  20218. if (this.constants.keyboard.enabled && this.isActive()) {
  20219. this.keycharm.bind("up", this._moveUp.bind(me) , "keydown");
  20220. this.keycharm.bind("up", this._yStopMoving.bind(me), "keyup");
  20221. this.keycharm.bind("down", this._moveDown.bind(me) , "keydown");
  20222. this.keycharm.bind("down", this._yStopMoving.bind(me), "keyup");
  20223. this.keycharm.bind("left", this._moveLeft.bind(me) , "keydown");
  20224. this.keycharm.bind("left", this._xStopMoving.bind(me), "keyup");
  20225. this.keycharm.bind("right",this._moveRight.bind(me), "keydown");
  20226. this.keycharm.bind("right",this._xStopMoving.bind(me), "keyup");
  20227. this.keycharm.bind("=", this._zoomIn.bind(me), "keydown");
  20228. this.keycharm.bind("=", this._stopZoom.bind(me), "keyup");
  20229. this.keycharm.bind("num+", this._zoomIn.bind(me), "keydown");
  20230. this.keycharm.bind("num+", this._stopZoom.bind(me), "keyup");
  20231. this.keycharm.bind("num-", this._zoomOut.bind(me), "keydown");
  20232. this.keycharm.bind("num-", this._stopZoom.bind(me), "keyup");
  20233. this.keycharm.bind("-", this._zoomOut.bind(me), "keydown");
  20234. this.keycharm.bind("-", this._stopZoom.bind(me), "keyup");
  20235. this.keycharm.bind("[", this._zoomIn.bind(me), "keydown");
  20236. this.keycharm.bind("[", this._stopZoom.bind(me), "keyup");
  20237. this.keycharm.bind("]", this._zoomOut.bind(me), "keydown");
  20238. this.keycharm.bind("]", this._stopZoom.bind(me), "keyup");
  20239. this.keycharm.bind("pageup",this._zoomIn.bind(me), "keydown");
  20240. this.keycharm.bind("pageup",this._stopZoom.bind(me), "keyup");
  20241. this.keycharm.bind("pagedown",this._zoomOut.bind(me),"keydown");
  20242. this.keycharm.bind("pagedown",this._stopZoom.bind(me), "keyup");
  20243. }
  20244. if (this.constants.dataManipulation.enabled == true) {
  20245. this.keycharm.bind("esc",this._createManipulatorBar.bind(me));
  20246. this.keycharm.bind("delete",this._deleteSelected.bind(me));
  20247. }
  20248. };
  20249. Network.prototype.destroy = function() {
  20250. // remove keybindings
  20251. this.keycharm.reset();
  20252. // clear hammer bindings
  20253. this.hammer.dispose();
  20254. // clear events
  20255. this.off();
  20256. }
  20257. /**
  20258. * Get the pointer location from a touch location
  20259. * @param {{pageX: Number, pageY: Number}} touch
  20260. * @return {{x: Number, y: Number}} pointer
  20261. * @private
  20262. */
  20263. Network.prototype._getPointer = function (touch) {
  20264. return {
  20265. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  20266. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  20267. };
  20268. };
  20269. /**
  20270. * On start of a touch gesture, store the pointer
  20271. * @param event
  20272. * @private
  20273. */
  20274. Network.prototype._onTouch = function (event) {
  20275. if (new Date().valueOf() - this.touchTime > 100) {
  20276. this.drag.pointer = this._getPointer(event.gesture.center);
  20277. this.drag.pinched = false;
  20278. this.pinch.scale = this._getScale();
  20279. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  20280. this.touchTime = new Date().valueOf();
  20281. this._handleTouch(this.drag.pointer);
  20282. }
  20283. };
  20284. /**
  20285. * handle drag start event
  20286. * @private
  20287. */
  20288. Network.prototype._onDragStart = function () {
  20289. this._handleDragStart();
  20290. };
  20291. /**
  20292. * This function is called by _onDragStart.
  20293. * It is separated out because we can then overload it for the datamanipulation system.
  20294. *
  20295. * @private
  20296. */
  20297. Network.prototype._handleDragStart = function() {
  20298. var drag = this.drag;
  20299. var node = this._getNodeAt(drag.pointer);
  20300. // note: drag.pointer is set in _onTouch to get the initial touch location
  20301. drag.dragging = true;
  20302. drag.selection = [];
  20303. drag.translation = this._getTranslation();
  20304. drag.nodeId = null;
  20305. this.draggingNodes = false;
  20306. if (node != null && this.constants.dragNodes == true) {
  20307. this.draggingNodes = true;
  20308. drag.nodeId = node.id;
  20309. // select the clicked node if not yet selected
  20310. if (!node.isSelected()) {
  20311. this._selectObject(node,false);
  20312. }
  20313. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  20314. // create an array with the selected nodes and their original location and status
  20315. for (var objectId in this.selectionObj.nodes) {
  20316. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  20317. var object = this.selectionObj.nodes[objectId];
  20318. var s = {
  20319. id: object.id,
  20320. node: object,
  20321. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  20322. x: object.x,
  20323. y: object.y,
  20324. xFixed: object.xFixed,
  20325. yFixed: object.yFixed
  20326. };
  20327. object.xFixed = true;
  20328. object.yFixed = true;
  20329. drag.selection.push(s);
  20330. }
  20331. }
  20332. }
  20333. };
  20334. /**
  20335. * handle drag event
  20336. * @private
  20337. */
  20338. Network.prototype._onDrag = function (event) {
  20339. this._handleOnDrag(event)
  20340. };
  20341. /**
  20342. * This function is called by _onDrag.
  20343. * It is separated out because we can then overload it for the datamanipulation system.
  20344. *
  20345. * @private
  20346. */
  20347. Network.prototype._handleOnDrag = function(event) {
  20348. if (this.drag.pinched) {
  20349. return;
  20350. }
  20351. // remove the focus on node if it is focussed on by the focusOnNode
  20352. this.releaseNode();
  20353. var pointer = this._getPointer(event.gesture.center);
  20354. var me = this;
  20355. var drag = this.drag;
  20356. var selection = drag.selection;
  20357. if (selection && selection.length && this.constants.dragNodes == true) {
  20358. // calculate delta's and new location
  20359. var deltaX = pointer.x - drag.pointer.x;
  20360. var deltaY = pointer.y - drag.pointer.y;
  20361. // update position of all selected nodes
  20362. selection.forEach(function (s) {
  20363. var node = s.node;
  20364. if (!s.xFixed) {
  20365. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  20366. }
  20367. if (!s.yFixed) {
  20368. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  20369. }
  20370. });
  20371. // start _animationStep if not yet running
  20372. if (!this.moving) {
  20373. this.moving = true;
  20374. this.start();
  20375. }
  20376. }
  20377. else {
  20378. if (this.constants.dragNetwork == true) {
  20379. // move the network
  20380. var diffX = pointer.x - this.drag.pointer.x;
  20381. var diffY = pointer.y - this.drag.pointer.y;
  20382. this._setTranslation(
  20383. this.drag.translation.x + diffX,
  20384. this.drag.translation.y + diffY
  20385. );
  20386. this._redraw();
  20387. // this.moving = true;
  20388. // this.start();
  20389. }
  20390. }
  20391. };
  20392. /**
  20393. * handle drag start event
  20394. * @private
  20395. */
  20396. Network.prototype._onDragEnd = function (event) {
  20397. this._handleDragEnd(event);
  20398. };
  20399. Network.prototype._handleDragEnd = function(event) {
  20400. this.drag.dragging = false;
  20401. var selection = this.drag.selection;
  20402. if (selection && selection.length) {
  20403. selection.forEach(function (s) {
  20404. // restore original xFixed and yFixed
  20405. s.node.xFixed = s.xFixed;
  20406. s.node.yFixed = s.yFixed;
  20407. });
  20408. this.moving = true;
  20409. this.start();
  20410. }
  20411. else {
  20412. this._redraw();
  20413. }
  20414. if (this.draggingNodes == false) {
  20415. this.emit("dragEnd",{nodeIds:[]});
  20416. }
  20417. else {
  20418. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  20419. }
  20420. }
  20421. /**
  20422. * handle tap/click event: select/unselect a node
  20423. * @private
  20424. */
  20425. Network.prototype._onTap = function (event) {
  20426. var pointer = this._getPointer(event.gesture.center);
  20427. this.pointerPosition = pointer;
  20428. this._handleTap(pointer);
  20429. };
  20430. /**
  20431. * handle doubletap event
  20432. * @private
  20433. */
  20434. Network.prototype._onDoubleTap = function (event) {
  20435. var pointer = this._getPointer(event.gesture.center);
  20436. this._handleDoubleTap(pointer);
  20437. };
  20438. /**
  20439. * handle long tap event: multi select nodes
  20440. * @private
  20441. */
  20442. Network.prototype._onHold = function (event) {
  20443. var pointer = this._getPointer(event.gesture.center);
  20444. this.pointerPosition = pointer;
  20445. this._handleOnHold(pointer);
  20446. };
  20447. /**
  20448. * handle the release of the screen
  20449. *
  20450. * @private
  20451. */
  20452. Network.prototype._onRelease = function (event) {
  20453. var pointer = this._getPointer(event.gesture.center);
  20454. this._handleOnRelease(pointer);
  20455. };
  20456. /**
  20457. * Handle pinch event
  20458. * @param event
  20459. * @private
  20460. */
  20461. Network.prototype._onPinch = function (event) {
  20462. var pointer = this._getPointer(event.gesture.center);
  20463. this.drag.pinched = true;
  20464. if (!('scale' in this.pinch)) {
  20465. this.pinch.scale = 1;
  20466. }
  20467. // TODO: enabled moving while pinching?
  20468. var scale = this.pinch.scale * event.gesture.scale;
  20469. this._zoom(scale, pointer)
  20470. };
  20471. /**
  20472. * Zoom the network in or out
  20473. * @param {Number} scale a number around 1, and between 0.01 and 10
  20474. * @param {{x: Number, y: Number}} pointer Position on screen
  20475. * @return {Number} appliedScale scale is limited within the boundaries
  20476. * @private
  20477. */
  20478. Network.prototype._zoom = function(scale, pointer) {
  20479. if (this.constants.zoomable == true) {
  20480. var scaleOld = this._getScale();
  20481. if (scale < 0.00001) {
  20482. scale = 0.00001;
  20483. }
  20484. if (scale > 10) {
  20485. scale = 10;
  20486. }
  20487. var preScaleDragPointer = null;
  20488. if (this.drag !== undefined) {
  20489. if (this.drag.dragging == true) {
  20490. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  20491. }
  20492. }
  20493. // + this.frame.canvas.clientHeight / 2
  20494. var translation = this._getTranslation();
  20495. var scaleFrac = scale / scaleOld;
  20496. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  20497. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  20498. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  20499. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  20500. this._setScale(scale);
  20501. this._setTranslation(tx, ty);
  20502. this.updateClustersDefault();
  20503. if (preScaleDragPointer != null) {
  20504. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  20505. this.drag.pointer.x = postScaleDragPointer.x;
  20506. this.drag.pointer.y = postScaleDragPointer.y;
  20507. }
  20508. this._redraw();
  20509. if (scaleOld < scale) {
  20510. this.emit("zoom", {direction:"+"});
  20511. }
  20512. else {
  20513. this.emit("zoom", {direction:"-"});
  20514. }
  20515. return scale;
  20516. }
  20517. };
  20518. /**
  20519. * Event handler for mouse wheel event, used to zoom the timeline
  20520. * See http://adomas.org/javascript-mouse-wheel/
  20521. * https://github.com/EightMedia/hammer.js/issues/256
  20522. * @param {MouseEvent} event
  20523. * @private
  20524. */
  20525. Network.prototype._onMouseWheel = function(event) {
  20526. // retrieve delta
  20527. var delta = 0;
  20528. if (event.wheelDelta) { /* IE/Opera. */
  20529. delta = event.wheelDelta/120;
  20530. } else if (event.detail) { /* Mozilla case. */
  20531. // In Mozilla, sign of delta is different than in IE.
  20532. // Also, delta is multiple of 3.
  20533. delta = -event.detail/3;
  20534. }
  20535. // If delta is nonzero, handle it.
  20536. // Basically, delta is now positive if wheel was scrolled up,
  20537. // and negative, if wheel was scrolled down.
  20538. if (delta) {
  20539. // calculate the new scale
  20540. var scale = this._getScale();
  20541. var zoom = delta / 10;
  20542. if (delta < 0) {
  20543. zoom = zoom / (1 - zoom);
  20544. }
  20545. scale *= (1 + zoom);
  20546. // calculate the pointer location
  20547. var gesture = hammerUtil.fakeGesture(this, event);
  20548. var pointer = this._getPointer(gesture.center);
  20549. // apply the new scale
  20550. this._zoom(scale, pointer);
  20551. }
  20552. // Prevent default actions caused by mouse wheel.
  20553. event.preventDefault();
  20554. };
  20555. /**
  20556. * Mouse move handler for checking whether the title moves over a node with a title.
  20557. * @param {Event} event
  20558. * @private
  20559. */
  20560. Network.prototype._onMouseMoveTitle = function (event) {
  20561. var gesture = hammerUtil.fakeGesture(this, event);
  20562. var pointer = this._getPointer(gesture.center);
  20563. // check if the previously selected node is still selected
  20564. if (this.popupObj) {
  20565. this._checkHidePopup(pointer);
  20566. }
  20567. // start a timeout that will check if the mouse is positioned above
  20568. // an element
  20569. var me = this;
  20570. var checkShow = function() {
  20571. me._checkShowPopup(pointer);
  20572. };
  20573. if (this.popupTimer) {
  20574. clearInterval(this.popupTimer); // stop any running calculationTimer
  20575. }
  20576. if (!this.drag.dragging) {
  20577. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  20578. }
  20579. /**
  20580. * Adding hover highlights
  20581. */
  20582. if (this.constants.hover == true) {
  20583. // removing all hover highlights
  20584. for (var edgeId in this.hoverObj.edges) {
  20585. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  20586. this.hoverObj.edges[edgeId].hover = false;
  20587. delete this.hoverObj.edges[edgeId];
  20588. }
  20589. }
  20590. // adding hover highlights
  20591. var obj = this._getNodeAt(pointer);
  20592. if (obj == null) {
  20593. obj = this._getEdgeAt(pointer);
  20594. }
  20595. if (obj != null) {
  20596. this._hoverObject(obj);
  20597. }
  20598. // removing all node hover highlights except for the selected one.
  20599. for (var nodeId in this.hoverObj.nodes) {
  20600. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  20601. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  20602. this._blurObject(this.hoverObj.nodes[nodeId]);
  20603. delete this.hoverObj.nodes[nodeId];
  20604. }
  20605. }
  20606. }
  20607. this.redraw();
  20608. }
  20609. };
  20610. /**
  20611. * Check if there is an element on the given position in the network
  20612. * (a node or edge). If so, and if this element has a title,
  20613. * show a popup window with its title.
  20614. *
  20615. * @param {{x:Number, y:Number}} pointer
  20616. * @private
  20617. */
  20618. Network.prototype._checkShowPopup = function (pointer) {
  20619. var obj = {
  20620. left: this._XconvertDOMtoCanvas(pointer.x),
  20621. top: this._YconvertDOMtoCanvas(pointer.y),
  20622. right: this._XconvertDOMtoCanvas(pointer.x),
  20623. bottom: this._YconvertDOMtoCanvas(pointer.y)
  20624. };
  20625. var id;
  20626. var lastPopupNode = this.popupObj;
  20627. if (this.popupObj == undefined) {
  20628. // search the nodes for overlap, select the top one in case of multiple nodes
  20629. var nodes = this.nodes;
  20630. for (id in nodes) {
  20631. if (nodes.hasOwnProperty(id)) {
  20632. var node = nodes[id];
  20633. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  20634. this.popupObj = node;
  20635. break;
  20636. }
  20637. }
  20638. }
  20639. }
  20640. if (this.popupObj === undefined) {
  20641. // search the edges for overlap
  20642. var edges = this.edges;
  20643. for (id in edges) {
  20644. if (edges.hasOwnProperty(id)) {
  20645. var edge = edges[id];
  20646. if (edge.connected && (edge.getTitle() !== undefined) &&
  20647. edge.isOverlappingWith(obj)) {
  20648. this.popupObj = edge;
  20649. break;
  20650. }
  20651. }
  20652. }
  20653. }
  20654. if (this.popupObj) {
  20655. // show popup message window
  20656. if (this.popupObj != lastPopupNode) {
  20657. var me = this;
  20658. if (!me.popup) {
  20659. me.popup = new Popup(me.frame, me.constants.tooltip);
  20660. }
  20661. // adjust a small offset such that the mouse cursor is located in the
  20662. // bottom left location of the popup, and you can easily move over the
  20663. // popup area
  20664. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  20665. me.popup.setText(me.popupObj.getTitle());
  20666. me.popup.show();
  20667. }
  20668. }
  20669. else {
  20670. if (this.popup) {
  20671. this.popup.hide();
  20672. }
  20673. }
  20674. };
  20675. /**
  20676. * Check if the popup must be hided, which is the case when the mouse is no
  20677. * longer hovering on the object
  20678. * @param {{x:Number, y:Number}} pointer
  20679. * @private
  20680. */
  20681. Network.prototype._checkHidePopup = function (pointer) {
  20682. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  20683. this.popupObj = undefined;
  20684. if (this.popup) {
  20685. this.popup.hide();
  20686. }
  20687. }
  20688. };
  20689. /**
  20690. * Set a new size for the network
  20691. * @param {string} width Width in pixels or percentage (for example '800px'
  20692. * or '50%')
  20693. * @param {string} height Height in pixels or percentage (for example '400px'
  20694. * or '30%')
  20695. */
  20696. Network.prototype.setSize = function(width, height) {
  20697. var emitEvent = false;
  20698. var oldWidth = this.frame.canvas.width;
  20699. var oldHeight = this.frame.canvas.height;
  20700. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  20701. this.frame.style.width = width;
  20702. this.frame.style.height = height;
  20703. this.frame.canvas.style.width = '100%';
  20704. this.frame.canvas.style.height = '100%';
  20705. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  20706. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  20707. this.constants.width = width;
  20708. this.constants.height = height;
  20709. emitEvent = true;
  20710. }
  20711. else {
  20712. // this would adapt the width of the canvas to the width from 100% if and only if
  20713. // there is a change.
  20714. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  20715. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  20716. emitEvent = true;
  20717. }
  20718. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  20719. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  20720. emitEvent = true;
  20721. }
  20722. }
  20723. if (emitEvent == true) {
  20724. 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});
  20725. }
  20726. };
  20727. /**
  20728. * Set a data set with nodes for the network
  20729. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  20730. * @private
  20731. */
  20732. Network.prototype._setNodes = function(nodes) {
  20733. var oldNodesData = this.nodesData;
  20734. if (nodes instanceof DataSet || nodes instanceof DataView) {
  20735. this.nodesData = nodes;
  20736. }
  20737. else if (Array.isArray(nodes)) {
  20738. this.nodesData = new DataSet();
  20739. this.nodesData.add(nodes);
  20740. }
  20741. else if (!nodes) {
  20742. this.nodesData = new DataSet();
  20743. }
  20744. else {
  20745. throw new TypeError('Array or DataSet expected');
  20746. }
  20747. if (oldNodesData) {
  20748. // unsubscribe from old dataset
  20749. util.forEach(this.nodesListeners, function (callback, event) {
  20750. oldNodesData.off(event, callback);
  20751. });
  20752. }
  20753. // remove drawn nodes
  20754. this.nodes = {};
  20755. if (this.nodesData) {
  20756. // subscribe to new dataset
  20757. var me = this;
  20758. util.forEach(this.nodesListeners, function (callback, event) {
  20759. me.nodesData.on(event, callback);
  20760. });
  20761. // draw all new nodes
  20762. var ids = this.nodesData.getIds();
  20763. this._addNodes(ids);
  20764. }
  20765. this._updateSelection();
  20766. };
  20767. /**
  20768. * Add nodes
  20769. * @param {Number[] | String[]} ids
  20770. * @private
  20771. */
  20772. Network.prototype._addNodes = function(ids) {
  20773. var id;
  20774. for (var i = 0, len = ids.length; i < len; i++) {
  20775. id = ids[i];
  20776. var data = this.nodesData.get(id);
  20777. var node = new Node(data, this.images, this.groups, this.constants);
  20778. this.nodes[id] = node; // note: this may replace an existing node
  20779. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  20780. var radius = 10 * 0.1*ids.length + 10;
  20781. var angle = 2 * Math.PI * Math.random();
  20782. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  20783. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  20784. }
  20785. this.moving = true;
  20786. }
  20787. this._updateNodeIndexList();
  20788. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20789. this._resetLevels();
  20790. this._setupHierarchicalLayout();
  20791. }
  20792. this._updateCalculationNodes();
  20793. this._reconnectEdges();
  20794. this._updateValueRange(this.nodes);
  20795. this.updateLabels();
  20796. };
  20797. /**
  20798. * Update existing nodes, or create them when not yet existing
  20799. * @param {Number[] | String[]} ids
  20800. * @private
  20801. */
  20802. Network.prototype._updateNodes = function(ids,changedData) {
  20803. var nodes = this.nodes;
  20804. for (var i = 0, len = ids.length; i < len; i++) {
  20805. var id = ids[i];
  20806. var node = nodes[id];
  20807. var data = changedData[i];
  20808. if (node) {
  20809. // update node
  20810. node.setProperties(data, this.constants);
  20811. }
  20812. else {
  20813. // create node
  20814. node = new Node(properties, this.images, this.groups, this.constants);
  20815. nodes[id] = node;
  20816. }
  20817. }
  20818. this.moving = true;
  20819. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20820. this._resetLevels();
  20821. this._setupHierarchicalLayout();
  20822. }
  20823. this._updateNodeIndexList();
  20824. this._updateValueRange(nodes);
  20825. };
  20826. /**
  20827. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  20828. * @param {Number[] | String[]} ids
  20829. * @private
  20830. */
  20831. Network.prototype._removeNodes = function(ids) {
  20832. var nodes = this.nodes;
  20833. for (var i = 0, len = ids.length; i < len; i++) {
  20834. var id = ids[i];
  20835. delete nodes[id];
  20836. }
  20837. this._updateNodeIndexList();
  20838. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20839. this._resetLevels();
  20840. this._setupHierarchicalLayout();
  20841. }
  20842. this._updateCalculationNodes();
  20843. this._reconnectEdges();
  20844. this._updateSelection();
  20845. this._updateValueRange(nodes);
  20846. };
  20847. /**
  20848. * Load edges by reading the data table
  20849. * @param {Array | DataSet | DataView} edges The data containing the edges.
  20850. * @private
  20851. * @private
  20852. */
  20853. Network.prototype._setEdges = function(edges) {
  20854. var oldEdgesData = this.edgesData;
  20855. if (edges instanceof DataSet || edges instanceof DataView) {
  20856. this.edgesData = edges;
  20857. }
  20858. else if (Array.isArray(edges)) {
  20859. this.edgesData = new DataSet();
  20860. this.edgesData.add(edges);
  20861. }
  20862. else if (!edges) {
  20863. this.edgesData = new DataSet();
  20864. }
  20865. else {
  20866. throw new TypeError('Array or DataSet expected');
  20867. }
  20868. if (oldEdgesData) {
  20869. // unsubscribe from old dataset
  20870. util.forEach(this.edgesListeners, function (callback, event) {
  20871. oldEdgesData.off(event, callback);
  20872. });
  20873. }
  20874. // remove drawn edges
  20875. this.edges = {};
  20876. if (this.edgesData) {
  20877. // subscribe to new dataset
  20878. var me = this;
  20879. util.forEach(this.edgesListeners, function (callback, event) {
  20880. me.edgesData.on(event, callback);
  20881. });
  20882. // draw all new nodes
  20883. var ids = this.edgesData.getIds();
  20884. this._addEdges(ids);
  20885. }
  20886. this._reconnectEdges();
  20887. };
  20888. /**
  20889. * Add edges
  20890. * @param {Number[] | String[]} ids
  20891. * @private
  20892. */
  20893. Network.prototype._addEdges = function (ids) {
  20894. var edges = this.edges,
  20895. edgesData = this.edgesData;
  20896. for (var i = 0, len = ids.length; i < len; i++) {
  20897. var id = ids[i];
  20898. var oldEdge = edges[id];
  20899. if (oldEdge) {
  20900. oldEdge.disconnect();
  20901. }
  20902. var data = edgesData.get(id, {"showInternalIds" : true});
  20903. edges[id] = new Edge(data, this, this.constants);
  20904. }
  20905. this.moving = true;
  20906. this._updateValueRange(edges);
  20907. this._createBezierNodes();
  20908. this._updateCalculationNodes();
  20909. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20910. this._resetLevels();
  20911. this._setupHierarchicalLayout();
  20912. }
  20913. };
  20914. /**
  20915. * Update existing edges, or create them when not yet existing
  20916. * @param {Number[] | String[]} ids
  20917. * @private
  20918. */
  20919. Network.prototype._updateEdges = function (ids) {
  20920. var edges = this.edges,
  20921. edgesData = this.edgesData;
  20922. for (var i = 0, len = ids.length; i < len; i++) {
  20923. var id = ids[i];
  20924. var data = edgesData.get(id);
  20925. var edge = edges[id];
  20926. if (edge) {
  20927. // update edge
  20928. edge.disconnect();
  20929. edge.setProperties(data, this.constants);
  20930. edge.connect();
  20931. }
  20932. else {
  20933. // create edge
  20934. edge = new Edge(data, this, this.constants);
  20935. this.edges[id] = edge;
  20936. }
  20937. }
  20938. this._createBezierNodes();
  20939. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20940. this._resetLevels();
  20941. this._setupHierarchicalLayout();
  20942. }
  20943. this.moving = true;
  20944. this._updateValueRange(edges);
  20945. };
  20946. /**
  20947. * Remove existing edges. Non existing ids will be ignored
  20948. * @param {Number[] | String[]} ids
  20949. * @private
  20950. */
  20951. Network.prototype._removeEdges = function (ids) {
  20952. var edges = this.edges;
  20953. for (var i = 0, len = ids.length; i < len; i++) {
  20954. var id = ids[i];
  20955. var edge = edges[id];
  20956. if (edge) {
  20957. if (edge.via != null) {
  20958. delete this.sectors['support']['nodes'][edge.via.id];
  20959. }
  20960. edge.disconnect();
  20961. delete edges[id];
  20962. }
  20963. }
  20964. this.moving = true;
  20965. this._updateValueRange(edges);
  20966. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20967. this._resetLevels();
  20968. this._setupHierarchicalLayout();
  20969. }
  20970. this._updateCalculationNodes();
  20971. };
  20972. /**
  20973. * Reconnect all edges
  20974. * @private
  20975. */
  20976. Network.prototype._reconnectEdges = function() {
  20977. var id,
  20978. nodes = this.nodes,
  20979. edges = this.edges;
  20980. for (id in nodes) {
  20981. if (nodes.hasOwnProperty(id)) {
  20982. nodes[id].edges = [];
  20983. nodes[id].dynamicEdges = [];
  20984. }
  20985. }
  20986. for (id in edges) {
  20987. if (edges.hasOwnProperty(id)) {
  20988. var edge = edges[id];
  20989. edge.from = null;
  20990. edge.to = null;
  20991. edge.connect();
  20992. }
  20993. }
  20994. };
  20995. /**
  20996. * Update the values of all object in the given array according to the current
  20997. * value range of the objects in the array.
  20998. * @param {Object} obj An object containing a set of Edges or Nodes
  20999. * The objects must have a method getValue() and
  21000. * setValueRange(min, max).
  21001. * @private
  21002. */
  21003. Network.prototype._updateValueRange = function(obj) {
  21004. var id;
  21005. // determine the range of the objects
  21006. var valueMin = undefined;
  21007. var valueMax = undefined;
  21008. for (id in obj) {
  21009. if (obj.hasOwnProperty(id)) {
  21010. var value = obj[id].getValue();
  21011. if (value !== undefined) {
  21012. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  21013. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  21014. }
  21015. }
  21016. }
  21017. // adjust the range of all objects
  21018. if (valueMin !== undefined && valueMax !== undefined) {
  21019. for (id in obj) {
  21020. if (obj.hasOwnProperty(id)) {
  21021. obj[id].setValueRange(valueMin, valueMax);
  21022. }
  21023. }
  21024. }
  21025. };
  21026. /**
  21027. * Redraw the network with the current data
  21028. * chart will be resized too.
  21029. */
  21030. Network.prototype.redraw = function() {
  21031. this.setSize(this.constants.width, this.constants.height);
  21032. this._redraw();
  21033. };
  21034. /**
  21035. * Redraw the network with the current data
  21036. * @private
  21037. */
  21038. Network.prototype._redraw = function() {
  21039. var ctx = this.frame.canvas.getContext('2d');
  21040. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  21041. // clear the canvas
  21042. var w = this.frame.canvas.width * this.pixelRatio;
  21043. var h = this.frame.canvas.height * this.pixelRatio;
  21044. ctx.clearRect(0, 0, w, h);
  21045. // set scaling and translation
  21046. ctx.save();
  21047. ctx.translate(this.translation.x, this.translation.y);
  21048. ctx.scale(this.scale, this.scale);
  21049. this.canvasTopLeft = {
  21050. "x": this._XconvertDOMtoCanvas(0),
  21051. "y": this._YconvertDOMtoCanvas(0)
  21052. };
  21053. this.canvasBottomRight = {
  21054. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth * this.pixelRatio),
  21055. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight * this.pixelRatio)
  21056. };
  21057. this._doInAllSectors("_drawAllSectorNodes",ctx);
  21058. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  21059. this._doInAllSectors("_drawEdges",ctx);
  21060. }
  21061. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  21062. this._doInAllSectors("_drawNodes",ctx,false);
  21063. }
  21064. if (this.controlNodesActive == true) {
  21065. this._doInAllSectors("_drawControlNodes",ctx);
  21066. }
  21067. // this._doInSupportSector("_drawNodes",ctx,true);
  21068. // this._drawTree(ctx,"#F00F0F");
  21069. // restore original scaling and translation
  21070. ctx.restore();
  21071. };
  21072. /**
  21073. * Set the translation of the network
  21074. * @param {Number} offsetX Horizontal offset
  21075. * @param {Number} offsetY Vertical offset
  21076. * @private
  21077. */
  21078. Network.prototype._setTranslation = function(offsetX, offsetY) {
  21079. if (this.translation === undefined) {
  21080. this.translation = {
  21081. x: 0,
  21082. y: 0
  21083. };
  21084. }
  21085. if (offsetX !== undefined) {
  21086. this.translation.x = offsetX;
  21087. }
  21088. if (offsetY !== undefined) {
  21089. this.translation.y = offsetY;
  21090. }
  21091. this.emit('viewChanged');
  21092. };
  21093. /**
  21094. * Get the translation of the network
  21095. * @return {Object} translation An object with parameters x and y, both a number
  21096. * @private
  21097. */
  21098. Network.prototype._getTranslation = function() {
  21099. return {
  21100. x: this.translation.x,
  21101. y: this.translation.y
  21102. };
  21103. };
  21104. /**
  21105. * Scale the network
  21106. * @param {Number} scale Scaling factor 1.0 is unscaled
  21107. * @private
  21108. */
  21109. Network.prototype._setScale = function(scale) {
  21110. this.scale = scale;
  21111. };
  21112. /**
  21113. * Get the current scale of the network
  21114. * @return {Number} scale Scaling factor 1.0 is unscaled
  21115. * @private
  21116. */
  21117. Network.prototype._getScale = function() {
  21118. return this.scale;
  21119. };
  21120. /**
  21121. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  21122. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  21123. * @param {number} x
  21124. * @returns {number}
  21125. * @private
  21126. */
  21127. Network.prototype._XconvertDOMtoCanvas = function(x) {
  21128. return (x - this.translation.x) / this.scale;
  21129. };
  21130. /**
  21131. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  21132. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  21133. * @param {number} x
  21134. * @returns {number}
  21135. * @private
  21136. */
  21137. Network.prototype._XconvertCanvasToDOM = function(x) {
  21138. return x * this.scale + this.translation.x;
  21139. };
  21140. /**
  21141. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  21142. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  21143. * @param {number} y
  21144. * @returns {number}
  21145. * @private
  21146. */
  21147. Network.prototype._YconvertDOMtoCanvas = function(y) {
  21148. return (y - this.translation.y) / this.scale;
  21149. };
  21150. /**
  21151. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  21152. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  21153. * @param {number} y
  21154. * @returns {number}
  21155. * @private
  21156. */
  21157. Network.prototype._YconvertCanvasToDOM = function(y) {
  21158. return y * this.scale + this.translation.y ;
  21159. };
  21160. /**
  21161. *
  21162. * @param {object} pos = {x: number, y: number}
  21163. * @returns {{x: number, y: number}}
  21164. * @constructor
  21165. */
  21166. Network.prototype.canvasToDOM = function (pos) {
  21167. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  21168. };
  21169. /**
  21170. *
  21171. * @param {object} pos = {x: number, y: number}
  21172. * @returns {{x: number, y: number}}
  21173. * @constructor
  21174. */
  21175. Network.prototype.DOMtoCanvas = function (pos) {
  21176. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  21177. };
  21178. /**
  21179. * Redraw all nodes
  21180. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  21181. * @param {CanvasRenderingContext2D} ctx
  21182. * @param {Boolean} [alwaysShow]
  21183. * @private
  21184. */
  21185. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  21186. if (alwaysShow === undefined) {
  21187. alwaysShow = false;
  21188. }
  21189. // first draw the unselected nodes
  21190. var nodes = this.nodes;
  21191. var selected = [];
  21192. for (var id in nodes) {
  21193. if (nodes.hasOwnProperty(id)) {
  21194. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  21195. if (nodes[id].isSelected()) {
  21196. selected.push(id);
  21197. }
  21198. else {
  21199. if (nodes[id].inArea() || alwaysShow) {
  21200. nodes[id].draw(ctx);
  21201. }
  21202. }
  21203. }
  21204. }
  21205. // draw the selected nodes on top
  21206. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  21207. if (nodes[selected[s]].inArea() || alwaysShow) {
  21208. nodes[selected[s]].draw(ctx);
  21209. }
  21210. }
  21211. };
  21212. /**
  21213. * Redraw all edges
  21214. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  21215. * @param {CanvasRenderingContext2D} ctx
  21216. * @private
  21217. */
  21218. Network.prototype._drawEdges = function(ctx) {
  21219. var edges = this.edges;
  21220. for (var id in edges) {
  21221. if (edges.hasOwnProperty(id)) {
  21222. var edge = edges[id];
  21223. edge.setScale(this.scale);
  21224. if (edge.connected) {
  21225. edges[id].draw(ctx);
  21226. }
  21227. }
  21228. }
  21229. };
  21230. /**
  21231. * Redraw all edges
  21232. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  21233. * @param {CanvasRenderingContext2D} ctx
  21234. * @private
  21235. */
  21236. Network.prototype._drawControlNodes = function(ctx) {
  21237. var edges = this.edges;
  21238. for (var id in edges) {
  21239. if (edges.hasOwnProperty(id)) {
  21240. edges[id]._drawControlNodes(ctx);
  21241. }
  21242. }
  21243. };
  21244. /**
  21245. * Find a stable position for all nodes
  21246. * @private
  21247. */
  21248. Network.prototype._stabilize = function() {
  21249. if (this.constants.freezeForStabilization == true) {
  21250. this._freezeDefinedNodes();
  21251. }
  21252. // find stable position
  21253. var count = 0;
  21254. while (this.moving && count < this.constants.stabilizationIterations) {
  21255. this._physicsTick();
  21256. count++;
  21257. }
  21258. if (this.constants.zoomExtentOnStabilize == true) {
  21259. this.zoomExtent(undefined, false, true);
  21260. }
  21261. if (this.constants.freezeForStabilization == true) {
  21262. this._restoreFrozenNodes();
  21263. }
  21264. };
  21265. /**
  21266. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  21267. * because only the supportnodes for the smoothCurves have to settle.
  21268. *
  21269. * @private
  21270. */
  21271. Network.prototype._freezeDefinedNodes = function() {
  21272. var nodes = this.nodes;
  21273. for (var id in nodes) {
  21274. if (nodes.hasOwnProperty(id)) {
  21275. if (nodes[id].x != null && nodes[id].y != null) {
  21276. nodes[id].fixedData.x = nodes[id].xFixed;
  21277. nodes[id].fixedData.y = nodes[id].yFixed;
  21278. nodes[id].xFixed = true;
  21279. nodes[id].yFixed = true;
  21280. }
  21281. }
  21282. }
  21283. };
  21284. /**
  21285. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  21286. *
  21287. * @private
  21288. */
  21289. Network.prototype._restoreFrozenNodes = function() {
  21290. var nodes = this.nodes;
  21291. for (var id in nodes) {
  21292. if (nodes.hasOwnProperty(id)) {
  21293. if (nodes[id].fixedData.x != null) {
  21294. nodes[id].xFixed = nodes[id].fixedData.x;
  21295. nodes[id].yFixed = nodes[id].fixedData.y;
  21296. }
  21297. }
  21298. }
  21299. };
  21300. /**
  21301. * Check if any of the nodes is still moving
  21302. * @param {number} vmin the minimum velocity considered as 'moving'
  21303. * @return {boolean} true if moving, false if non of the nodes is moving
  21304. * @private
  21305. */
  21306. Network.prototype._isMoving = function(vmin) {
  21307. var nodes = this.nodes;
  21308. for (var id in nodes) {
  21309. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  21310. return true;
  21311. }
  21312. }
  21313. return false;
  21314. };
  21315. /**
  21316. * /**
  21317. * Perform one discrete step for all nodes
  21318. *
  21319. * @private
  21320. */
  21321. Network.prototype._discreteStepNodes = function() {
  21322. var interval = this.physicsDiscreteStepsize;
  21323. var nodes = this.nodes;
  21324. var nodeId;
  21325. var nodesPresent = false;
  21326. if (this.constants.maxVelocity > 0) {
  21327. for (nodeId in nodes) {
  21328. if (nodes.hasOwnProperty(nodeId)) {
  21329. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  21330. nodesPresent = true;
  21331. }
  21332. }
  21333. }
  21334. else {
  21335. for (nodeId in nodes) {
  21336. if (nodes.hasOwnProperty(nodeId)) {
  21337. nodes[nodeId].discreteStep(interval);
  21338. nodesPresent = true;
  21339. }
  21340. }
  21341. }
  21342. if (nodesPresent == true) {
  21343. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  21344. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  21345. return true;
  21346. }
  21347. else {
  21348. return this._isMoving(vminCorrected);
  21349. }
  21350. }
  21351. return false;
  21352. };
  21353. /**
  21354. * A single simulation step (or "tick") in the physics simulation
  21355. *
  21356. * @private
  21357. */
  21358. Network.prototype._physicsTick = function() {
  21359. if (!this.freezeSimulation) {
  21360. if (this.moving == true) {
  21361. var mainMovingStatus = false;
  21362. var supportMovingStatus = false;
  21363. this._doInAllActiveSectors("_initializeForceCalculation");
  21364. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  21365. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  21366. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  21367. }
  21368. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  21369. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  21370. // determine if the network has stabilzied
  21371. this.moving = mainMovingStatus || supportMovingStatus;
  21372. this.stabilizationIterations++;
  21373. }
  21374. }
  21375. };
  21376. /**
  21377. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  21378. * It reschedules itself at the beginning of the function
  21379. *
  21380. * @private
  21381. */
  21382. Network.prototype._animationStep = function() {
  21383. // reset the timer so a new scheduled animation step can be set
  21384. this.timer = undefined;
  21385. // handle the keyboad movement
  21386. this._handleNavigation();
  21387. // this schedules a new animation step
  21388. this.start();
  21389. // start the physics simulation
  21390. var calculationTime = Date.now();
  21391. var maxSteps = 1;
  21392. this._physicsTick();
  21393. var timeRequired = Date.now() - calculationTime;
  21394. while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  21395. this._physicsTick();
  21396. timeRequired = Date.now() - calculationTime;
  21397. maxSteps++;
  21398. }
  21399. // start the rendering process
  21400. var renderTime = Date.now();
  21401. this._redraw();
  21402. this.renderTime = Date.now() - renderTime;
  21403. };
  21404. if (typeof window !== 'undefined') {
  21405. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  21406. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  21407. }
  21408. /**
  21409. * Schedule a animation step with the refreshrate interval.
  21410. */
  21411. Network.prototype.start = function() {
  21412. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  21413. if (this.startedStabilization == false) {
  21414. this.emit("startStabilization");
  21415. this.startedStabilization = true;
  21416. }
  21417. if (!this.timer) {
  21418. var ua = navigator.userAgent.toLowerCase();
  21419. var requiresTimeout = false;
  21420. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  21421. requiresTimeout = true;
  21422. }
  21423. else if (ua.indexOf('safari') != -1) { // safari
  21424. if (ua.indexOf('chrome') <= -1) {
  21425. requiresTimeout = true;
  21426. }
  21427. }
  21428. if (requiresTimeout == true) {
  21429. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  21430. }
  21431. else{
  21432. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  21433. }
  21434. }
  21435. }
  21436. else {
  21437. this._redraw();
  21438. if (this.stabilizationIterations > 0) {
  21439. // trigger the "stabilized" event.
  21440. // The event is triggered on the next tick, to prevent the case that
  21441. // it is fired while initializing the Network, in which case you would not
  21442. // be able to catch it
  21443. var me = this;
  21444. var params = {
  21445. iterations: me.stabilizationIterations
  21446. };
  21447. me.stabilizationIterations = 0;
  21448. me.startedStabilization = false;
  21449. setTimeout(function () {
  21450. me.emit("stabilized", params);
  21451. }, 0);
  21452. }
  21453. }
  21454. };
  21455. /**
  21456. * Move the network according to the keyboard presses.
  21457. *
  21458. * @private
  21459. */
  21460. Network.prototype._handleNavigation = function() {
  21461. if (this.xIncrement != 0 || this.yIncrement != 0) {
  21462. var translation = this._getTranslation();
  21463. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  21464. }
  21465. if (this.zoomIncrement != 0) {
  21466. var center = {
  21467. x: this.frame.canvas.clientWidth / 2,
  21468. y: this.frame.canvas.clientHeight / 2
  21469. };
  21470. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  21471. }
  21472. };
  21473. /**
  21474. * Freeze the _animationStep
  21475. */
  21476. Network.prototype.toggleFreeze = function() {
  21477. if (this.freezeSimulation == false) {
  21478. this.freezeSimulation = true;
  21479. }
  21480. else {
  21481. this.freezeSimulation = false;
  21482. this.start();
  21483. }
  21484. };
  21485. /**
  21486. * This function cleans the support nodes if they are not needed and adds them when they are.
  21487. *
  21488. * @param {boolean} [disableStart]
  21489. * @private
  21490. */
  21491. Network.prototype._configureSmoothCurves = function(disableStart) {
  21492. if (disableStart === undefined) {
  21493. disableStart = true;
  21494. }
  21495. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  21496. this._createBezierNodes();
  21497. // cleanup unused support nodes
  21498. for (var nodeId in this.sectors['support']['nodes']) {
  21499. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  21500. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  21501. delete this.sectors['support']['nodes'][nodeId];
  21502. }
  21503. }
  21504. }
  21505. }
  21506. else {
  21507. // delete the support nodes
  21508. this.sectors['support']['nodes'] = {};
  21509. for (var edgeId in this.edges) {
  21510. if (this.edges.hasOwnProperty(edgeId)) {
  21511. this.edges[edgeId].via = null;
  21512. }
  21513. }
  21514. }
  21515. this._updateCalculationNodes();
  21516. if (!disableStart) {
  21517. this.moving = true;
  21518. this.start();
  21519. }
  21520. };
  21521. /**
  21522. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  21523. * are used for the force calculation.
  21524. *
  21525. * @private
  21526. */
  21527. Network.prototype._createBezierNodes = function() {
  21528. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  21529. for (var edgeId in this.edges) {
  21530. if (this.edges.hasOwnProperty(edgeId)) {
  21531. var edge = this.edges[edgeId];
  21532. if (edge.via == null) {
  21533. var nodeId = "edgeId:".concat(edge.id);
  21534. this.sectors['support']['nodes'][nodeId] = new Node(
  21535. {id:nodeId,
  21536. mass:1,
  21537. shape:'circle',
  21538. image:"",
  21539. internalMultiplier:1
  21540. },{},{},this.constants);
  21541. edge.via = this.sectors['support']['nodes'][nodeId];
  21542. edge.via.parentEdgeId = edge.id;
  21543. edge.positionBezierNode();
  21544. }
  21545. }
  21546. }
  21547. }
  21548. };
  21549. /**
  21550. * load the functions that load the mixins into the prototype.
  21551. *
  21552. * @private
  21553. */
  21554. Network.prototype._initializeMixinLoaders = function () {
  21555. for (var mixin in MixinLoader) {
  21556. if (MixinLoader.hasOwnProperty(mixin)) {
  21557. Network.prototype[mixin] = MixinLoader[mixin];
  21558. }
  21559. }
  21560. };
  21561. /**
  21562. * Load the XY positions of the nodes into the dataset.
  21563. */
  21564. Network.prototype.storePosition = function() {
  21565. console.log("storePosition is depricated: use .storePositions() from now on.")
  21566. this.storePositions();
  21567. };
  21568. /**
  21569. * Load the XY positions of the nodes into the dataset.
  21570. */
  21571. Network.prototype.storePositions = function() {
  21572. var dataArray = [];
  21573. for (var nodeId in this.nodes) {
  21574. if (this.nodes.hasOwnProperty(nodeId)) {
  21575. var node = this.nodes[nodeId];
  21576. var allowedToMoveX = !this.nodes.xFixed;
  21577. var allowedToMoveY = !this.nodes.yFixed;
  21578. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  21579. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  21580. }
  21581. }
  21582. }
  21583. this.nodesData.update(dataArray);
  21584. };
  21585. /**
  21586. * Return the positions of the nodes.
  21587. */
  21588. Network.prototype.getPositions = function(ids) {
  21589. var dataArray = {};
  21590. if (ids !== undefined) {
  21591. if (Array.isArray(ids) == true) {
  21592. for (var i = 0; i < ids.length; i++) {
  21593. if (this.nodes[ids[i]] !== undefined) {
  21594. var node = this.nodes[ids[i]];
  21595. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  21596. }
  21597. }
  21598. }
  21599. else {
  21600. if (this.nodes[ids] !== undefined) {
  21601. var node = this.nodes[ids];
  21602. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  21603. }
  21604. }
  21605. }
  21606. else {
  21607. for (var nodeId in this.nodes) {
  21608. if (this.nodes.hasOwnProperty(nodeId)) {
  21609. var node = this.nodes[nodeId];
  21610. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  21611. }
  21612. }
  21613. }
  21614. return dataArray;
  21615. };
  21616. /**
  21617. * Center a node in view.
  21618. *
  21619. * @param {Number} nodeId
  21620. * @param {Number} [options]
  21621. */
  21622. Network.prototype.focusOnNode = function (nodeId, options) {
  21623. if (this.nodes.hasOwnProperty(nodeId)) {
  21624. if (options === undefined) {
  21625. options = {};
  21626. }
  21627. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  21628. options.position = nodePosition;
  21629. options.lockedOnNode = nodeId;
  21630. this.moveTo(options)
  21631. }
  21632. else {
  21633. console.log("This nodeId cannot be found.");
  21634. }
  21635. };
  21636. /**
  21637. *
  21638. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  21639. * | options.scale = Number // scale to move to
  21640. * | options.position = {x:Number, y:Number} // position to move to
  21641. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  21642. */
  21643. Network.prototype.moveTo = function (options) {
  21644. if (options === undefined) {
  21645. options = {};
  21646. return;
  21647. }
  21648. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  21649. if (options.offset.x === undefined) {options.offset.x = 0; }
  21650. if (options.offset.y === undefined) {options.offset.y = 0; }
  21651. if (options.scale === undefined) {options.scale = this._getScale(); }
  21652. if (options.position === undefined) {options.position = this._getTranslation();}
  21653. if (options.animation === undefined) {options.animation = {duration:0}; }
  21654. if (options.animation === false ) {options.animation = {duration:0}; }
  21655. if (options.animation === true ) {options.animation = {}; }
  21656. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  21657. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  21658. this.animateView(options);
  21659. };
  21660. /**
  21661. *
  21662. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  21663. * | options.time = Number // animation time in milliseconds
  21664. * | options.scale = Number // scale to animate to
  21665. * | options.position = {x:Number, y:Number} // position to animate to
  21666. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  21667. * // easeInCubic, easeOutCubic, easeInOutCubic,
  21668. * // easeInQuart, easeOutQuart, easeInOutQuart,
  21669. * // easeInQuint, easeOutQuint, easeInOutQuint
  21670. */
  21671. Network.prototype.animateView = function (options) {
  21672. if (options === undefined) {
  21673. options = {};
  21674. return;
  21675. }
  21676. // release if something focussed on the node
  21677. this.releaseNode();
  21678. if (options.locked == true) {
  21679. this.lockedOnNodeId = options.lockedOnNode;
  21680. this.lockedOnNodeOffset = options.offset;
  21681. }
  21682. // forcefully complete the old animation if it was still running
  21683. if (this.easingTime != 0) {
  21684. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  21685. }
  21686. this.sourceScale = this._getScale();
  21687. this.sourceTranslation = this._getTranslation();
  21688. this.targetScale = options.scale;
  21689. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  21690. // but at least then we'll have the target transition
  21691. this._setScale(this.targetScale);
  21692. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  21693. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  21694. x: viewCenter.x - options.position.x,
  21695. y: viewCenter.y - options.position.y
  21696. };
  21697. this.targetTranslation = {
  21698. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  21699. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  21700. };
  21701. // if the time is set to 0, don't do an animation
  21702. if (options.animation.duration == 0) {
  21703. if (this.lockedOnNodeId != null) {
  21704. this._classicRedraw = this._redraw;
  21705. this._redraw = this._lockedRedraw;
  21706. }
  21707. else {
  21708. this._setScale(this.targetScale);
  21709. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  21710. this._redraw();
  21711. }
  21712. }
  21713. else {
  21714. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  21715. this.animationEasingFunction = options.animation.easingFunction;
  21716. this._classicRedraw = this._redraw;
  21717. this._redraw = this._transitionRedraw;
  21718. this._redraw();
  21719. this.moving = true;
  21720. this.start();
  21721. }
  21722. };
  21723. Network.prototype._lockedRedraw = function () {
  21724. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  21725. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  21726. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  21727. x: viewCenter.x - nodePosition.x,
  21728. y: viewCenter.y - nodePosition.y
  21729. };
  21730. var sourceTranslation = this._getTranslation();
  21731. var targetTranslation = {
  21732. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  21733. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  21734. };
  21735. this._setTranslation(targetTranslation.x,targetTranslation.y);
  21736. this._classicRedraw();
  21737. }
  21738. Network.prototype.releaseNode = function () {
  21739. if (this.lockedOnNodeId != null) {
  21740. this._redraw = this._classicRedraw;
  21741. this.lockedOnNodeId = null;
  21742. this.lockedOnNodeOffset = null;
  21743. }
  21744. }
  21745. /**
  21746. *
  21747. * @param easingTime
  21748. * @private
  21749. */
  21750. Network.prototype._transitionRedraw = function (easingTime) {
  21751. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  21752. this.easingTime += this.animationSpeed;
  21753. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  21754. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  21755. this._setTranslation(
  21756. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  21757. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  21758. );
  21759. this._classicRedraw();
  21760. this.moving = true;
  21761. // cleanup
  21762. if (this.easingTime >= 1.0) {
  21763. this.easingTime = 0;
  21764. if (this.lockedOnNodeId != null) {
  21765. this._redraw = this._lockedRedraw;
  21766. }
  21767. else {
  21768. this._redraw = this._classicRedraw;
  21769. }
  21770. this.emit("animationFinished");
  21771. }
  21772. };
  21773. Network.prototype._classicRedraw = function () {
  21774. // placeholder function to be overloaded by animations;
  21775. };
  21776. /**
  21777. * Returns true when the Network is active.
  21778. * @returns {boolean}
  21779. */
  21780. Network.prototype.isActive = function () {
  21781. return !this.activator || this.activator.active;
  21782. };
  21783. /**
  21784. * Sets the scale
  21785. * @returns {Number}
  21786. */
  21787. Network.prototype.setScale = function () {
  21788. return this._setScale();
  21789. };
  21790. /**
  21791. * Returns the scale
  21792. * @returns {Number}
  21793. */
  21794. Network.prototype.getScale = function () {
  21795. return this._getScale();
  21796. };
  21797. /**
  21798. * Returns the scale
  21799. * @returns {Number}
  21800. */
  21801. Network.prototype.getCenterCoordinates = function () {
  21802. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  21803. };
  21804. module.exports = Network;
  21805. /***/ },
  21806. /* 52 */
  21807. /***/ function(module, exports, __webpack_require__) {
  21808. var util = __webpack_require__(1);
  21809. var Node = __webpack_require__(53);
  21810. /**
  21811. * @class Edge
  21812. *
  21813. * A edge connects two nodes
  21814. * @param {Object} properties Object with properties. Must contain
  21815. * At least properties from and to.
  21816. * Available properties: from (number),
  21817. * to (number), label (string, color (string),
  21818. * width (number), style (string),
  21819. * length (number), title (string)
  21820. * @param {Network} network A Network object, used to find and edge to
  21821. * nodes.
  21822. * @param {Object} constants An object with default values for
  21823. * example for the color
  21824. */
  21825. function Edge (properties, network, networkConstants) {
  21826. if (!network) {
  21827. throw "No network provided";
  21828. }
  21829. var fields = ['edges','physics'];
  21830. var constants = util.selectiveBridgeObject(fields,networkConstants);
  21831. this.options = constants.edges;
  21832. this.physics = constants.physics;
  21833. this.options['smoothCurves'] = networkConstants['smoothCurves'];
  21834. this.network = network;
  21835. // initialize variables
  21836. this.id = undefined;
  21837. this.fromId = undefined;
  21838. this.toId = undefined;
  21839. this.title = undefined;
  21840. this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
  21841. this.value = undefined;
  21842. this.selected = false;
  21843. this.hover = false;
  21844. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  21845. this.dirtyLabel = true;
  21846. this.from = null; // a node
  21847. this.to = null; // a node
  21848. this.via = null; // a temp node
  21849. this.fromBackup = null; // used to clean up after reconnect
  21850. this.toBackup = null;; // used to clean up after reconnect
  21851. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  21852. // by storing the original information we can revert to the original connection when the cluser is opened.
  21853. this.originalFromId = [];
  21854. this.originalToId = [];
  21855. this.connected = false;
  21856. this.widthFixed = false;
  21857. this.lengthFixed = false;
  21858. this.setProperties(properties);
  21859. this.controlNodesEnabled = false;
  21860. this.controlNodes = {from:null, to:null, positions:{}};
  21861. this.connectedNode = null;
  21862. }
  21863. /**
  21864. * Set or overwrite properties for the edge
  21865. * @param {Object} properties an object with properties
  21866. * @param {Object} constants and object with default, global properties
  21867. */
  21868. Edge.prototype.setProperties = function(properties) {
  21869. if (!properties) {
  21870. return;
  21871. }
  21872. var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
  21873. 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor'
  21874. ];
  21875. util.selectiveDeepExtend(fields, this.options, properties);
  21876. if (properties.from !== undefined) {this.fromId = properties.from;}
  21877. if (properties.to !== undefined) {this.toId = properties.to;}
  21878. if (properties.id !== undefined) {this.id = properties.id;}
  21879. if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
  21880. if (properties.title !== undefined) {this.title = properties.title;}
  21881. if (properties.value !== undefined) {this.value = properties.value;}
  21882. if (properties.length !== undefined) {this.physics.springLength = properties.length;}
  21883. if (properties.color !== undefined) {
  21884. this.options.inheritColor = false;
  21885. if (util.isString(properties.color)) {
  21886. this.options.color.color = properties.color;
  21887. this.options.color.highlight = properties.color;
  21888. }
  21889. else {
  21890. if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
  21891. if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
  21892. if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
  21893. }
  21894. }
  21895. // A node is connected when it has a from and to node.
  21896. this.connect();
  21897. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  21898. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  21899. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  21900. // set draw method based on style
  21901. switch (this.options.style) {
  21902. case 'line': this.draw = this._drawLine; break;
  21903. case 'arrow': this.draw = this._drawArrow; break;
  21904. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  21905. case 'dash-line': this.draw = this._drawDashLine; break;
  21906. default: this.draw = this._drawLine; break;
  21907. }
  21908. };
  21909. /**
  21910. * Connect an edge to its nodes
  21911. */
  21912. Edge.prototype.connect = function () {
  21913. this.disconnect();
  21914. this.from = this.network.nodes[this.fromId] || null;
  21915. this.to = this.network.nodes[this.toId] || null;
  21916. this.connected = (this.from && this.to);
  21917. if (this.connected) {
  21918. this.from.attachEdge(this);
  21919. this.to.attachEdge(this);
  21920. }
  21921. else {
  21922. if (this.from) {
  21923. this.from.detachEdge(this);
  21924. }
  21925. if (this.to) {
  21926. this.to.detachEdge(this);
  21927. }
  21928. }
  21929. };
  21930. /**
  21931. * Disconnect an edge from its nodes
  21932. */
  21933. Edge.prototype.disconnect = function () {
  21934. if (this.from) {
  21935. this.from.detachEdge(this);
  21936. this.from = null;
  21937. }
  21938. if (this.to) {
  21939. this.to.detachEdge(this);
  21940. this.to = null;
  21941. }
  21942. this.connected = false;
  21943. };
  21944. /**
  21945. * get the title of this edge.
  21946. * @return {string} title The title of the edge, or undefined when no title
  21947. * has been set.
  21948. */
  21949. Edge.prototype.getTitle = function() {
  21950. return typeof this.title === "function" ? this.title() : this.title;
  21951. };
  21952. /**
  21953. * Retrieve the value of the edge. Can be undefined
  21954. * @return {Number} value
  21955. */
  21956. Edge.prototype.getValue = function() {
  21957. return this.value;
  21958. };
  21959. /**
  21960. * Adjust the value range of the edge. The edge will adjust it's width
  21961. * based on its value.
  21962. * @param {Number} min
  21963. * @param {Number} max
  21964. */
  21965. Edge.prototype.setValueRange = function(min, max) {
  21966. if (!this.widthFixed && this.value !== undefined) {
  21967. var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
  21968. this.options.width= (this.value - min) * scale + this.options.widthMin;
  21969. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  21970. }
  21971. };
  21972. /**
  21973. * Redraw a edge
  21974. * Draw this edge in the given canvas
  21975. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  21976. * @param {CanvasRenderingContext2D} ctx
  21977. */
  21978. Edge.prototype.draw = function(ctx) {
  21979. throw "Method draw not initialized in edge";
  21980. };
  21981. /**
  21982. * Check if this object is overlapping with the provided object
  21983. * @param {Object} obj an object with parameters left, top
  21984. * @return {boolean} True if location is located on the edge
  21985. */
  21986. Edge.prototype.isOverlappingWith = function(obj) {
  21987. if (this.connected) {
  21988. var distMax = 10;
  21989. var xFrom = this.from.x;
  21990. var yFrom = this.from.y;
  21991. var xTo = this.to.x;
  21992. var yTo = this.to.y;
  21993. var xObj = obj.left;
  21994. var yObj = obj.top;
  21995. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  21996. return (dist < distMax);
  21997. }
  21998. else {
  21999. return false
  22000. }
  22001. };
  22002. Edge.prototype._getColor = function() {
  22003. var colorObj = this.options.color;
  22004. if (this.options.inheritColor == "to") {
  22005. colorObj = {
  22006. highlight: this.to.options.color.highlight.border,
  22007. hover: this.to.options.color.hover.border,
  22008. color: this.to.options.color.border
  22009. };
  22010. }
  22011. else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
  22012. colorObj = {
  22013. highlight: this.from.options.color.highlight.border,
  22014. hover: this.from.options.color.hover.border,
  22015. color: this.from.options.color.border
  22016. };
  22017. }
  22018. if (this.selected == true) {return colorObj.highlight;}
  22019. else if (this.hover == true) {return colorObj.hover;}
  22020. else {return colorObj.color;}
  22021. };
  22022. /**
  22023. * Redraw a edge as a line
  22024. * Draw this edge in the given canvas
  22025. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  22026. * @param {CanvasRenderingContext2D} ctx
  22027. * @private
  22028. */
  22029. Edge.prototype._drawLine = function(ctx) {
  22030. // set style
  22031. ctx.strokeStyle = this._getColor();
  22032. ctx.lineWidth = this._getLineWidth();
  22033. if (this.from != this.to) {
  22034. // draw line
  22035. var via = this._line(ctx);
  22036. // draw label
  22037. var point;
  22038. if (this.label) {
  22039. if (this.options.smoothCurves.enabled == true && via != null) {
  22040. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  22041. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  22042. point = {x:midpointX, y:midpointY};
  22043. }
  22044. else {
  22045. point = this._pointOnLine(0.5);
  22046. }
  22047. this._label(ctx, this.label, point.x, point.y);
  22048. }
  22049. }
  22050. else {
  22051. var x, y;
  22052. var radius = this.physics.springLength / 4;
  22053. var node = this.from;
  22054. if (!node.width) {
  22055. node.resize(ctx);
  22056. }
  22057. if (node.width > node.height) {
  22058. x = node.x + node.width / 2;
  22059. y = node.y - radius;
  22060. }
  22061. else {
  22062. x = node.x + radius;
  22063. y = node.y - node.height / 2;
  22064. }
  22065. this._circle(ctx, x, y, radius);
  22066. point = this._pointOnCircle(x, y, radius, 0.5);
  22067. this._label(ctx, this.label, point.x, point.y);
  22068. }
  22069. };
  22070. /**
  22071. * Get the line width of the edge. Depends on width and whether one of the
  22072. * connected nodes is selected.
  22073. * @return {Number} width
  22074. * @private
  22075. */
  22076. Edge.prototype._getLineWidth = function() {
  22077. if (this.selected == true) {
  22078. return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
  22079. }
  22080. else {
  22081. if (this.hover == true) {
  22082. return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
  22083. }
  22084. else {
  22085. return Math.max(this.options.width, 0.3*this.networkScaleInv);
  22086. }
  22087. }
  22088. };
  22089. Edge.prototype._getViaCoordinates = function () {
  22090. var xVia = null;
  22091. var yVia = null;
  22092. var factor = this.options.smoothCurves.roundness;
  22093. var type = this.options.smoothCurves.type;
  22094. var dx = Math.abs(this.from.x - this.to.x);
  22095. var dy = Math.abs(this.from.y - this.to.y);
  22096. if (type == 'discrete' || type == 'diagonalCross') {
  22097. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  22098. if (this.from.y > this.to.y) {
  22099. if (this.from.x < this.to.x) {
  22100. xVia = this.from.x + factor * dy;
  22101. yVia = this.from.y - factor * dy;
  22102. }
  22103. else if (this.from.x > this.to.x) {
  22104. xVia = this.from.x - factor * dy;
  22105. yVia = this.from.y - factor * dy;
  22106. }
  22107. }
  22108. else if (this.from.y < this.to.y) {
  22109. if (this.from.x < this.to.x) {
  22110. xVia = this.from.x + factor * dy;
  22111. yVia = this.from.y + factor * dy;
  22112. }
  22113. else if (this.from.x > this.to.x) {
  22114. xVia = this.from.x - factor * dy;
  22115. yVia = this.from.y + factor * dy;
  22116. }
  22117. }
  22118. if (type == "discrete") {
  22119. xVia = dx < factor * dy ? this.from.x : xVia;
  22120. }
  22121. }
  22122. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  22123. if (this.from.y > this.to.y) {
  22124. if (this.from.x < this.to.x) {
  22125. xVia = this.from.x + factor * dx;
  22126. yVia = this.from.y - factor * dx;
  22127. }
  22128. else if (this.from.x > this.to.x) {
  22129. xVia = this.from.x - factor * dx;
  22130. yVia = this.from.y - factor * dx;
  22131. }
  22132. }
  22133. else if (this.from.y < this.to.y) {
  22134. if (this.from.x < this.to.x) {
  22135. xVia = this.from.x + factor * dx;
  22136. yVia = this.from.y + factor * dx;
  22137. }
  22138. else if (this.from.x > this.to.x) {
  22139. xVia = this.from.x - factor * dx;
  22140. yVia = this.from.y + factor * dx;
  22141. }
  22142. }
  22143. if (type == "discrete") {
  22144. yVia = dy < factor * dx ? this.from.y : yVia;
  22145. }
  22146. }
  22147. }
  22148. else if (type == "straightCross") {
  22149. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
  22150. xVia = this.from.x;
  22151. if (this.from.y < this.to.y) {
  22152. yVia = this.to.y - (1-factor) * dy;
  22153. }
  22154. else {
  22155. yVia = this.to.y + (1-factor) * dy;
  22156. }
  22157. }
  22158. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
  22159. if (this.from.x < this.to.x) {
  22160. xVia = this.to.x - (1-factor) * dx;
  22161. }
  22162. else {
  22163. xVia = this.to.x + (1-factor) * dx;
  22164. }
  22165. yVia = this.from.y;
  22166. }
  22167. }
  22168. else if (type == 'horizontal') {
  22169. if (this.from.x < this.to.x) {
  22170. xVia = this.to.x - (1-factor) * dx;
  22171. }
  22172. else {
  22173. xVia = this.to.x + (1-factor) * dx;
  22174. }
  22175. yVia = this.from.y;
  22176. }
  22177. else if (type == 'vertical') {
  22178. xVia = this.from.x;
  22179. if (this.from.y < this.to.y) {
  22180. yVia = this.to.y - (1-factor) * dy;
  22181. }
  22182. else {
  22183. yVia = this.to.y + (1-factor) * dy;
  22184. }
  22185. }
  22186. else { // continuous
  22187. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  22188. if (this.from.y > this.to.y) {
  22189. if (this.from.x < this.to.x) {
  22190. // console.log(1)
  22191. xVia = this.from.x + factor * dy;
  22192. yVia = this.from.y - factor * dy;
  22193. xVia = this.to.x < xVia ? this.to.x : xVia;
  22194. }
  22195. else if (this.from.x > this.to.x) {
  22196. // console.log(2)
  22197. xVia = this.from.x - factor * dy;
  22198. yVia = this.from.y - factor * dy;
  22199. xVia = this.to.x > xVia ? this.to.x :xVia;
  22200. }
  22201. }
  22202. else if (this.from.y < this.to.y) {
  22203. if (this.from.x < this.to.x) {
  22204. // console.log(3)
  22205. xVia = this.from.x + factor * dy;
  22206. yVia = this.from.y + factor * dy;
  22207. xVia = this.to.x < xVia ? this.to.x : xVia;
  22208. }
  22209. else if (this.from.x > this.to.x) {
  22210. // console.log(4, this.from.x, this.to.x)
  22211. xVia = this.from.x - factor * dy;
  22212. yVia = this.from.y + factor * dy;
  22213. xVia = this.to.x > xVia ? this.to.x : xVia;
  22214. }
  22215. }
  22216. }
  22217. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  22218. if (this.from.y > this.to.y) {
  22219. if (this.from.x < this.to.x) {
  22220. // console.log(5)
  22221. xVia = this.from.x + factor * dx;
  22222. yVia = this.from.y - factor * dx;
  22223. yVia = this.to.y > yVia ? this.to.y : yVia;
  22224. }
  22225. else if (this.from.x > this.to.x) {
  22226. // console.log(6)
  22227. xVia = this.from.x - factor * dx;
  22228. yVia = this.from.y - factor * dx;
  22229. yVia = this.to.y > yVia ? this.to.y : yVia;
  22230. }
  22231. }
  22232. else if (this.from.y < this.to.y) {
  22233. if (this.from.x < this.to.x) {
  22234. // console.log(7)
  22235. xVia = this.from.x + factor * dx;
  22236. yVia = this.from.y + factor * dx;
  22237. yVia = this.to.y < yVia ? this.to.y : yVia;
  22238. }
  22239. else if (this.from.x > this.to.x) {
  22240. // console.log(8)
  22241. xVia = this.from.x - factor * dx;
  22242. yVia = this.from.y + factor * dx;
  22243. yVia = this.to.y < yVia ? this.to.y : yVia;
  22244. }
  22245. }
  22246. }
  22247. }
  22248. return {x:xVia, y:yVia};
  22249. };
  22250. /**
  22251. * Draw a line between two nodes
  22252. * @param {CanvasRenderingContext2D} ctx
  22253. * @private
  22254. */
  22255. Edge.prototype._line = function (ctx) {
  22256. // draw a straight line
  22257. ctx.beginPath();
  22258. ctx.moveTo(this.from.x, this.from.y);
  22259. if (this.options.smoothCurves.enabled == true) {
  22260. if (this.options.smoothCurves.dynamic == false) {
  22261. var via = this._getViaCoordinates();
  22262. if (via.x == null) {
  22263. ctx.lineTo(this.to.x, this.to.y);
  22264. ctx.stroke();
  22265. return null;
  22266. }
  22267. else {
  22268. // this.via.x = via.x;
  22269. // this.via.y = via.y;
  22270. ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
  22271. ctx.stroke();
  22272. return via;
  22273. }
  22274. }
  22275. else {
  22276. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  22277. ctx.stroke();
  22278. return this.via;
  22279. }
  22280. }
  22281. else {
  22282. ctx.lineTo(this.to.x, this.to.y);
  22283. ctx.stroke();
  22284. return null;
  22285. }
  22286. };
  22287. /**
  22288. * Draw a line from a node to itself, a circle
  22289. * @param {CanvasRenderingContext2D} ctx
  22290. * @param {Number} x
  22291. * @param {Number} y
  22292. * @param {Number} radius
  22293. * @private
  22294. */
  22295. Edge.prototype._circle = function (ctx, x, y, radius) {
  22296. // draw a circle
  22297. ctx.beginPath();
  22298. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  22299. ctx.stroke();
  22300. };
  22301. /**
  22302. * Draw label with white background and with the middle at (x, y)
  22303. * @param {CanvasRenderingContext2D} ctx
  22304. * @param {String} text
  22305. * @param {Number} x
  22306. * @param {Number} y
  22307. * @private
  22308. */
  22309. Edge.prototype._label = function (ctx, text, x, y) {
  22310. if (text) {
  22311. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  22312. this.options.fontSize + "px " + this.options.fontFace;
  22313. var yLine;
  22314. if (this.dirtyLabel == true) {
  22315. var lines = String(text).split('\n');
  22316. var lineCount = lines.length;
  22317. var fontSize = (Number(this.options.fontSize) + 4);
  22318. yLine = y + (1 - lineCount) / 2 * fontSize;
  22319. var width = ctx.measureText(lines[0]).width;
  22320. for (var i = 1; i < lineCount; i++) {
  22321. var lineWidth = ctx.measureText(lines[i]).width;
  22322. width = lineWidth > width ? lineWidth : width;
  22323. }
  22324. var height = this.options.fontSize * lineCount;
  22325. var left = x - width / 2;
  22326. var top = y - height / 2;
  22327. // cache
  22328. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  22329. }
  22330. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  22331. ctx.fillStyle = this.options.fontFill;
  22332. ctx.fillRect(this.labelDimensions.left,
  22333. this.labelDimensions.top,
  22334. this.labelDimensions.width,
  22335. this.labelDimensions.height);
  22336. }
  22337. // draw text
  22338. ctx.fillStyle = this.options.fontColor || "black";
  22339. ctx.textAlign = "center";
  22340. ctx.textBaseline = "middle";
  22341. yLine = this.labelDimensions.yLine;
  22342. for (var i = 0; i < lineCount; i++) {
  22343. ctx.fillText(lines[i], x, yLine);
  22344. yLine += fontSize;
  22345. }
  22346. }
  22347. };
  22348. /**
  22349. * Redraw a edge as a dashed line
  22350. * Draw this edge in the given canvas
  22351. * @author David Jordan
  22352. * @date 2012-08-08
  22353. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  22354. * @param {CanvasRenderingContext2D} ctx
  22355. * @private
  22356. */
  22357. Edge.prototype._drawDashLine = function(ctx) {
  22358. // set style
  22359. ctx.strokeStyle = this._getColor();
  22360. ctx.lineWidth = this._getLineWidth();
  22361. var via = null;
  22362. // only firefox and chrome support this method, else we use the legacy one.
  22363. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  22364. // configure the dash pattern
  22365. var pattern = [0];
  22366. if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
  22367. pattern = [this.options.dash.length,this.options.dash.gap];
  22368. }
  22369. else {
  22370. pattern = [5,5];
  22371. }
  22372. // set dash settings for chrome or firefox
  22373. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  22374. ctx.setLineDash(pattern);
  22375. ctx.lineDashOffset = 0;
  22376. } else { //Firefox
  22377. ctx.mozDash = pattern;
  22378. ctx.mozDashOffset = 0;
  22379. }
  22380. // draw the line
  22381. via = this._line(ctx);
  22382. // restore the dash settings.
  22383. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  22384. ctx.setLineDash([0]);
  22385. ctx.lineDashOffset = 0;
  22386. } else { //Firefox
  22387. ctx.mozDash = [0];
  22388. ctx.mozDashOffset = 0;
  22389. }
  22390. }
  22391. else { // unsupporting smooth lines
  22392. // draw dashed line
  22393. ctx.beginPath();
  22394. ctx.lineCap = 'round';
  22395. if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  22396. {
  22397. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  22398. [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
  22399. }
  22400. 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
  22401. {
  22402. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  22403. [this.options.dash.length,this.options.dash.gap]);
  22404. }
  22405. else //If all else fails draw a line
  22406. {
  22407. ctx.moveTo(this.from.x, this.from.y);
  22408. ctx.lineTo(this.to.x, this.to.y);
  22409. }
  22410. ctx.stroke();
  22411. }
  22412. // draw label
  22413. if (this.label) {
  22414. var point;
  22415. if (this.options.smoothCurves.enabled == true && via != null) {
  22416. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  22417. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  22418. point = {x:midpointX, y:midpointY};
  22419. }
  22420. else {
  22421. point = this._pointOnLine(0.5);
  22422. }
  22423. this._label(ctx, this.label, point.x, point.y);
  22424. }
  22425. };
  22426. /**
  22427. * Get a point on a line
  22428. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  22429. * @return {Object} point
  22430. * @private
  22431. */
  22432. Edge.prototype._pointOnLine = function (percentage) {
  22433. return {
  22434. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  22435. y: (1 - percentage) * this.from.y + percentage * this.to.y
  22436. }
  22437. };
  22438. /**
  22439. * Get a point on a circle
  22440. * @param {Number} x
  22441. * @param {Number} y
  22442. * @param {Number} radius
  22443. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  22444. * @return {Object} point
  22445. * @private
  22446. */
  22447. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  22448. var angle = (percentage - 3/8) * 2 * Math.PI;
  22449. return {
  22450. x: x + radius * Math.cos(angle),
  22451. y: y - radius * Math.sin(angle)
  22452. }
  22453. };
  22454. /**
  22455. * Redraw a edge as a line with an arrow halfway the line
  22456. * Draw this edge in the given canvas
  22457. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  22458. * @param {CanvasRenderingContext2D} ctx
  22459. * @private
  22460. */
  22461. Edge.prototype._drawArrowCenter = function(ctx) {
  22462. var point;
  22463. // set style
  22464. ctx.strokeStyle = this._getColor();
  22465. ctx.fillStyle = ctx.strokeStyle;
  22466. ctx.lineWidth = this._getLineWidth();
  22467. if (this.from != this.to) {
  22468. // draw line
  22469. var via = this._line(ctx);
  22470. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  22471. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  22472. // draw an arrow halfway the line
  22473. if (this.options.smoothCurves.enabled == true && via != null) {
  22474. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  22475. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  22476. point = {x:midpointX, y:midpointY};
  22477. }
  22478. else {
  22479. point = this._pointOnLine(0.5);
  22480. }
  22481. ctx.arrow(point.x, point.y, angle, length);
  22482. ctx.fill();
  22483. ctx.stroke();
  22484. // draw label
  22485. if (this.label) {
  22486. this._label(ctx, this.label, point.x, point.y);
  22487. }
  22488. }
  22489. else {
  22490. // draw circle
  22491. var x, y;
  22492. var radius = 0.25 * Math.max(100,this.physics.springLength);
  22493. var node = this.from;
  22494. if (!node.width) {
  22495. node.resize(ctx);
  22496. }
  22497. if (node.width > node.height) {
  22498. x = node.x + node.width * 0.5;
  22499. y = node.y - radius;
  22500. }
  22501. else {
  22502. x = node.x + radius;
  22503. y = node.y - node.height * 0.5;
  22504. }
  22505. this._circle(ctx, x, y, radius);
  22506. // draw all arrows
  22507. var angle = 0.2 * Math.PI;
  22508. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  22509. point = this._pointOnCircle(x, y, radius, 0.5);
  22510. ctx.arrow(point.x, point.y, angle, length);
  22511. ctx.fill();
  22512. ctx.stroke();
  22513. // draw label
  22514. if (this.label) {
  22515. point = this._pointOnCircle(x, y, radius, 0.5);
  22516. this._label(ctx, this.label, point.x, point.y);
  22517. }
  22518. }
  22519. };
  22520. /**
  22521. * Redraw a edge as a line with an arrow
  22522. * Draw this edge in the given canvas
  22523. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  22524. * @param {CanvasRenderingContext2D} ctx
  22525. * @private
  22526. */
  22527. Edge.prototype._drawArrow = function(ctx) {
  22528. // set style
  22529. ctx.strokeStyle = this._getColor();
  22530. ctx.fillStyle = ctx.strokeStyle;
  22531. ctx.lineWidth = this._getLineWidth();
  22532. var angle, length;
  22533. //draw a line
  22534. if (this.from != this.to) {
  22535. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  22536. var dx = (this.to.x - this.from.x);
  22537. var dy = (this.to.y - this.from.y);
  22538. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  22539. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  22540. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  22541. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  22542. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  22543. var via;
  22544. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
  22545. via = this.via;
  22546. }
  22547. else if (this.options.smoothCurves.enabled == true) {
  22548. via = this._getViaCoordinates();
  22549. }
  22550. if (this.options.smoothCurves.enabled == true && via.x != null) {
  22551. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  22552. dx = (this.to.x - via.x);
  22553. dy = (this.to.y - via.y);
  22554. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  22555. }
  22556. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  22557. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  22558. var xTo,yTo;
  22559. if (this.options.smoothCurves.enabled == true && via.x != null) {
  22560. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  22561. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  22562. }
  22563. else {
  22564. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  22565. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  22566. }
  22567. ctx.beginPath();
  22568. ctx.moveTo(xFrom,yFrom);
  22569. if (this.options.smoothCurves.enabled == true && via.x != null) {
  22570. ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
  22571. }
  22572. else {
  22573. ctx.lineTo(xTo, yTo);
  22574. }
  22575. ctx.stroke();
  22576. // draw arrow at the end of the line
  22577. length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  22578. ctx.arrow(xTo, yTo, angle, length);
  22579. ctx.fill();
  22580. ctx.stroke();
  22581. // draw label
  22582. if (this.label) {
  22583. var point;
  22584. if (this.options.smoothCurves.enabled == true && via != null) {
  22585. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  22586. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  22587. point = {x:midpointX, y:midpointY};
  22588. }
  22589. else {
  22590. point = this._pointOnLine(0.5);
  22591. }
  22592. this._label(ctx, this.label, point.x, point.y);
  22593. }
  22594. }
  22595. else {
  22596. // draw circle
  22597. var node = this.from;
  22598. var x, y, arrow;
  22599. var radius = 0.25 * Math.max(100,this.physics.springLength);
  22600. if (!node.width) {
  22601. node.resize(ctx);
  22602. }
  22603. if (node.width > node.height) {
  22604. x = node.x + node.width * 0.5;
  22605. y = node.y - radius;
  22606. arrow = {
  22607. x: x,
  22608. y: node.y,
  22609. angle: 0.9 * Math.PI
  22610. };
  22611. }
  22612. else {
  22613. x = node.x + radius;
  22614. y = node.y - node.height * 0.5;
  22615. arrow = {
  22616. x: node.x,
  22617. y: y,
  22618. angle: 0.6 * Math.PI
  22619. };
  22620. }
  22621. ctx.beginPath();
  22622. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  22623. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  22624. ctx.stroke();
  22625. // draw all arrows
  22626. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  22627. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  22628. ctx.fill();
  22629. ctx.stroke();
  22630. // draw label
  22631. if (this.label) {
  22632. point = this._pointOnCircle(x, y, radius, 0.5);
  22633. this._label(ctx, this.label, point.x, point.y);
  22634. }
  22635. }
  22636. };
  22637. /**
  22638. * Calculate the distance between a point (x3,y3) and a line segment from
  22639. * (x1,y1) to (x2,y2).
  22640. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  22641. * @param {number} x1
  22642. * @param {number} y1
  22643. * @param {number} x2
  22644. * @param {number} y2
  22645. * @param {number} x3
  22646. * @param {number} y3
  22647. * @private
  22648. */
  22649. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  22650. var returnValue = 0;
  22651. if (this.from != this.to) {
  22652. if (this.options.smoothCurves.enabled == true) {
  22653. var xVia, yVia;
  22654. if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
  22655. xVia = this.via.x;
  22656. yVia = this.via.y;
  22657. }
  22658. else {
  22659. var via = this._getViaCoordinates();
  22660. xVia = via.x;
  22661. yVia = via.y;
  22662. }
  22663. var minDistance = 1e9;
  22664. var distance;
  22665. var i,t,x,y, lastX, lastY;
  22666. for (i = 0; i < 10; i++) {
  22667. t = 0.1*i;
  22668. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
  22669. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
  22670. if (i > 0) {
  22671. distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
  22672. minDistance = distance < minDistance ? distance : minDistance;
  22673. }
  22674. lastX = x; lastY = y;
  22675. }
  22676. returnValue = minDistance;
  22677. }
  22678. else {
  22679. returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
  22680. }
  22681. }
  22682. else {
  22683. var x, y, dx, dy;
  22684. var radius = 0.25 * this.physics.springLength;
  22685. var node = this.from;
  22686. if (node.width > node.height) {
  22687. x = node.x + 0.5 * node.width;
  22688. y = node.y - radius;
  22689. }
  22690. else {
  22691. x = node.x + radius;
  22692. y = node.y - 0.5 * node.height;
  22693. }
  22694. dx = x - x3;
  22695. dy = y - y3;
  22696. returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
  22697. }
  22698. if (this.labelDimensions.left < x3 &&
  22699. this.labelDimensions.left + this.labelDimensions.width > x3 &&
  22700. this.labelDimensions.top < y3 &&
  22701. this.labelDimensions.top + this.labelDimensions.height > y3) {
  22702. return 0;
  22703. }
  22704. else {
  22705. return returnValue;
  22706. }
  22707. };
  22708. Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
  22709. var px = x2-x1,
  22710. py = y2-y1,
  22711. something = px*px + py*py,
  22712. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  22713. if (u > 1) {
  22714. u = 1;
  22715. }
  22716. else if (u < 0) {
  22717. u = 0;
  22718. }
  22719. var x = x1 + u * px,
  22720. y = y1 + u * py,
  22721. dx = x - x3,
  22722. dy = y - y3;
  22723. //# Note: If the actual distance does not matter,
  22724. //# if you only want to compare what this function
  22725. //# returns to other results of this function, you
  22726. //# can just return the squared distance instead
  22727. //# (i.e. remove the sqrt) to gain a little performance
  22728. return Math.sqrt(dx*dx + dy*dy);
  22729. };
  22730. /**
  22731. * This allows the zoom level of the network to influence the rendering
  22732. *
  22733. * @param scale
  22734. */
  22735. Edge.prototype.setScale = function(scale) {
  22736. this.networkScaleInv = 1.0/scale;
  22737. };
  22738. Edge.prototype.select = function() {
  22739. this.selected = true;
  22740. };
  22741. Edge.prototype.unselect = function() {
  22742. this.selected = false;
  22743. };
  22744. Edge.prototype.positionBezierNode = function() {
  22745. if (this.via !== null && this.from !== null && this.to !== null) {
  22746. this.via.x = 0.5 * (this.from.x + this.to.x);
  22747. this.via.y = 0.5 * (this.from.y + this.to.y);
  22748. }
  22749. else {
  22750. this.via.x = 0;
  22751. this.via.y = 0;
  22752. }
  22753. };
  22754. /**
  22755. * This function draws the control nodes for the manipulator.
  22756. * In order to enable this, only set the this.controlNodesEnabled to true.
  22757. * @param ctx
  22758. */
  22759. Edge.prototype._drawControlNodes = function(ctx) {
  22760. if (this.controlNodesEnabled == true) {
  22761. if (this.controlNodes.from === null && this.controlNodes.to === null) {
  22762. var nodeIdFrom = "edgeIdFrom:".concat(this.id);
  22763. var nodeIdTo = "edgeIdTo:".concat(this.id);
  22764. var constants = {
  22765. nodes:{group:'', radius:8},
  22766. physics:{damping:0},
  22767. clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
  22768. };
  22769. this.controlNodes.from = new Node(
  22770. {id:nodeIdFrom,
  22771. shape:'dot',
  22772. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  22773. },{},{},constants);
  22774. this.controlNodes.to = new Node(
  22775. {id:nodeIdTo,
  22776. shape:'dot',
  22777. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  22778. },{},{},constants);
  22779. }
  22780. if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
  22781. this.controlNodes.positions = this.getControlNodePositions(ctx);
  22782. this.controlNodes.from.x = this.controlNodes.positions.from.x;
  22783. this.controlNodes.from.y = this.controlNodes.positions.from.y;
  22784. this.controlNodes.to.x = this.controlNodes.positions.to.x;
  22785. this.controlNodes.to.y = this.controlNodes.positions.to.y;
  22786. }
  22787. this.controlNodes.from.draw(ctx);
  22788. this.controlNodes.to.draw(ctx);
  22789. }
  22790. else {
  22791. this.controlNodes = {from:null, to:null, positions:{}};
  22792. }
  22793. };
  22794. /**
  22795. * Enable control nodes.
  22796. * @private
  22797. */
  22798. Edge.prototype._enableControlNodes = function() {
  22799. this.fromBackup = this.from;
  22800. this.toBackup = this.to;
  22801. this.controlNodesEnabled = true;
  22802. };
  22803. /**
  22804. * disable control nodes and remove from dynamicEdges from old node
  22805. * @private
  22806. */
  22807. Edge.prototype._disableControlNodes = function() {
  22808. this.fromId = this.from.id;
  22809. this.toId = this.to.id;
  22810. if (this.fromId != this.fromBackup.id) { // from was changed, remove edge from old 'from' node dynamic edges
  22811. this.fromBackup.detachEdge(this);
  22812. }
  22813. else if (this.toId != this.toBackup.id) { // to was changed, remove edge from old 'to' node dynamic edges
  22814. this.toBackup.detachEdge(this);
  22815. }
  22816. this.fromBackup = null;
  22817. this.toBackup = null;
  22818. this.controlNodesEnabled = false;
  22819. };
  22820. /**
  22821. * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
  22822. * @param x
  22823. * @param y
  22824. * @returns {null}
  22825. * @private
  22826. */
  22827. Edge.prototype._getSelectedControlNode = function(x,y) {
  22828. var positions = this.controlNodes.positions;
  22829. var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
  22830. var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
  22831. if (fromDistance < 15) {
  22832. this.connectedNode = this.from;
  22833. this.from = this.controlNodes.from;
  22834. return this.controlNodes.from;
  22835. }
  22836. else if (toDistance < 15) {
  22837. this.connectedNode = this.to;
  22838. this.to = this.controlNodes.to;
  22839. return this.controlNodes.to;
  22840. }
  22841. else {
  22842. return null;
  22843. }
  22844. };
  22845. /**
  22846. * this resets the control nodes to their original position.
  22847. * @private
  22848. */
  22849. Edge.prototype._restoreControlNodes = function() {
  22850. if (this.controlNodes.from.selected == true) {
  22851. this.from = this.connectedNode;
  22852. this.connectedNode = null;
  22853. this.controlNodes.from.unselect();
  22854. }
  22855. else if (this.controlNodes.to.selected == true) {
  22856. this.to = this.connectedNode;
  22857. this.connectedNode = null;
  22858. this.controlNodes.to.unselect();
  22859. }
  22860. };
  22861. /**
  22862. * this calculates the position of the control nodes on the edges of the parent nodes.
  22863. *
  22864. * @param ctx
  22865. * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
  22866. */
  22867. Edge.prototype.getControlNodePositions = function(ctx) {
  22868. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  22869. var dx = (this.to.x - this.from.x);
  22870. var dy = (this.to.y - this.from.y);
  22871. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  22872. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  22873. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  22874. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  22875. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  22876. var via;
  22877. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
  22878. via = this.via;
  22879. }
  22880. else if (this.options.smoothCurves.enabled == true) {
  22881. via = this._getViaCoordinates();
  22882. }
  22883. if (this.options.smoothCurves.enabled == true && via.x != null) {
  22884. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  22885. dx = (this.to.x - via.x);
  22886. dy = (this.to.y - via.y);
  22887. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  22888. }
  22889. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  22890. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  22891. var xTo,yTo;
  22892. if (this.options.smoothCurves.enabled == true && via.x != null) {
  22893. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  22894. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  22895. }
  22896. else {
  22897. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  22898. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  22899. }
  22900. return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
  22901. };
  22902. module.exports = Edge;
  22903. /***/ },
  22904. /* 53 */
  22905. /***/ function(module, exports, __webpack_require__) {
  22906. var util = __webpack_require__(1);
  22907. /**
  22908. * @class Node
  22909. * A node. A node can be connected to other nodes via one or multiple edges.
  22910. * @param {object} properties An object containing properties for the node. All
  22911. * properties are optional, except for the id.
  22912. * {number} id Id of the node. Required
  22913. * {string} label Text label for the node
  22914. * {number} x Horizontal position of the node
  22915. * {number} y Vertical position of the node
  22916. * {string} shape Node shape, available:
  22917. * "database", "circle", "ellipse",
  22918. * "box", "image", "text", "dot",
  22919. * "star", "triangle", "triangleDown",
  22920. * "square"
  22921. * {string} image An image url
  22922. * {string} title An title text, can be HTML
  22923. * {anytype} group A group name or number
  22924. * @param {Network.Images} imagelist A list with images. Only needed
  22925. * when the node has an image
  22926. * @param {Network.Groups} grouplist A list with groups. Needed for
  22927. * retrieving group properties
  22928. * @param {Object} constants An object with default values for
  22929. * example for the color
  22930. *
  22931. */
  22932. function Node(properties, imagelist, grouplist, networkConstants) {
  22933. var constants = util.selectiveBridgeObject(['nodes'],networkConstants);
  22934. this.options = constants.nodes;
  22935. this.selected = false;
  22936. this.hover = false;
  22937. this.edges = []; // all edges connected to this node
  22938. this.dynamicEdges = [];
  22939. this.reroutedEdges = {};
  22940. this.fontDrawThreshold = 3;
  22941. // set defaults for the properties
  22942. this.id = undefined;
  22943. this.x = null;
  22944. this.y = null;
  22945. this.allowedToMoveX = false;
  22946. this.allowedToMoveY = false;
  22947. this.xFixed = false;
  22948. this.yFixed = false;
  22949. this.horizontalAlignLeft = true; // these are for the navigation controls
  22950. this.verticalAlignTop = true; // these are for the navigation controls
  22951. this.baseRadiusValue = networkConstants.nodes.radius;
  22952. this.radiusFixed = false;
  22953. this.level = -1;
  22954. this.preassignedLevel = false;
  22955. this.hierarchyEnumerated = false;
  22956. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  22957. this.imagelist = imagelist;
  22958. this.grouplist = grouplist;
  22959. // physics properties
  22960. this.fx = 0.0; // external force x
  22961. this.fy = 0.0; // external force y
  22962. this.vx = 0.0; // velocity x
  22963. this.vy = 0.0; // velocity y
  22964. this.damping = networkConstants.physics.damping; // written every time gravity is calculated
  22965. this.fixedData = {x:null,y:null};
  22966. this.setProperties(properties, constants);
  22967. // creating the variables for clustering
  22968. this.resetCluster();
  22969. this.dynamicEdgesLength = 0;
  22970. this.clusterSession = 0;
  22971. this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width;
  22972. this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height;
  22973. this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius;
  22974. this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements;
  22975. this.growthIndicator = 0;
  22976. // variables to tell the node about the network.
  22977. this.networkScaleInv = 1;
  22978. this.networkScale = 1;
  22979. this.canvasTopLeft = {"x": -300, "y": -300};
  22980. this.canvasBottomRight = {"x": 300, "y": 300};
  22981. this.parentEdgeId = null;
  22982. }
  22983. /**
  22984. * (re)setting the clustering variables and objects
  22985. */
  22986. Node.prototype.resetCluster = function() {
  22987. // clustering variables
  22988. this.formationScale = undefined; // this is used to determine when to open the cluster
  22989. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  22990. this.containedNodes = {};
  22991. this.containedEdges = {};
  22992. this.clusterSessions = [];
  22993. };
  22994. /**
  22995. * Attach a edge to the node
  22996. * @param {Edge} edge
  22997. */
  22998. Node.prototype.attachEdge = function(edge) {
  22999. if (this.edges.indexOf(edge) == -1) {
  23000. this.edges.push(edge);
  23001. }
  23002. if (this.dynamicEdges.indexOf(edge) == -1) {
  23003. this.dynamicEdges.push(edge);
  23004. }
  23005. this.dynamicEdgesLength = this.dynamicEdges.length;
  23006. };
  23007. /**
  23008. * Detach a edge from the node
  23009. * @param {Edge} edge
  23010. */
  23011. Node.prototype.detachEdge = function(edge) {
  23012. var index = this.edges.indexOf(edge);
  23013. if (index != -1) {
  23014. this.edges.splice(index, 1);
  23015. }
  23016. index = this.dynamicEdges.indexOf(edge);
  23017. if (index != -1) {
  23018. this.dynamicEdges.splice(index, 1);
  23019. }
  23020. this.dynamicEdgesLength = this.dynamicEdges.length;
  23021. };
  23022. /**
  23023. * Set or overwrite properties for the node
  23024. * @param {Object} properties an object with properties
  23025. * @param {Object} constants and object with default, global properties
  23026. */
  23027. Node.prototype.setProperties = function(properties, constants) {
  23028. if (!properties) {
  23029. return;
  23030. }
  23031. var fields = ['borderWidth','borderWidthSelected','shape','image','brokenImage','radius','fontColor',
  23032. 'fontSize','fontFace','fontFill','group','mass'
  23033. ];
  23034. util.selectiveDeepExtend(fields, this.options, properties);
  23035. // basic properties
  23036. if (properties.id !== undefined) {this.id = properties.id;}
  23037. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  23038. if (properties.title !== undefined) {this.title = properties.title;}
  23039. if (properties.x !== undefined) {this.x = properties.x;}
  23040. if (properties.y !== undefined) {this.y = properties.y;}
  23041. if (properties.value !== undefined) {this.value = properties.value;}
  23042. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  23043. // navigation controls properties
  23044. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  23045. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  23046. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  23047. if (this.id === undefined) {
  23048. throw "Node must have an id";
  23049. }
  23050. // copy group properties
  23051. if (typeof this.options.group === 'number' || (typeof this.options.group === 'string' && this.options.group != '')) {
  23052. var groupObj = this.grouplist.get(this.options.group);
  23053. for (var prop in groupObj) {
  23054. if (groupObj.hasOwnProperty(prop)) {
  23055. this.options[prop] = groupObj[prop];
  23056. }
  23057. }
  23058. }
  23059. // individual shape properties
  23060. if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;}
  23061. if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);}
  23062. if (this.options.image!== undefined && this.options.image!= "") {
  23063. if (this.imagelist) {
  23064. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage);
  23065. }
  23066. else {
  23067. throw "No imagelist provided";
  23068. }
  23069. }
  23070. if (properties.allowedToMoveX !== undefined) {
  23071. this.xFixed = !properties.allowedToMoveX;
  23072. this.allowedToMoveX = properties.allowedToMoveX;
  23073. }
  23074. else if (properties.x !== undefined && this.allowedToMoveX == false) {
  23075. this.xFixed = true;
  23076. }
  23077. if (properties.allowedToMoveY !== undefined) {
  23078. this.yFixed = !properties.allowedToMoveY;
  23079. this.allowedToMoveY = properties.allowedToMoveY;
  23080. }
  23081. else if (properties.y !== undefined && this.allowedToMoveY == false) {
  23082. this.yFixed = true;
  23083. }
  23084. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  23085. if (this.options.shape == 'image') {
  23086. this.options.radiusMin = constants.nodes.widthMin;
  23087. this.options.radiusMax = constants.nodes.widthMax;
  23088. }
  23089. // choose draw method depending on the shape
  23090. switch (this.options.shape) {
  23091. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  23092. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  23093. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  23094. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  23095. // TODO: add diamond shape
  23096. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  23097. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  23098. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  23099. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  23100. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  23101. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  23102. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  23103. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  23104. }
  23105. // reset the size of the node, this can be changed
  23106. this._reset();
  23107. };
  23108. /**
  23109. * select this node
  23110. */
  23111. Node.prototype.select = function() {
  23112. this.selected = true;
  23113. this._reset();
  23114. };
  23115. /**
  23116. * unselect this node
  23117. */
  23118. Node.prototype.unselect = function() {
  23119. this.selected = false;
  23120. this._reset();
  23121. };
  23122. /**
  23123. * Reset the calculated size of the node, forces it to recalculate its size
  23124. */
  23125. Node.prototype.clearSizeCache = function() {
  23126. this._reset();
  23127. };
  23128. /**
  23129. * Reset the calculated size of the node, forces it to recalculate its size
  23130. * @private
  23131. */
  23132. Node.prototype._reset = function() {
  23133. this.width = undefined;
  23134. this.height = undefined;
  23135. };
  23136. /**
  23137. * get the title of this node.
  23138. * @return {string} title The title of the node, or undefined when no title
  23139. * has been set.
  23140. */
  23141. Node.prototype.getTitle = function() {
  23142. return typeof this.title === "function" ? this.title() : this.title;
  23143. };
  23144. /**
  23145. * Calculate the distance to the border of the Node
  23146. * @param {CanvasRenderingContext2D} ctx
  23147. * @param {Number} angle Angle in radians
  23148. * @returns {number} distance Distance to the border in pixels
  23149. */
  23150. Node.prototype.distanceToBorder = function (ctx, angle) {
  23151. var borderWidth = 1;
  23152. if (!this.width) {
  23153. this.resize(ctx);
  23154. }
  23155. switch (this.options.shape) {
  23156. case 'circle':
  23157. case 'dot':
  23158. return this.options.radius+ borderWidth;
  23159. case 'ellipse':
  23160. var a = this.width / 2;
  23161. var b = this.height / 2;
  23162. var w = (Math.sin(angle) * a);
  23163. var h = (Math.cos(angle) * b);
  23164. return a * b / Math.sqrt(w * w + h * h);
  23165. // TODO: implement distanceToBorder for database
  23166. // TODO: implement distanceToBorder for triangle
  23167. // TODO: implement distanceToBorder for triangleDown
  23168. case 'box':
  23169. case 'image':
  23170. case 'text':
  23171. default:
  23172. if (this.width) {
  23173. return Math.min(
  23174. Math.abs(this.width / 2 / Math.cos(angle)),
  23175. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  23176. // TODO: reckon with border radius too in case of box
  23177. }
  23178. else {
  23179. return 0;
  23180. }
  23181. }
  23182. // TODO: implement calculation of distance to border for all shapes
  23183. };
  23184. /**
  23185. * Set forces acting on the node
  23186. * @param {number} fx Force in horizontal direction
  23187. * @param {number} fy Force in vertical direction
  23188. */
  23189. Node.prototype._setForce = function(fx, fy) {
  23190. this.fx = fx;
  23191. this.fy = fy;
  23192. };
  23193. /**
  23194. * Add forces acting on the node
  23195. * @param {number} fx Force in horizontal direction
  23196. * @param {number} fy Force in vertical direction
  23197. * @private
  23198. */
  23199. Node.prototype._addForce = function(fx, fy) {
  23200. this.fx += fx;
  23201. this.fy += fy;
  23202. };
  23203. /**
  23204. * Perform one discrete step for the node
  23205. * @param {number} interval Time interval in seconds
  23206. */
  23207. Node.prototype.discreteStep = function(interval) {
  23208. if (!this.xFixed) {
  23209. var dx = this.damping * this.vx; // damping force
  23210. var ax = (this.fx - dx) / this.options.mass; // acceleration
  23211. this.vx += ax * interval; // velocity
  23212. this.x += this.vx * interval; // position
  23213. }
  23214. else {
  23215. this.fx = 0;
  23216. this.vx = 0;
  23217. }
  23218. if (!this.yFixed) {
  23219. var dy = this.damping * this.vy; // damping force
  23220. var ay = (this.fy - dy) / this.options.mass; // acceleration
  23221. this.vy += ay * interval; // velocity
  23222. this.y += this.vy * interval; // position
  23223. }
  23224. else {
  23225. this.fy = 0;
  23226. this.vy = 0;
  23227. }
  23228. };
  23229. /**
  23230. * Perform one discrete step for the node
  23231. * @param {number} interval Time interval in seconds
  23232. * @param {number} maxVelocity The speed limit imposed on the velocity
  23233. */
  23234. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  23235. if (!this.xFixed) {
  23236. var dx = this.damping * this.vx; // damping force
  23237. var ax = (this.fx - dx) / this.options.mass; // acceleration
  23238. this.vx += ax * interval; // velocity
  23239. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  23240. this.x += this.vx * interval; // position
  23241. }
  23242. else {
  23243. this.fx = 0;
  23244. this.vx = 0;
  23245. }
  23246. if (!this.yFixed) {
  23247. var dy = this.damping * this.vy; // damping force
  23248. var ay = (this.fy - dy) / this.options.mass; // acceleration
  23249. this.vy += ay * interval; // velocity
  23250. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  23251. this.y += this.vy * interval; // position
  23252. }
  23253. else {
  23254. this.fy = 0;
  23255. this.vy = 0;
  23256. }
  23257. };
  23258. /**
  23259. * Check if this node has a fixed x and y position
  23260. * @return {boolean} true if fixed, false if not
  23261. */
  23262. Node.prototype.isFixed = function() {
  23263. return (this.xFixed && this.yFixed);
  23264. };
  23265. /**
  23266. * Check if this node is moving
  23267. * @param {number} vmin the minimum velocity considered as "moving"
  23268. * @return {boolean} true if moving, false if it has no velocity
  23269. */
  23270. Node.prototype.isMoving = function(vmin) {
  23271. var velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2));
  23272. // this.velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2))
  23273. return (velocity > vmin);
  23274. };
  23275. /**
  23276. * check if this node is selecte
  23277. * @return {boolean} selected True if node is selected, else false
  23278. */
  23279. Node.prototype.isSelected = function() {
  23280. return this.selected;
  23281. };
  23282. /**
  23283. * Retrieve the value of the node. Can be undefined
  23284. * @return {Number} value
  23285. */
  23286. Node.prototype.getValue = function() {
  23287. return this.value;
  23288. };
  23289. /**
  23290. * Calculate the distance from the nodes location to the given location (x,y)
  23291. * @param {Number} x
  23292. * @param {Number} y
  23293. * @return {Number} value
  23294. */
  23295. Node.prototype.getDistance = function(x, y) {
  23296. var dx = this.x - x,
  23297. dy = this.y - y;
  23298. return Math.sqrt(dx * dx + dy * dy);
  23299. };
  23300. /**
  23301. * Adjust the value range of the node. The node will adjust it's radius
  23302. * based on its value.
  23303. * @param {Number} min
  23304. * @param {Number} max
  23305. */
  23306. Node.prototype.setValueRange = function(min, max) {
  23307. if (!this.radiusFixed && this.value !== undefined) {
  23308. if (max == min) {
  23309. this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2;
  23310. }
  23311. else {
  23312. var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min);
  23313. this.options.radius= (this.value - min) * scale + this.options.radiusMin;
  23314. }
  23315. }
  23316. this.baseRadiusValue = this.options.radius;
  23317. };
  23318. /**
  23319. * Draw this node in the given canvas
  23320. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23321. * @param {CanvasRenderingContext2D} ctx
  23322. */
  23323. Node.prototype.draw = function(ctx) {
  23324. throw "Draw method not initialized for node";
  23325. };
  23326. /**
  23327. * Recalculate the size of this node in the given canvas
  23328. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23329. * @param {CanvasRenderingContext2D} ctx
  23330. */
  23331. Node.prototype.resize = function(ctx) {
  23332. throw "Resize method not initialized for node";
  23333. };
  23334. /**
  23335. * Check if this object is overlapping with the provided object
  23336. * @param {Object} obj an object with parameters left, top, right, bottom
  23337. * @return {boolean} True if location is located on node
  23338. */
  23339. Node.prototype.isOverlappingWith = function(obj) {
  23340. return (this.left < obj.right &&
  23341. this.left + this.width > obj.left &&
  23342. this.top < obj.bottom &&
  23343. this.top + this.height > obj.top);
  23344. };
  23345. Node.prototype._resizeImage = function (ctx) {
  23346. // TODO: pre calculate the image size
  23347. if (!this.width || !this.height) { // undefined or 0
  23348. var width, height;
  23349. if (this.value) {
  23350. this.options.radius= this.baseRadiusValue;
  23351. var scale = this.imageObj.height / this.imageObj.width;
  23352. if (scale !== undefined) {
  23353. width = this.options.radius|| this.imageObj.width;
  23354. height = this.options.radius* scale || this.imageObj.height;
  23355. }
  23356. else {
  23357. width = 0;
  23358. height = 0;
  23359. }
  23360. }
  23361. else {
  23362. width = this.imageObj.width;
  23363. height = this.imageObj.height;
  23364. }
  23365. this.width = width;
  23366. this.height = height;
  23367. this.growthIndicator = 0;
  23368. if (this.width > 0 && this.height > 0) {
  23369. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23370. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23371. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23372. this.growthIndicator = this.width - width;
  23373. }
  23374. }
  23375. };
  23376. Node.prototype._drawImage = function (ctx) {
  23377. this._resizeImage(ctx);
  23378. this.left = this.x - this.width / 2;
  23379. this.top = this.y - this.height / 2;
  23380. var yLabel;
  23381. if (this.imageObj.width != 0 ) {
  23382. // draw the shade
  23383. if (this.clusterSize > 1) {
  23384. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  23385. lineWidth *= this.networkScaleInv;
  23386. lineWidth = Math.min(0.2 * this.width,lineWidth);
  23387. ctx.globalAlpha = 0.5;
  23388. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  23389. }
  23390. // draw the image
  23391. ctx.globalAlpha = 1.0;
  23392. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  23393. yLabel = this.y + this.height / 2;
  23394. }
  23395. else {
  23396. // image still loading... just draw the label for now
  23397. yLabel = this.y;
  23398. }
  23399. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  23400. };
  23401. Node.prototype._resizeBox = function (ctx) {
  23402. if (!this.width) {
  23403. var margin = 5;
  23404. var textSize = this.getTextSize(ctx);
  23405. this.width = textSize.width + 2 * margin;
  23406. this.height = textSize.height + 2 * margin;
  23407. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  23408. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  23409. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  23410. // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  23411. }
  23412. };
  23413. Node.prototype._drawBox = function (ctx) {
  23414. this._resizeBox(ctx);
  23415. this.left = this.x - this.width / 2;
  23416. this.top = this.y - this.height / 2;
  23417. var clusterLineWidth = 2.5;
  23418. var borderWidth = this.options.borderWidth;
  23419. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23420. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23421. // draw the outer border
  23422. if (this.clusterSize > 1) {
  23423. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23424. ctx.lineWidth *= this.networkScaleInv;
  23425. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23426. 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);
  23427. ctx.stroke();
  23428. }
  23429. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23430. ctx.lineWidth *= this.networkScaleInv;
  23431. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23432. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.options.color.background;
  23433. ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius);
  23434. ctx.fill();
  23435. ctx.stroke();
  23436. this._label(ctx, this.label, this.x, this.y);
  23437. };
  23438. Node.prototype._resizeDatabase = function (ctx) {
  23439. if (!this.width) {
  23440. var margin = 5;
  23441. var textSize = this.getTextSize(ctx);
  23442. var size = textSize.width + 2 * margin;
  23443. this.width = size;
  23444. this.height = size;
  23445. // scaling used for clustering
  23446. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23447. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23448. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23449. this.growthIndicator = this.width - size;
  23450. }
  23451. };
  23452. Node.prototype._drawDatabase = function (ctx) {
  23453. this._resizeDatabase(ctx);
  23454. this.left = this.x - this.width / 2;
  23455. this.top = this.y - this.height / 2;
  23456. var clusterLineWidth = 2.5;
  23457. var borderWidth = this.options.borderWidth;
  23458. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23459. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23460. // draw the outer border
  23461. if (this.clusterSize > 1) {
  23462. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23463. ctx.lineWidth *= this.networkScaleInv;
  23464. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23465. 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);
  23466. ctx.stroke();
  23467. }
  23468. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23469. ctx.lineWidth *= this.networkScaleInv;
  23470. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23471. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23472. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  23473. ctx.fill();
  23474. ctx.stroke();
  23475. this._label(ctx, this.label, this.x, this.y);
  23476. };
  23477. Node.prototype._resizeCircle = function (ctx) {
  23478. if (!this.width) {
  23479. var margin = 5;
  23480. var textSize = this.getTextSize(ctx);
  23481. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  23482. this.options.radius = diameter / 2;
  23483. this.width = diameter;
  23484. this.height = diameter;
  23485. // scaling used for clustering
  23486. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  23487. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  23488. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  23489. this.growthIndicator = this.options.radius- 0.5*diameter;
  23490. }
  23491. };
  23492. Node.prototype._drawCircle = function (ctx) {
  23493. this._resizeCircle(ctx);
  23494. this.left = this.x - this.width / 2;
  23495. this.top = this.y - this.height / 2;
  23496. var clusterLineWidth = 2.5;
  23497. var borderWidth = this.options.borderWidth;
  23498. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23499. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23500. // draw the outer border
  23501. if (this.clusterSize > 1) {
  23502. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23503. ctx.lineWidth *= this.networkScaleInv;
  23504. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23505. ctx.circle(this.x, this.y, this.options.radius+2*ctx.lineWidth);
  23506. ctx.stroke();
  23507. }
  23508. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23509. ctx.lineWidth *= this.networkScaleInv;
  23510. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23511. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23512. ctx.circle(this.x, this.y, this.options.radius);
  23513. ctx.fill();
  23514. ctx.stroke();
  23515. this._label(ctx, this.label, this.x, this.y);
  23516. };
  23517. Node.prototype._resizeEllipse = function (ctx) {
  23518. if (!this.width) {
  23519. var textSize = this.getTextSize(ctx);
  23520. this.width = textSize.width * 1.5;
  23521. this.height = textSize.height * 2;
  23522. if (this.width < this.height) {
  23523. this.width = this.height;
  23524. }
  23525. var defaultSize = this.width;
  23526. // scaling used for clustering
  23527. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23528. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23529. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23530. this.growthIndicator = this.width - defaultSize;
  23531. }
  23532. };
  23533. Node.prototype._drawEllipse = function (ctx) {
  23534. this._resizeEllipse(ctx);
  23535. this.left = this.x - this.width / 2;
  23536. this.top = this.y - this.height / 2;
  23537. var clusterLineWidth = 2.5;
  23538. var borderWidth = this.options.borderWidth;
  23539. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23540. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23541. // draw the outer border
  23542. if (this.clusterSize > 1) {
  23543. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23544. ctx.lineWidth *= this.networkScaleInv;
  23545. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23546. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  23547. ctx.stroke();
  23548. }
  23549. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23550. ctx.lineWidth *= this.networkScaleInv;
  23551. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23552. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23553. ctx.ellipse(this.left, this.top, this.width, this.height);
  23554. ctx.fill();
  23555. ctx.stroke();
  23556. this._label(ctx, this.label, this.x, this.y);
  23557. };
  23558. Node.prototype._drawDot = function (ctx) {
  23559. this._drawShape(ctx, 'circle');
  23560. };
  23561. Node.prototype._drawTriangle = function (ctx) {
  23562. this._drawShape(ctx, 'triangle');
  23563. };
  23564. Node.prototype._drawTriangleDown = function (ctx) {
  23565. this._drawShape(ctx, 'triangleDown');
  23566. };
  23567. Node.prototype._drawSquare = function (ctx) {
  23568. this._drawShape(ctx, 'square');
  23569. };
  23570. Node.prototype._drawStar = function (ctx) {
  23571. this._drawShape(ctx, 'star');
  23572. };
  23573. Node.prototype._resizeShape = function (ctx) {
  23574. if (!this.width) {
  23575. this.options.radius= this.baseRadiusValue;
  23576. var size = 2 * this.options.radius;
  23577. this.width = size;
  23578. this.height = size;
  23579. // scaling used for clustering
  23580. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23581. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23582. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  23583. this.growthIndicator = this.width - size;
  23584. }
  23585. };
  23586. Node.prototype._drawShape = function (ctx, shape) {
  23587. this._resizeShape(ctx);
  23588. this.left = this.x - this.width / 2;
  23589. this.top = this.y - this.height / 2;
  23590. var clusterLineWidth = 2.5;
  23591. var borderWidth = this.options.borderWidth;
  23592. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23593. var radiusMultiplier = 2;
  23594. // choose draw method depending on the shape
  23595. switch (shape) {
  23596. case 'dot': radiusMultiplier = 2; break;
  23597. case 'square': radiusMultiplier = 2; break;
  23598. case 'triangle': radiusMultiplier = 3; break;
  23599. case 'triangleDown': radiusMultiplier = 3; break;
  23600. case 'star': radiusMultiplier = 4; break;
  23601. }
  23602. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23603. // draw the outer border
  23604. if (this.clusterSize > 1) {
  23605. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23606. ctx.lineWidth *= this.networkScaleInv;
  23607. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23608. ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth);
  23609. ctx.stroke();
  23610. }
  23611. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23612. ctx.lineWidth *= this.networkScaleInv;
  23613. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23614. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23615. ctx[shape](this.x, this.y, this.options.radius);
  23616. ctx.fill();
  23617. ctx.stroke();
  23618. if (this.label) {
  23619. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true);
  23620. }
  23621. };
  23622. Node.prototype._resizeText = function (ctx) {
  23623. if (!this.width) {
  23624. var margin = 5;
  23625. var textSize = this.getTextSize(ctx);
  23626. this.width = textSize.width + 2 * margin;
  23627. this.height = textSize.height + 2 * margin;
  23628. // scaling used for clustering
  23629. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23630. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23631. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23632. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  23633. }
  23634. };
  23635. Node.prototype._drawText = function (ctx) {
  23636. this._resizeText(ctx);
  23637. this.left = this.x - this.width / 2;
  23638. this.top = this.y - this.height / 2;
  23639. this._label(ctx, this.label, this.x, this.y);
  23640. };
  23641. Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) {
  23642. if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) {
  23643. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  23644. var lines = text.split('\n');
  23645. var lineCount = lines.length;
  23646. var fontSize = (Number(this.options.fontSize) + 4); // TODO: why is this +4 ?
  23647. var yLine = y + (1 - lineCount) / 2 * fontSize;
  23648. if (labelUnderNode == true) {
  23649. yLine = y + (1 - lineCount) / (2 * fontSize);
  23650. }
  23651. // font fill from edges now for nodes!
  23652. var width = ctx.measureText(lines[0]).width;
  23653. for (var i = 1; i < lineCount; i++) {
  23654. var lineWidth = ctx.measureText(lines[i]).width;
  23655. width = lineWidth > width ? lineWidth : width;
  23656. }
  23657. var height = this.options.fontSize * lineCount;
  23658. var left = x - width / 2;
  23659. var top = y - height / 2;
  23660. if (baseline == "top") {
  23661. top += 0.5 * fontSize;
  23662. }
  23663. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  23664. // create the fontfill background
  23665. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  23666. ctx.fillStyle = this.options.fontFill;
  23667. ctx.fillRect(left, top, width, height);
  23668. }
  23669. // draw text
  23670. ctx.fillStyle = this.options.fontColor || "black";
  23671. ctx.textAlign = align || "center";
  23672. ctx.textBaseline = baseline || "middle";
  23673. for (var i = 0; i < lineCount; i++) {
  23674. ctx.fillText(lines[i], x, yLine);
  23675. yLine += fontSize;
  23676. }
  23677. }
  23678. };
  23679. Node.prototype.getTextSize = function(ctx) {
  23680. if (this.label !== undefined) {
  23681. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  23682. var lines = this.label.split('\n'),
  23683. height = (Number(this.options.fontSize) + 4) * lines.length,
  23684. width = 0;
  23685. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  23686. width = Math.max(width, ctx.measureText(lines[i]).width);
  23687. }
  23688. return {"width": width, "height": height};
  23689. }
  23690. else {
  23691. return {"width": 0, "height": 0};
  23692. }
  23693. };
  23694. /**
  23695. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  23696. * there is a safety margin of 0.3 * width;
  23697. *
  23698. * @returns {boolean}
  23699. */
  23700. Node.prototype.inArea = function() {
  23701. if (this.width !== undefined) {
  23702. return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x &&
  23703. this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x &&
  23704. this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y &&
  23705. this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y);
  23706. }
  23707. else {
  23708. return true;
  23709. }
  23710. };
  23711. /**
  23712. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  23713. * @returns {boolean}
  23714. */
  23715. Node.prototype.inView = function() {
  23716. return (this.x >= this.canvasTopLeft.x &&
  23717. this.x < this.canvasBottomRight.x &&
  23718. this.y >= this.canvasTopLeft.y &&
  23719. this.y < this.canvasBottomRight.y);
  23720. };
  23721. /**
  23722. * This allows the zoom level of the network to influence the rendering
  23723. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  23724. *
  23725. * @param scale
  23726. * @param canvasTopLeft
  23727. * @param canvasBottomRight
  23728. */
  23729. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  23730. this.networkScaleInv = 1.0/scale;
  23731. this.networkScale = scale;
  23732. this.canvasTopLeft = canvasTopLeft;
  23733. this.canvasBottomRight = canvasBottomRight;
  23734. };
  23735. /**
  23736. * This allows the zoom level of the network to influence the rendering
  23737. *
  23738. * @param scale
  23739. */
  23740. Node.prototype.setScale = function(scale) {
  23741. this.networkScaleInv = 1.0/scale;
  23742. this.networkScale = scale;
  23743. };
  23744. /**
  23745. * set the velocity at 0. Is called when this node is contained in another during clustering
  23746. */
  23747. Node.prototype.clearVelocity = function() {
  23748. this.vx = 0;
  23749. this.vy = 0;
  23750. };
  23751. /**
  23752. * Basic preservation of (kinectic) energy
  23753. *
  23754. * @param massBeforeClustering
  23755. */
  23756. Node.prototype.updateVelocity = function(massBeforeClustering) {
  23757. var energyBefore = this.vx * this.vx * massBeforeClustering;
  23758. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  23759. this.vx = Math.sqrt(energyBefore/this.options.mass);
  23760. energyBefore = this.vy * this.vy * massBeforeClustering;
  23761. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  23762. this.vy = Math.sqrt(energyBefore/this.options.mass);
  23763. };
  23764. module.exports = Node;
  23765. /***/ },
  23766. /* 54 */
  23767. /***/ function(module, exports, __webpack_require__) {
  23768. var util = __webpack_require__(1);
  23769. /**
  23770. * @class Groups
  23771. * This class can store groups and properties specific for groups.
  23772. */
  23773. function Groups() {
  23774. this.clear();
  23775. this.defaultIndex = 0;
  23776. }
  23777. /**
  23778. * default constants for group colors
  23779. */
  23780. Groups.DEFAULT = [
  23781. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  23782. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  23783. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  23784. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green
  23785. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  23786. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  23787. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange
  23788. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  23789. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  23790. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  23791. ];
  23792. /**
  23793. * Clear all groups
  23794. */
  23795. Groups.prototype.clear = function () {
  23796. this.groups = {};
  23797. this.groups.length = function()
  23798. {
  23799. var i = 0;
  23800. for ( var p in this ) {
  23801. if (this.hasOwnProperty(p)) {
  23802. i++;
  23803. }
  23804. }
  23805. return i;
  23806. }
  23807. };
  23808. /**
  23809. * get group properties of a groupname. If groupname is not found, a new group
  23810. * is added.
  23811. * @param {*} groupname Can be a number, string, Date, etc.
  23812. * @return {Object} group The created group, containing all group properties
  23813. */
  23814. Groups.prototype.get = function (groupname) {
  23815. var group = this.groups[groupname];
  23816. if (group == undefined) {
  23817. // create new group
  23818. var index = this.defaultIndex % Groups.DEFAULT.length;
  23819. this.defaultIndex++;
  23820. group = {};
  23821. group.color = Groups.DEFAULT[index];
  23822. this.groups[groupname] = group;
  23823. }
  23824. return group;
  23825. };
  23826. /**
  23827. * Add a custom group style
  23828. * @param {String} groupname
  23829. * @param {Object} style An object containing borderColor,
  23830. * backgroundColor, etc.
  23831. * @return {Object} group The created group object
  23832. */
  23833. Groups.prototype.add = function (groupname, style) {
  23834. this.groups[groupname] = style;
  23835. if (style.color) {
  23836. style.color = util.parseColor(style.color);
  23837. }
  23838. return style;
  23839. };
  23840. module.exports = Groups;
  23841. /***/ },
  23842. /* 55 */
  23843. /***/ function(module, exports, __webpack_require__) {
  23844. /**
  23845. * @class Images
  23846. * This class loads images and keeps them stored.
  23847. */
  23848. function Images() {
  23849. this.images = {};
  23850. this.callback = undefined;
  23851. }
  23852. /**
  23853. * Set an onload callback function. This will be called each time an image
  23854. * is loaded
  23855. * @param {function} callback
  23856. */
  23857. Images.prototype.setOnloadCallback = function(callback) {
  23858. this.callback = callback;
  23859. };
  23860. /**
  23861. *
  23862. * @param {string} url Url of the image
  23863. * @param {string} url Url of an image to use if the url image is not found
  23864. * @return {Image} img The image object
  23865. */
  23866. Images.prototype.load = function(url, brokenUrl) {
  23867. var img = this.images[url];
  23868. if (img == undefined) {
  23869. // create the image
  23870. var images = this;
  23871. img = new Image();
  23872. this.images[url] = img;
  23873. img.onload = function() {
  23874. if (images.callback) {
  23875. images.callback(this);
  23876. }
  23877. };
  23878. img.onerror = function () {
  23879. this.src = brokenUrl;
  23880. if (images.callback) {
  23881. images.callback(this);
  23882. }
  23883. };
  23884. img.src = url;
  23885. }
  23886. return img;
  23887. };
  23888. module.exports = Images;
  23889. /***/ },
  23890. /* 56 */
  23891. /***/ function(module, exports, __webpack_require__) {
  23892. /**
  23893. * Popup is a class to create a popup window with some text
  23894. * @param {Element} container The container object.
  23895. * @param {Number} [x]
  23896. * @param {Number} [y]
  23897. * @param {String} [text]
  23898. * @param {Object} [style] An object containing borderColor,
  23899. * backgroundColor, etc.
  23900. */
  23901. function Popup(container, x, y, text, style) {
  23902. if (container) {
  23903. this.container = container;
  23904. }
  23905. else {
  23906. this.container = document.body;
  23907. }
  23908. // x, y and text are optional, see if a style object was passed in their place
  23909. if (style === undefined) {
  23910. if (typeof x === "object") {
  23911. style = x;
  23912. x = undefined;
  23913. } else if (typeof text === "object") {
  23914. style = text;
  23915. text = undefined;
  23916. } else {
  23917. // for backwards compatibility, in case clients other than Network are creating Popup directly
  23918. style = {
  23919. fontColor: 'black',
  23920. fontSize: 14, // px
  23921. fontFace: 'verdana',
  23922. color: {
  23923. border: '#666',
  23924. background: '#FFFFC6'
  23925. }
  23926. }
  23927. }
  23928. }
  23929. this.x = 0;
  23930. this.y = 0;
  23931. this.padding = 5;
  23932. if (x !== undefined && y !== undefined ) {
  23933. this.setPosition(x, y);
  23934. }
  23935. if (text !== undefined) {
  23936. this.setText(text);
  23937. }
  23938. // create the frame
  23939. this.frame = document.createElement("div");
  23940. var styleAttr = this.frame.style;
  23941. styleAttr.position = "absolute";
  23942. styleAttr.visibility = "hidden";
  23943. styleAttr.border = "1px solid " + style.color.border;
  23944. styleAttr.color = style.fontColor;
  23945. styleAttr.fontSize = style.fontSize + "px";
  23946. styleAttr.fontFamily = style.fontFace;
  23947. styleAttr.padding = this.padding + "px";
  23948. styleAttr.backgroundColor = style.color.background;
  23949. styleAttr.borderRadius = "3px";
  23950. styleAttr.MozBorderRadius = "3px";
  23951. styleAttr.WebkitBorderRadius = "3px";
  23952. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  23953. styleAttr.whiteSpace = "nowrap";
  23954. this.container.appendChild(this.frame);
  23955. }
  23956. /**
  23957. * @param {number} x Horizontal position of the popup window
  23958. * @param {number} y Vertical position of the popup window
  23959. */
  23960. Popup.prototype.setPosition = function(x, y) {
  23961. this.x = parseInt(x);
  23962. this.y = parseInt(y);
  23963. };
  23964. /**
  23965. * Set the content for the popup window. This can be HTML code or text.
  23966. * @param {string | Element} content
  23967. */
  23968. Popup.prototype.setText = function(content) {
  23969. if (content instanceof Element) {
  23970. this.frame.innerHTML = '';
  23971. this.frame.appendChild(content);
  23972. }
  23973. else {
  23974. this.frame.innerHTML = content; // string containing text or HTML
  23975. }
  23976. };
  23977. /**
  23978. * Show the popup window
  23979. * @param {boolean} show Optional. Show or hide the window
  23980. */
  23981. Popup.prototype.show = function (show) {
  23982. if (show === undefined) {
  23983. show = true;
  23984. }
  23985. if (show) {
  23986. var height = this.frame.clientHeight;
  23987. var width = this.frame.clientWidth;
  23988. var maxHeight = this.frame.parentNode.clientHeight;
  23989. var maxWidth = this.frame.parentNode.clientWidth;
  23990. var top = (this.y - height);
  23991. if (top + height + this.padding > maxHeight) {
  23992. top = maxHeight - height - this.padding;
  23993. }
  23994. if (top < this.padding) {
  23995. top = this.padding;
  23996. }
  23997. var left = this.x;
  23998. if (left + width + this.padding > maxWidth) {
  23999. left = maxWidth - width - this.padding;
  24000. }
  24001. if (left < this.padding) {
  24002. left = this.padding;
  24003. }
  24004. this.frame.style.left = left + "px";
  24005. this.frame.style.top = top + "px";
  24006. this.frame.style.visibility = "visible";
  24007. }
  24008. else {
  24009. this.hide();
  24010. }
  24011. };
  24012. /**
  24013. * Hide the popup window
  24014. */
  24015. Popup.prototype.hide = function () {
  24016. this.frame.style.visibility = "hidden";
  24017. };
  24018. module.exports = Popup;
  24019. /***/ },
  24020. /* 57 */
  24021. /***/ function(module, exports, __webpack_require__) {
  24022. /**
  24023. * Parse a text source containing data in DOT language into a JSON object.
  24024. * The object contains two lists: one with nodes and one with edges.
  24025. *
  24026. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  24027. *
  24028. * @param {String} data Text containing a graph in DOT-notation
  24029. * @return {Object} graph An object containing two parameters:
  24030. * {Object[]} nodes
  24031. * {Object[]} edges
  24032. */
  24033. function parseDOT (data) {
  24034. dot = data;
  24035. return parseGraph();
  24036. }
  24037. // token types enumeration
  24038. var TOKENTYPE = {
  24039. NULL : 0,
  24040. DELIMITER : 1,
  24041. IDENTIFIER: 2,
  24042. UNKNOWN : 3
  24043. };
  24044. // map with all delimiters
  24045. var DELIMITERS = {
  24046. '{': true,
  24047. '}': true,
  24048. '[': true,
  24049. ']': true,
  24050. ';': true,
  24051. '=': true,
  24052. ',': true,
  24053. '->': true,
  24054. '--': true
  24055. };
  24056. var dot = ''; // current dot file
  24057. var index = 0; // current index in dot file
  24058. var c = ''; // current token character in expr
  24059. var token = ''; // current token
  24060. var tokenType = TOKENTYPE.NULL; // type of the token
  24061. /**
  24062. * Get the first character from the dot file.
  24063. * The character is stored into the char c. If the end of the dot file is
  24064. * reached, the function puts an empty string in c.
  24065. */
  24066. function first() {
  24067. index = 0;
  24068. c = dot.charAt(0);
  24069. }
  24070. /**
  24071. * Get the next character from the dot file.
  24072. * The character is stored into the char c. If the end of the dot file is
  24073. * reached, the function puts an empty string in c.
  24074. */
  24075. function next() {
  24076. index++;
  24077. c = dot.charAt(index);
  24078. }
  24079. /**
  24080. * Preview the next character from the dot file.
  24081. * @return {String} cNext
  24082. */
  24083. function nextPreview() {
  24084. return dot.charAt(index + 1);
  24085. }
  24086. /**
  24087. * Test whether given character is alphabetic or numeric
  24088. * @param {String} c
  24089. * @return {Boolean} isAlphaNumeric
  24090. */
  24091. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  24092. function isAlphaNumeric(c) {
  24093. return regexAlphaNumeric.test(c);
  24094. }
  24095. /**
  24096. * Merge all properties of object b into object b
  24097. * @param {Object} a
  24098. * @param {Object} b
  24099. * @return {Object} a
  24100. */
  24101. function merge (a, b) {
  24102. if (!a) {
  24103. a = {};
  24104. }
  24105. if (b) {
  24106. for (var name in b) {
  24107. if (b.hasOwnProperty(name)) {
  24108. a[name] = b[name];
  24109. }
  24110. }
  24111. }
  24112. return a;
  24113. }
  24114. /**
  24115. * Set a value in an object, where the provided parameter name can be a
  24116. * path with nested parameters. For example:
  24117. *
  24118. * var obj = {a: 2};
  24119. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  24120. *
  24121. * @param {Object} obj
  24122. * @param {String} path A parameter name or dot-separated parameter path,
  24123. * like "color.highlight.border".
  24124. * @param {*} value
  24125. */
  24126. function setValue(obj, path, value) {
  24127. var keys = path.split('.');
  24128. var o = obj;
  24129. while (keys.length) {
  24130. var key = keys.shift();
  24131. if (keys.length) {
  24132. // this isn't the end point
  24133. if (!o[key]) {
  24134. o[key] = {};
  24135. }
  24136. o = o[key];
  24137. }
  24138. else {
  24139. // this is the end point
  24140. o[key] = value;
  24141. }
  24142. }
  24143. }
  24144. /**
  24145. * Add a node to a graph object. If there is already a node with
  24146. * the same id, their attributes will be merged.
  24147. * @param {Object} graph
  24148. * @param {Object} node
  24149. */
  24150. function addNode(graph, node) {
  24151. var i, len;
  24152. var current = null;
  24153. // find root graph (in case of subgraph)
  24154. var graphs = [graph]; // list with all graphs from current graph to root graph
  24155. var root = graph;
  24156. while (root.parent) {
  24157. graphs.push(root.parent);
  24158. root = root.parent;
  24159. }
  24160. // find existing node (at root level) by its id
  24161. if (root.nodes) {
  24162. for (i = 0, len = root.nodes.length; i < len; i++) {
  24163. if (node.id === root.nodes[i].id) {
  24164. current = root.nodes[i];
  24165. break;
  24166. }
  24167. }
  24168. }
  24169. if (!current) {
  24170. // this is a new node
  24171. current = {
  24172. id: node.id
  24173. };
  24174. if (graph.node) {
  24175. // clone default attributes
  24176. current.attr = merge(current.attr, graph.node);
  24177. }
  24178. }
  24179. // add node to this (sub)graph and all its parent graphs
  24180. for (i = graphs.length - 1; i >= 0; i--) {
  24181. var g = graphs[i];
  24182. if (!g.nodes) {
  24183. g.nodes = [];
  24184. }
  24185. if (g.nodes.indexOf(current) == -1) {
  24186. g.nodes.push(current);
  24187. }
  24188. }
  24189. // merge attributes
  24190. if (node.attr) {
  24191. current.attr = merge(current.attr, node.attr);
  24192. }
  24193. }
  24194. /**
  24195. * Add an edge to a graph object
  24196. * @param {Object} graph
  24197. * @param {Object} edge
  24198. */
  24199. function addEdge(graph, edge) {
  24200. if (!graph.edges) {
  24201. graph.edges = [];
  24202. }
  24203. graph.edges.push(edge);
  24204. if (graph.edge) {
  24205. var attr = merge({}, graph.edge); // clone default attributes
  24206. edge.attr = merge(attr, edge.attr); // merge attributes
  24207. }
  24208. }
  24209. /**
  24210. * Create an edge to a graph object
  24211. * @param {Object} graph
  24212. * @param {String | Number | Object} from
  24213. * @param {String | Number | Object} to
  24214. * @param {String} type
  24215. * @param {Object | null} attr
  24216. * @return {Object} edge
  24217. */
  24218. function createEdge(graph, from, to, type, attr) {
  24219. var edge = {
  24220. from: from,
  24221. to: to,
  24222. type: type
  24223. };
  24224. if (graph.edge) {
  24225. edge.attr = merge({}, graph.edge); // clone default attributes
  24226. }
  24227. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  24228. return edge;
  24229. }
  24230. /**
  24231. * Get next token in the current dot file.
  24232. * The token and token type are available as token and tokenType
  24233. */
  24234. function getToken() {
  24235. tokenType = TOKENTYPE.NULL;
  24236. token = '';
  24237. // skip over whitespaces
  24238. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  24239. next();
  24240. }
  24241. do {
  24242. var isComment = false;
  24243. // skip comment
  24244. if (c == '#') {
  24245. // find the previous non-space character
  24246. var i = index - 1;
  24247. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  24248. i--;
  24249. }
  24250. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  24251. // the # is at the start of a line, this is indeed a line comment
  24252. while (c != '' && c != '\n') {
  24253. next();
  24254. }
  24255. isComment = true;
  24256. }
  24257. }
  24258. if (c == '/' && nextPreview() == '/') {
  24259. // skip line comment
  24260. while (c != '' && c != '\n') {
  24261. next();
  24262. }
  24263. isComment = true;
  24264. }
  24265. if (c == '/' && nextPreview() == '*') {
  24266. // skip block comment
  24267. while (c != '') {
  24268. if (c == '*' && nextPreview() == '/') {
  24269. // end of block comment found. skip these last two characters
  24270. next();
  24271. next();
  24272. break;
  24273. }
  24274. else {
  24275. next();
  24276. }
  24277. }
  24278. isComment = true;
  24279. }
  24280. // skip over whitespaces
  24281. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  24282. next();
  24283. }
  24284. }
  24285. while (isComment);
  24286. // check for end of dot file
  24287. if (c == '') {
  24288. // token is still empty
  24289. tokenType = TOKENTYPE.DELIMITER;
  24290. return;
  24291. }
  24292. // check for delimiters consisting of 2 characters
  24293. var c2 = c + nextPreview();
  24294. if (DELIMITERS[c2]) {
  24295. tokenType = TOKENTYPE.DELIMITER;
  24296. token = c2;
  24297. next();
  24298. next();
  24299. return;
  24300. }
  24301. // check for delimiters consisting of 1 character
  24302. if (DELIMITERS[c]) {
  24303. tokenType = TOKENTYPE.DELIMITER;
  24304. token = c;
  24305. next();
  24306. return;
  24307. }
  24308. // check for an identifier (number or string)
  24309. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  24310. if (isAlphaNumeric(c) || c == '-') {
  24311. token += c;
  24312. next();
  24313. while (isAlphaNumeric(c)) {
  24314. token += c;
  24315. next();
  24316. }
  24317. if (token == 'false') {
  24318. token = false; // convert to boolean
  24319. }
  24320. else if (token == 'true') {
  24321. token = true; // convert to boolean
  24322. }
  24323. else if (!isNaN(Number(token))) {
  24324. token = Number(token); // convert to number
  24325. }
  24326. tokenType = TOKENTYPE.IDENTIFIER;
  24327. return;
  24328. }
  24329. // check for a string enclosed by double quotes
  24330. if (c == '"') {
  24331. next();
  24332. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  24333. token += c;
  24334. if (c == '"') { // skip the escape character
  24335. next();
  24336. }
  24337. next();
  24338. }
  24339. if (c != '"') {
  24340. throw newSyntaxError('End of string " expected');
  24341. }
  24342. next();
  24343. tokenType = TOKENTYPE.IDENTIFIER;
  24344. return;
  24345. }
  24346. // something unknown is found, wrong characters, a syntax error
  24347. tokenType = TOKENTYPE.UNKNOWN;
  24348. while (c != '') {
  24349. token += c;
  24350. next();
  24351. }
  24352. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  24353. }
  24354. /**
  24355. * Parse a graph.
  24356. * @returns {Object} graph
  24357. */
  24358. function parseGraph() {
  24359. var graph = {};
  24360. first();
  24361. getToken();
  24362. // optional strict keyword
  24363. if (token == 'strict') {
  24364. graph.strict = true;
  24365. getToken();
  24366. }
  24367. // graph or digraph keyword
  24368. if (token == 'graph' || token == 'digraph') {
  24369. graph.type = token;
  24370. getToken();
  24371. }
  24372. // optional graph id
  24373. if (tokenType == TOKENTYPE.IDENTIFIER) {
  24374. graph.id = token;
  24375. getToken();
  24376. }
  24377. // open angle bracket
  24378. if (token != '{') {
  24379. throw newSyntaxError('Angle bracket { expected');
  24380. }
  24381. getToken();
  24382. // statements
  24383. parseStatements(graph);
  24384. // close angle bracket
  24385. if (token != '}') {
  24386. throw newSyntaxError('Angle bracket } expected');
  24387. }
  24388. getToken();
  24389. // end of file
  24390. if (token !== '') {
  24391. throw newSyntaxError('End of file expected');
  24392. }
  24393. getToken();
  24394. // remove temporary default properties
  24395. delete graph.node;
  24396. delete graph.edge;
  24397. delete graph.graph;
  24398. return graph;
  24399. }
  24400. /**
  24401. * Parse a list with statements.
  24402. * @param {Object} graph
  24403. */
  24404. function parseStatements (graph) {
  24405. while (token !== '' && token != '}') {
  24406. parseStatement(graph);
  24407. if (token == ';') {
  24408. getToken();
  24409. }
  24410. }
  24411. }
  24412. /**
  24413. * Parse a single statement. Can be a an attribute statement, node
  24414. * statement, a series of node statements and edge statements, or a
  24415. * parameter.
  24416. * @param {Object} graph
  24417. */
  24418. function parseStatement(graph) {
  24419. // parse subgraph
  24420. var subgraph = parseSubgraph(graph);
  24421. if (subgraph) {
  24422. // edge statements
  24423. parseEdge(graph, subgraph);
  24424. return;
  24425. }
  24426. // parse an attribute statement
  24427. var attr = parseAttributeStatement(graph);
  24428. if (attr) {
  24429. return;
  24430. }
  24431. // parse node
  24432. if (tokenType != TOKENTYPE.IDENTIFIER) {
  24433. throw newSyntaxError('Identifier expected');
  24434. }
  24435. var id = token; // id can be a string or a number
  24436. getToken();
  24437. if (token == '=') {
  24438. // id statement
  24439. getToken();
  24440. if (tokenType != TOKENTYPE.IDENTIFIER) {
  24441. throw newSyntaxError('Identifier expected');
  24442. }
  24443. graph[id] = token;
  24444. getToken();
  24445. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  24446. }
  24447. else {
  24448. parseNodeStatement(graph, id);
  24449. }
  24450. }
  24451. /**
  24452. * Parse a subgraph
  24453. * @param {Object} graph parent graph object
  24454. * @return {Object | null} subgraph
  24455. */
  24456. function parseSubgraph (graph) {
  24457. var subgraph = null;
  24458. // optional subgraph keyword
  24459. if (token == 'subgraph') {
  24460. subgraph = {};
  24461. subgraph.type = 'subgraph';
  24462. getToken();
  24463. // optional graph id
  24464. if (tokenType == TOKENTYPE.IDENTIFIER) {
  24465. subgraph.id = token;
  24466. getToken();
  24467. }
  24468. }
  24469. // open angle bracket
  24470. if (token == '{') {
  24471. getToken();
  24472. if (!subgraph) {
  24473. subgraph = {};
  24474. }
  24475. subgraph.parent = graph;
  24476. subgraph.node = graph.node;
  24477. subgraph.edge = graph.edge;
  24478. subgraph.graph = graph.graph;
  24479. // statements
  24480. parseStatements(subgraph);
  24481. // close angle bracket
  24482. if (token != '}') {
  24483. throw newSyntaxError('Angle bracket } expected');
  24484. }
  24485. getToken();
  24486. // remove temporary default properties
  24487. delete subgraph.node;
  24488. delete subgraph.edge;
  24489. delete subgraph.graph;
  24490. delete subgraph.parent;
  24491. // register at the parent graph
  24492. if (!graph.subgraphs) {
  24493. graph.subgraphs = [];
  24494. }
  24495. graph.subgraphs.push(subgraph);
  24496. }
  24497. return subgraph;
  24498. }
  24499. /**
  24500. * parse an attribute statement like "node [shape=circle fontSize=16]".
  24501. * Available keywords are 'node', 'edge', 'graph'.
  24502. * The previous list with default attributes will be replaced
  24503. * @param {Object} graph
  24504. * @returns {String | null} keyword Returns the name of the parsed attribute
  24505. * (node, edge, graph), or null if nothing
  24506. * is parsed.
  24507. */
  24508. function parseAttributeStatement (graph) {
  24509. // attribute statements
  24510. if (token == 'node') {
  24511. getToken();
  24512. // node attributes
  24513. graph.node = parseAttributeList();
  24514. return 'node';
  24515. }
  24516. else if (token == 'edge') {
  24517. getToken();
  24518. // edge attributes
  24519. graph.edge = parseAttributeList();
  24520. return 'edge';
  24521. }
  24522. else if (token == 'graph') {
  24523. getToken();
  24524. // graph attributes
  24525. graph.graph = parseAttributeList();
  24526. return 'graph';
  24527. }
  24528. return null;
  24529. }
  24530. /**
  24531. * parse a node statement
  24532. * @param {Object} graph
  24533. * @param {String | Number} id
  24534. */
  24535. function parseNodeStatement(graph, id) {
  24536. // node statement
  24537. var node = {
  24538. id: id
  24539. };
  24540. var attr = parseAttributeList();
  24541. if (attr) {
  24542. node.attr = attr;
  24543. }
  24544. addNode(graph, node);
  24545. // edge statements
  24546. parseEdge(graph, id);
  24547. }
  24548. /**
  24549. * Parse an edge or a series of edges
  24550. * @param {Object} graph
  24551. * @param {String | Number} from Id of the from node
  24552. */
  24553. function parseEdge(graph, from) {
  24554. while (token == '->' || token == '--') {
  24555. var to;
  24556. var type = token;
  24557. getToken();
  24558. var subgraph = parseSubgraph(graph);
  24559. if (subgraph) {
  24560. to = subgraph;
  24561. }
  24562. else {
  24563. if (tokenType != TOKENTYPE.IDENTIFIER) {
  24564. throw newSyntaxError('Identifier or subgraph expected');
  24565. }
  24566. to = token;
  24567. addNode(graph, {
  24568. id: to
  24569. });
  24570. getToken();
  24571. }
  24572. // parse edge attributes
  24573. var attr = parseAttributeList();
  24574. // create edge
  24575. var edge = createEdge(graph, from, to, type, attr);
  24576. addEdge(graph, edge);
  24577. from = to;
  24578. }
  24579. }
  24580. /**
  24581. * Parse a set with attributes,
  24582. * for example [label="1.000", shape=solid]
  24583. * @return {Object | null} attr
  24584. */
  24585. function parseAttributeList() {
  24586. var attr = null;
  24587. while (token == '[') {
  24588. getToken();
  24589. attr = {};
  24590. while (token !== '' && token != ']') {
  24591. if (tokenType != TOKENTYPE.IDENTIFIER) {
  24592. throw newSyntaxError('Attribute name expected');
  24593. }
  24594. var name = token;
  24595. getToken();
  24596. if (token != '=') {
  24597. throw newSyntaxError('Equal sign = expected');
  24598. }
  24599. getToken();
  24600. if (tokenType != TOKENTYPE.IDENTIFIER) {
  24601. throw newSyntaxError('Attribute value expected');
  24602. }
  24603. var value = token;
  24604. setValue(attr, name, value); // name can be a path
  24605. getToken();
  24606. if (token ==',') {
  24607. getToken();
  24608. }
  24609. }
  24610. if (token != ']') {
  24611. throw newSyntaxError('Bracket ] expected');
  24612. }
  24613. getToken();
  24614. }
  24615. return attr;
  24616. }
  24617. /**
  24618. * Create a syntax error with extra information on current token and index.
  24619. * @param {String} message
  24620. * @returns {SyntaxError} err
  24621. */
  24622. function newSyntaxError(message) {
  24623. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  24624. }
  24625. /**
  24626. * Chop off text after a maximum length
  24627. * @param {String} text
  24628. * @param {Number} maxLength
  24629. * @returns {String}
  24630. */
  24631. function chop (text, maxLength) {
  24632. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  24633. }
  24634. /**
  24635. * Execute a function fn for each pair of elements in two arrays
  24636. * @param {Array | *} array1
  24637. * @param {Array | *} array2
  24638. * @param {function} fn
  24639. */
  24640. function forEach2(array1, array2, fn) {
  24641. if (Array.isArray(array1)) {
  24642. array1.forEach(function (elem1) {
  24643. if (Array.isArray(array2)) {
  24644. array2.forEach(function (elem2) {
  24645. fn(elem1, elem2);
  24646. });
  24647. }
  24648. else {
  24649. fn(elem1, array2);
  24650. }
  24651. });
  24652. }
  24653. else {
  24654. if (Array.isArray(array2)) {
  24655. array2.forEach(function (elem2) {
  24656. fn(array1, elem2);
  24657. });
  24658. }
  24659. else {
  24660. fn(array1, array2);
  24661. }
  24662. }
  24663. }
  24664. /**
  24665. * Convert a string containing a graph in DOT language into a map containing
  24666. * with nodes and edges in the format of graph.
  24667. * @param {String} data Text containing a graph in DOT-notation
  24668. * @return {Object} graphData
  24669. */
  24670. function DOTToGraph (data) {
  24671. // parse the DOT file
  24672. var dotData = parseDOT(data);
  24673. var graphData = {
  24674. nodes: [],
  24675. edges: [],
  24676. options: {}
  24677. };
  24678. // copy the nodes
  24679. if (dotData.nodes) {
  24680. dotData.nodes.forEach(function (dotNode) {
  24681. var graphNode = {
  24682. id: dotNode.id,
  24683. label: String(dotNode.label || dotNode.id)
  24684. };
  24685. merge(graphNode, dotNode.attr);
  24686. if (graphNode.image) {
  24687. graphNode.shape = 'image';
  24688. }
  24689. graphData.nodes.push(graphNode);
  24690. });
  24691. }
  24692. // copy the edges
  24693. if (dotData.edges) {
  24694. /**
  24695. * Convert an edge in DOT format to an edge with VisGraph format
  24696. * @param {Object} dotEdge
  24697. * @returns {Object} graphEdge
  24698. */
  24699. var convertEdge = function (dotEdge) {
  24700. var graphEdge = {
  24701. from: dotEdge.from,
  24702. to: dotEdge.to
  24703. };
  24704. merge(graphEdge, dotEdge.attr);
  24705. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  24706. return graphEdge;
  24707. }
  24708. dotData.edges.forEach(function (dotEdge) {
  24709. var from, to;
  24710. if (dotEdge.from instanceof Object) {
  24711. from = dotEdge.from.nodes;
  24712. }
  24713. else {
  24714. from = {
  24715. id: dotEdge.from
  24716. }
  24717. }
  24718. if (dotEdge.to instanceof Object) {
  24719. to = dotEdge.to.nodes;
  24720. }
  24721. else {
  24722. to = {
  24723. id: dotEdge.to
  24724. }
  24725. }
  24726. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  24727. dotEdge.from.edges.forEach(function (subEdge) {
  24728. var graphEdge = convertEdge(subEdge);
  24729. graphData.edges.push(graphEdge);
  24730. });
  24731. }
  24732. forEach2(from, to, function (from, to) {
  24733. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  24734. var graphEdge = convertEdge(subEdge);
  24735. graphData.edges.push(graphEdge);
  24736. });
  24737. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  24738. dotEdge.to.edges.forEach(function (subEdge) {
  24739. var graphEdge = convertEdge(subEdge);
  24740. graphData.edges.push(graphEdge);
  24741. });
  24742. }
  24743. });
  24744. }
  24745. // copy the options
  24746. if (dotData.attr) {
  24747. graphData.options = dotData.attr;
  24748. }
  24749. return graphData;
  24750. }
  24751. // exports
  24752. exports.parseDOT = parseDOT;
  24753. exports.DOTToGraph = DOTToGraph;
  24754. /***/ },
  24755. /* 58 */
  24756. /***/ function(module, exports, __webpack_require__) {
  24757. function parseGephi(gephiJSON, options) {
  24758. var edges = [];
  24759. var nodes = [];
  24760. this.options = {
  24761. edges: {
  24762. inheritColor: true
  24763. },
  24764. nodes: {
  24765. allowedToMove: false,
  24766. parseColor: false
  24767. }
  24768. };
  24769. if (options !== undefined) {
  24770. this.options.nodes['allowedToMove'] = options.allowedToMove | false;
  24771. this.options.nodes['parseColor'] = options.parseColor | false;
  24772. this.options.edges['inheritColor'] = options.inheritColor | true;
  24773. }
  24774. var gEdges = gephiJSON.edges;
  24775. var gNodes = gephiJSON.nodes;
  24776. for (var i = 0; i < gEdges.length; i++) {
  24777. var edge = {};
  24778. var gEdge = gEdges[i];
  24779. edge['id'] = gEdge.id;
  24780. edge['from'] = gEdge.source;
  24781. edge['to'] = gEdge.target;
  24782. edge['attributes'] = gEdge.attributes;
  24783. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  24784. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  24785. edge['color'] = gEdge.color;
  24786. edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
  24787. edges.push(edge);
  24788. }
  24789. for (var i = 0; i < gNodes.length; i++) {
  24790. var node = {};
  24791. var gNode = gNodes[i];
  24792. node['id'] = gNode.id;
  24793. node['attributes'] = gNode.attributes;
  24794. node['x'] = gNode.x;
  24795. node['y'] = gNode.y;
  24796. node['label'] = gNode.label;
  24797. if (this.options.nodes.parseColor == true) {
  24798. node['color'] = gNode.color;
  24799. }
  24800. else {
  24801. node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
  24802. }
  24803. node['radius'] = gNode.size;
  24804. node['allowedToMoveX'] = this.options.nodes.allowedToMove;
  24805. node['allowedToMoveY'] = this.options.nodes.allowedToMove;
  24806. nodes.push(node);
  24807. }
  24808. return {nodes:nodes, edges:edges};
  24809. }
  24810. exports.parseGephi = parseGephi;
  24811. /***/ },
  24812. /* 59 */
  24813. /***/ function(module, exports, __webpack_require__) {
  24814. var PhysicsMixin = __webpack_require__(62);
  24815. var ClusterMixin = __webpack_require__(63);
  24816. var SectorsMixin = __webpack_require__(64);
  24817. var SelectionMixin = __webpack_require__(65);
  24818. var ManipulationMixin = __webpack_require__(66);
  24819. var NavigationMixin = __webpack_require__(67);
  24820. var HierarchicalLayoutMixin = __webpack_require__(68);
  24821. /**
  24822. * Load a mixin into the network object
  24823. *
  24824. * @param {Object} sourceVariable | this object has to contain functions.
  24825. * @private
  24826. */
  24827. exports._loadMixin = function (sourceVariable) {
  24828. for (var mixinFunction in sourceVariable) {
  24829. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  24830. this[mixinFunction] = sourceVariable[mixinFunction];
  24831. }
  24832. }
  24833. };
  24834. /**
  24835. * removes a mixin from the network object.
  24836. *
  24837. * @param {Object} sourceVariable | this object has to contain functions.
  24838. * @private
  24839. */
  24840. exports._clearMixin = function (sourceVariable) {
  24841. for (var mixinFunction in sourceVariable) {
  24842. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  24843. this[mixinFunction] = undefined;
  24844. }
  24845. }
  24846. };
  24847. /**
  24848. * Mixin the physics system and initialize the parameters required.
  24849. *
  24850. * @private
  24851. */
  24852. exports._loadPhysicsSystem = function () {
  24853. this._loadMixin(PhysicsMixin);
  24854. this._loadSelectedForceSolver();
  24855. if (this.constants.configurePhysics == true) {
  24856. this._loadPhysicsConfiguration();
  24857. }
  24858. };
  24859. /**
  24860. * Mixin the cluster system and initialize the parameters required.
  24861. *
  24862. * @private
  24863. */
  24864. exports._loadClusterSystem = function () {
  24865. this.clusterSession = 0;
  24866. this.hubThreshold = 5;
  24867. this._loadMixin(ClusterMixin);
  24868. };
  24869. /**
  24870. * Mixin the sector system and initialize the parameters required
  24871. *
  24872. * @private
  24873. */
  24874. exports._loadSectorSystem = function () {
  24875. this.sectors = {};
  24876. this.activeSector = ["default"];
  24877. this.sectors["active"] = {};
  24878. this.sectors["active"]["default"] = {"nodes": {},
  24879. "edges": {},
  24880. "nodeIndices": [],
  24881. "formationScale": 1.0,
  24882. "drawingNode": undefined };
  24883. this.sectors["frozen"] = {};
  24884. this.sectors["support"] = {"nodes": {},
  24885. "edges": {},
  24886. "nodeIndices": [],
  24887. "formationScale": 1.0,
  24888. "drawingNode": undefined };
  24889. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  24890. this._loadMixin(SectorsMixin);
  24891. };
  24892. /**
  24893. * Mixin the selection system and initialize the parameters required
  24894. *
  24895. * @private
  24896. */
  24897. exports._loadSelectionSystem = function () {
  24898. this.selectionObj = {nodes: {}, edges: {}};
  24899. this._loadMixin(SelectionMixin);
  24900. };
  24901. /**
  24902. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  24903. *
  24904. * @private
  24905. */
  24906. exports._loadManipulationSystem = function () {
  24907. // reset global variables -- these are used by the selection of nodes and edges.
  24908. this.blockConnectingEdgeSelection = false;
  24909. this.forceAppendSelection = false;
  24910. if (this.constants.dataManipulation.enabled == true) {
  24911. // load the manipulator HTML elements. All styling done in css.
  24912. if (this.manipulationDiv === undefined) {
  24913. this.manipulationDiv = document.createElement('div');
  24914. this.manipulationDiv.className = 'network-manipulationDiv';
  24915. if (this.editMode == true) {
  24916. this.manipulationDiv.style.display = "block";
  24917. }
  24918. else {
  24919. this.manipulationDiv.style.display = "none";
  24920. }
  24921. this.frame.appendChild(this.manipulationDiv);
  24922. }
  24923. if (this.editModeDiv === undefined) {
  24924. this.editModeDiv = document.createElement('div');
  24925. this.editModeDiv.className = 'network-manipulation-editMode';
  24926. if (this.editMode == true) {
  24927. this.editModeDiv.style.display = "none";
  24928. }
  24929. else {
  24930. this.editModeDiv.style.display = "block";
  24931. }
  24932. this.frame.appendChild(this.editModeDiv);
  24933. }
  24934. if (this.closeDiv === undefined) {
  24935. this.closeDiv = document.createElement('div');
  24936. this.closeDiv.className = 'network-manipulation-closeDiv';
  24937. this.closeDiv.style.display = this.manipulationDiv.style.display;
  24938. this.frame.appendChild(this.closeDiv);
  24939. }
  24940. // load the manipulation functions
  24941. this._loadMixin(ManipulationMixin);
  24942. // create the manipulator toolbar
  24943. this._createManipulatorBar();
  24944. }
  24945. else {
  24946. if (this.manipulationDiv !== undefined) {
  24947. // removes all the bindings and overloads
  24948. this._createManipulatorBar();
  24949. // remove the manipulation divs
  24950. this.frame.removeChild(this.manipulationDiv);
  24951. this.frame.removeChild(this.editModeDiv);
  24952. this.frame.removeChild(this.closeDiv);
  24953. this.manipulationDiv = undefined;
  24954. this.editModeDiv = undefined;
  24955. this.closeDiv = undefined;
  24956. // remove the mixin functions
  24957. this._clearMixin(ManipulationMixin);
  24958. }
  24959. }
  24960. };
  24961. /**
  24962. * Mixin the navigation (User Interface) system and initialize the parameters required
  24963. *
  24964. * @private
  24965. */
  24966. exports._loadNavigationControls = function () {
  24967. this._loadMixin(NavigationMixin);
  24968. // the clean function removes the button divs, this is done to remove the bindings.
  24969. this._cleanNavigation();
  24970. if (this.constants.navigation.enabled == true) {
  24971. this._loadNavigationElements();
  24972. }
  24973. };
  24974. /**
  24975. * Mixin the hierarchical layout system.
  24976. *
  24977. * @private
  24978. */
  24979. exports._loadHierarchySystem = function () {
  24980. this._loadMixin(HierarchicalLayoutMixin);
  24981. };
  24982. /***/ },
  24983. /* 60 */
  24984. /***/ function(module, exports, __webpack_require__) {
  24985. // English
  24986. exports['en'] = {
  24987. edit: 'Edit',
  24988. del: 'Delete selected',
  24989. back: 'Back',
  24990. addNode: 'Add Node',
  24991. addEdge: 'Add Edge',
  24992. editNode: 'Edit Node',
  24993. editEdge: 'Edit Edge',
  24994. addDescription: 'Click in an empty space to place a new node.',
  24995. edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
  24996. editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
  24997. createEdgeError: 'Cannot link edges to a cluster.',
  24998. deleteClusterError: 'Clusters cannot be deleted.'
  24999. };
  25000. exports['en_EN'] = exports['en'];
  25001. exports['en_US'] = exports['en'];
  25002. // Dutch
  25003. exports['nl'] = {
  25004. edit: 'Wijzigen',
  25005. del: 'Selectie verwijderen',
  25006. back: 'Terug',
  25007. addNode: 'Node toevoegen',
  25008. addEdge: 'Link toevoegen',
  25009. editNode: 'Node wijzigen',
  25010. editEdge: 'Link wijzigen',
  25011. addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.',
  25012. edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.',
  25013. editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.',
  25014. createEdgeError: 'Kan geen link maken naar een cluster.',
  25015. deleteClusterError: 'Clusters kunnen niet worden verwijderd.'
  25016. };
  25017. exports['nl_NL'] = exports['nl'];
  25018. exports['nl_BE'] = exports['nl'];
  25019. /***/ },
  25020. /* 61 */
  25021. /***/ function(module, exports, __webpack_require__) {
  25022. /**
  25023. * Canvas shapes used by Network
  25024. */
  25025. if (typeof CanvasRenderingContext2D !== 'undefined') {
  25026. /**
  25027. * Draw a circle shape
  25028. */
  25029. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  25030. this.beginPath();
  25031. this.arc(x, y, r, 0, 2*Math.PI, false);
  25032. };
  25033. /**
  25034. * Draw a square shape
  25035. * @param {Number} x horizontal center
  25036. * @param {Number} y vertical center
  25037. * @param {Number} r size, width and height of the square
  25038. */
  25039. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  25040. this.beginPath();
  25041. this.rect(x - r, y - r, r * 2, r * 2);
  25042. };
  25043. /**
  25044. * Draw a triangle shape
  25045. * @param {Number} x horizontal center
  25046. * @param {Number} y vertical center
  25047. * @param {Number} r radius, half the length of the sides of the triangle
  25048. */
  25049. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  25050. // http://en.wikipedia.org/wiki/Equilateral_triangle
  25051. this.beginPath();
  25052. var s = r * 2;
  25053. var s2 = s / 2;
  25054. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  25055. var h = Math.sqrt(s * s - s2 * s2); // height
  25056. this.moveTo(x, y - (h - ir));
  25057. this.lineTo(x + s2, y + ir);
  25058. this.lineTo(x - s2, y + ir);
  25059. this.lineTo(x, y - (h - ir));
  25060. this.closePath();
  25061. };
  25062. /**
  25063. * Draw a triangle shape in downward orientation
  25064. * @param {Number} x horizontal center
  25065. * @param {Number} y vertical center
  25066. * @param {Number} r radius
  25067. */
  25068. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  25069. // http://en.wikipedia.org/wiki/Equilateral_triangle
  25070. this.beginPath();
  25071. var s = r * 2;
  25072. var s2 = s / 2;
  25073. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  25074. var h = Math.sqrt(s * s - s2 * s2); // height
  25075. this.moveTo(x, y + (h - ir));
  25076. this.lineTo(x + s2, y - ir);
  25077. this.lineTo(x - s2, y - ir);
  25078. this.lineTo(x, y + (h - ir));
  25079. this.closePath();
  25080. };
  25081. /**
  25082. * Draw a star shape, a star with 5 points
  25083. * @param {Number} x horizontal center
  25084. * @param {Number} y vertical center
  25085. * @param {Number} r radius, half the length of the sides of the triangle
  25086. */
  25087. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  25088. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  25089. this.beginPath();
  25090. for (var n = 0; n < 10; n++) {
  25091. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  25092. this.lineTo(
  25093. x + radius * Math.sin(n * 2 * Math.PI / 10),
  25094. y - radius * Math.cos(n * 2 * Math.PI / 10)
  25095. );
  25096. }
  25097. this.closePath();
  25098. };
  25099. /**
  25100. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  25101. */
  25102. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  25103. var r2d = Math.PI/180;
  25104. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  25105. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  25106. this.beginPath();
  25107. this.moveTo(x+r,y);
  25108. this.lineTo(x+w-r,y);
  25109. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  25110. this.lineTo(x+w,y+h-r);
  25111. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  25112. this.lineTo(x+r,y+h);
  25113. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  25114. this.lineTo(x,y+r);
  25115. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  25116. };
  25117. /**
  25118. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  25119. */
  25120. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  25121. var kappa = .5522848,
  25122. ox = (w / 2) * kappa, // control point offset horizontal
  25123. oy = (h / 2) * kappa, // control point offset vertical
  25124. xe = x + w, // x-end
  25125. ye = y + h, // y-end
  25126. xm = x + w / 2, // x-middle
  25127. ym = y + h / 2; // y-middle
  25128. this.beginPath();
  25129. this.moveTo(x, ym);
  25130. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  25131. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  25132. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  25133. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  25134. };
  25135. /**
  25136. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  25137. */
  25138. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  25139. var f = 1/3;
  25140. var wEllipse = w;
  25141. var hEllipse = h * f;
  25142. var kappa = .5522848,
  25143. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  25144. oy = (hEllipse / 2) * kappa, // control point offset vertical
  25145. xe = x + wEllipse, // x-end
  25146. ye = y + hEllipse, // y-end
  25147. xm = x + wEllipse / 2, // x-middle
  25148. ym = y + hEllipse / 2, // y-middle
  25149. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  25150. yeb = y + h; // y-end, bottom ellipse
  25151. this.beginPath();
  25152. this.moveTo(xe, ym);
  25153. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  25154. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  25155. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  25156. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  25157. this.lineTo(xe, ymb);
  25158. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  25159. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  25160. this.lineTo(x, ym);
  25161. };
  25162. /**
  25163. * Draw an arrow point (no line)
  25164. */
  25165. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  25166. // tail
  25167. var xt = x - length * Math.cos(angle);
  25168. var yt = y - length * Math.sin(angle);
  25169. // inner tail
  25170. // TODO: allow to customize different shapes
  25171. var xi = x - length * 0.9 * Math.cos(angle);
  25172. var yi = y - length * 0.9 * Math.sin(angle);
  25173. // left
  25174. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  25175. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  25176. // right
  25177. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  25178. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  25179. this.beginPath();
  25180. this.moveTo(x, y);
  25181. this.lineTo(xl, yl);
  25182. this.lineTo(xi, yi);
  25183. this.lineTo(xr, yr);
  25184. this.closePath();
  25185. };
  25186. /**
  25187. * Sets up the dashedLine functionality for drawing
  25188. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  25189. * @author David Jordan
  25190. * @date 2012-08-08
  25191. */
  25192. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  25193. if (!dashArray) dashArray=[10,5];
  25194. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  25195. var dashCount = dashArray.length;
  25196. this.moveTo(x, y);
  25197. var dx = (x2-x), dy = (y2-y);
  25198. var slope = dy/dx;
  25199. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  25200. var dashIndex=0, draw=true;
  25201. while (distRemaining>=0.1){
  25202. var dashLength = dashArray[dashIndex++%dashCount];
  25203. if (dashLength > distRemaining) dashLength = distRemaining;
  25204. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  25205. if (dx<0) xStep = -xStep;
  25206. x += xStep;
  25207. y += slope*xStep;
  25208. this[draw ? 'lineTo' : 'moveTo'](x,y);
  25209. distRemaining -= dashLength;
  25210. draw = !draw;
  25211. }
  25212. };
  25213. // TODO: add diamond shape
  25214. }
  25215. /***/ },
  25216. /* 62 */
  25217. /***/ function(module, exports, __webpack_require__) {
  25218. var util = __webpack_require__(1);
  25219. var RepulsionMixin = __webpack_require__(69);
  25220. var HierarchialRepulsionMixin = __webpack_require__(70);
  25221. var BarnesHutMixin = __webpack_require__(71);
  25222. /**
  25223. * Toggling barnes Hut calculation on and off.
  25224. *
  25225. * @private
  25226. */
  25227. exports._toggleBarnesHut = function () {
  25228. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  25229. this._loadSelectedForceSolver();
  25230. this.moving = true;
  25231. this.start();
  25232. };
  25233. /**
  25234. * This loads the node force solver based on the barnes hut or repulsion algorithm
  25235. *
  25236. * @private
  25237. */
  25238. exports._loadSelectedForceSolver = function () {
  25239. // this overloads the this._calculateNodeForces
  25240. if (this.constants.physics.barnesHut.enabled == true) {
  25241. this._clearMixin(RepulsionMixin);
  25242. this._clearMixin(HierarchialRepulsionMixin);
  25243. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  25244. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  25245. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  25246. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  25247. this._loadMixin(BarnesHutMixin);
  25248. }
  25249. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  25250. this._clearMixin(BarnesHutMixin);
  25251. this._clearMixin(RepulsionMixin);
  25252. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  25253. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  25254. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  25255. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  25256. this._loadMixin(HierarchialRepulsionMixin);
  25257. }
  25258. else {
  25259. this._clearMixin(BarnesHutMixin);
  25260. this._clearMixin(HierarchialRepulsionMixin);
  25261. this.barnesHutTree = undefined;
  25262. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  25263. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  25264. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  25265. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  25266. this._loadMixin(RepulsionMixin);
  25267. }
  25268. };
  25269. /**
  25270. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  25271. * if there is more than one node. If it is just one node, we dont calculate anything.
  25272. *
  25273. * @private
  25274. */
  25275. exports._initializeForceCalculation = function () {
  25276. // stop calculation if there is only one node
  25277. if (this.nodeIndices.length == 1) {
  25278. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  25279. }
  25280. else {
  25281. // if there are too many nodes on screen, we cluster without repositioning
  25282. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  25283. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  25284. }
  25285. // we now start the force calculation
  25286. this._calculateForces();
  25287. }
  25288. };
  25289. /**
  25290. * Calculate the external forces acting on the nodes
  25291. * Forces are caused by: edges, repulsing forces between nodes, gravity
  25292. * @private
  25293. */
  25294. exports._calculateForces = function () {
  25295. // Gravity is required to keep separated groups from floating off
  25296. // the forces are reset to zero in this loop by using _setForce instead
  25297. // of _addForce
  25298. this._calculateGravitationalForces();
  25299. this._calculateNodeForces();
  25300. if (this.constants.physics.springConstant > 0) {
  25301. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  25302. this._calculateSpringForcesWithSupport();
  25303. }
  25304. else {
  25305. if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  25306. this._calculateHierarchicalSpringForces();
  25307. }
  25308. else {
  25309. this._calculateSpringForces();
  25310. }
  25311. }
  25312. }
  25313. };
  25314. /**
  25315. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  25316. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  25317. * This function joins the datanodes and invisible (called support) nodes into one object.
  25318. * We do this so we do not contaminate this.nodes with the support nodes.
  25319. *
  25320. * @private
  25321. */
  25322. exports._updateCalculationNodes = function () {
  25323. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  25324. this.calculationNodes = {};
  25325. this.calculationNodeIndices = [];
  25326. for (var nodeId in this.nodes) {
  25327. if (this.nodes.hasOwnProperty(nodeId)) {
  25328. this.calculationNodes[nodeId] = this.nodes[nodeId];
  25329. }
  25330. }
  25331. var supportNodes = this.sectors['support']['nodes'];
  25332. for (var supportNodeId in supportNodes) {
  25333. if (supportNodes.hasOwnProperty(supportNodeId)) {
  25334. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  25335. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  25336. }
  25337. else {
  25338. supportNodes[supportNodeId]._setForce(0, 0);
  25339. }
  25340. }
  25341. }
  25342. for (var idx in this.calculationNodes) {
  25343. if (this.calculationNodes.hasOwnProperty(idx)) {
  25344. this.calculationNodeIndices.push(idx);
  25345. }
  25346. }
  25347. }
  25348. else {
  25349. this.calculationNodes = this.nodes;
  25350. this.calculationNodeIndices = this.nodeIndices;
  25351. }
  25352. };
  25353. /**
  25354. * this function applies the central gravity effect to keep groups from floating off
  25355. *
  25356. * @private
  25357. */
  25358. exports._calculateGravitationalForces = function () {
  25359. var dx, dy, distance, node, i;
  25360. var nodes = this.calculationNodes;
  25361. var gravity = this.constants.physics.centralGravity;
  25362. var gravityForce = 0;
  25363. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  25364. node = nodes[this.calculationNodeIndices[i]];
  25365. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  25366. // gravity does not apply when we are in a pocket sector
  25367. if (this._sector() == "default" && gravity != 0) {
  25368. dx = -node.x;
  25369. dy = -node.y;
  25370. distance = Math.sqrt(dx * dx + dy * dy);
  25371. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  25372. node.fx = dx * gravityForce;
  25373. node.fy = dy * gravityForce;
  25374. }
  25375. else {
  25376. node.fx = 0;
  25377. node.fy = 0;
  25378. }
  25379. }
  25380. };
  25381. /**
  25382. * this function calculates the effects of the springs in the case of unsmooth curves.
  25383. *
  25384. * @private
  25385. */
  25386. exports._calculateSpringForces = function () {
  25387. var edgeLength, edge, edgeId;
  25388. var dx, dy, fx, fy, springForce, distance;
  25389. var edges = this.edges;
  25390. // forces caused by the edges, modelled as springs
  25391. for (edgeId in edges) {
  25392. if (edges.hasOwnProperty(edgeId)) {
  25393. edge = edges[edgeId];
  25394. if (edge.connected) {
  25395. // only calculate forces if nodes are in the same sector
  25396. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25397. edgeLength = edge.physics.springLength;
  25398. // this implies that the edges between big clusters are longer
  25399. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  25400. dx = (edge.from.x - edge.to.x);
  25401. dy = (edge.from.y - edge.to.y);
  25402. distance = Math.sqrt(dx * dx + dy * dy);
  25403. if (distance == 0) {
  25404. distance = 0.01;
  25405. }
  25406. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25407. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25408. fx = dx * springForce;
  25409. fy = dy * springForce;
  25410. edge.from.fx += fx;
  25411. edge.from.fy += fy;
  25412. edge.to.fx -= fx;
  25413. edge.to.fy -= fy;
  25414. }
  25415. }
  25416. }
  25417. }
  25418. };
  25419. /**
  25420. * This function calculates the springforces on the nodes, accounting for the support nodes.
  25421. *
  25422. * @private
  25423. */
  25424. exports._calculateSpringForcesWithSupport = function () {
  25425. var edgeLength, edge, edgeId, combinedClusterSize;
  25426. var edges = this.edges;
  25427. // forces caused by the edges, modelled as springs
  25428. for (edgeId in edges) {
  25429. if (edges.hasOwnProperty(edgeId)) {
  25430. edge = edges[edgeId];
  25431. if (edge.connected) {
  25432. // only calculate forces if nodes are in the same sector
  25433. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25434. if (edge.via != null) {
  25435. var node1 = edge.to;
  25436. var node2 = edge.via;
  25437. var node3 = edge.from;
  25438. edgeLength = edge.physics.springLength;
  25439. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  25440. // this implies that the edges between big clusters are longer
  25441. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  25442. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  25443. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  25444. }
  25445. }
  25446. }
  25447. }
  25448. }
  25449. };
  25450. /**
  25451. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  25452. *
  25453. * @param node1
  25454. * @param node2
  25455. * @param edgeLength
  25456. * @private
  25457. */
  25458. exports._calculateSpringForce = function (node1, node2, edgeLength) {
  25459. var dx, dy, fx, fy, springForce, distance;
  25460. dx = (node1.x - node2.x);
  25461. dy = (node1.y - node2.y);
  25462. distance = Math.sqrt(dx * dx + dy * dy);
  25463. if (distance == 0) {
  25464. distance = 0.01;
  25465. }
  25466. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25467. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25468. fx = dx * springForce;
  25469. fy = dy * springForce;
  25470. node1.fx += fx;
  25471. node1.fy += fy;
  25472. node2.fx -= fx;
  25473. node2.fy -= fy;
  25474. };
  25475. /**
  25476. * Load the HTML for the physics config and bind it
  25477. * @private
  25478. */
  25479. exports._loadPhysicsConfiguration = function () {
  25480. if (this.physicsConfiguration === undefined) {
  25481. this.backupConstants = {};
  25482. util.deepExtend(this.backupConstants,this.constants);
  25483. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  25484. this.physicsConfiguration = document.createElement('div');
  25485. this.physicsConfiguration.className = "PhysicsConfiguration";
  25486. this.physicsConfiguration.innerHTML = '' +
  25487. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  25488. '<tr>' +
  25489. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  25490. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  25491. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  25492. '</tr>' +
  25493. '</table>' +
  25494. '<table id="graph_BH_table" style="display:none">' +
  25495. '<tr><td><b>Barnes Hut</b></td></tr>' +
  25496. '<tr>' +
  25497. '<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>' +
  25498. '</tr>' +
  25499. '<tr>' +
  25500. '<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>' +
  25501. '</tr>' +
  25502. '<tr>' +
  25503. '<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>' +
  25504. '</tr>' +
  25505. '<tr>' +
  25506. '<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>' +
  25507. '</tr>' +
  25508. '<tr>' +
  25509. '<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>' +
  25510. '</tr>' +
  25511. '</table>' +
  25512. '<table id="graph_R_table" style="display:none">' +
  25513. '<tr><td><b>Repulsion</b></td></tr>' +
  25514. '<tr>' +
  25515. '<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>' +
  25516. '</tr>' +
  25517. '<tr>' +
  25518. '<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>' +
  25519. '</tr>' +
  25520. '<tr>' +
  25521. '<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>' +
  25522. '</tr>' +
  25523. '<tr>' +
  25524. '<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>' +
  25525. '</tr>' +
  25526. '<tr>' +
  25527. '<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>' +
  25528. '</tr>' +
  25529. '</table>' +
  25530. '<table id="graph_H_table" style="display:none">' +
  25531. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  25532. '<tr>' +
  25533. '<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>' +
  25534. '</tr>' +
  25535. '<tr>' +
  25536. '<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>' +
  25537. '</tr>' +
  25538. '<tr>' +
  25539. '<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>' +
  25540. '</tr>' +
  25541. '<tr>' +
  25542. '<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>' +
  25543. '</tr>' +
  25544. '<tr>' +
  25545. '<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>' +
  25546. '</tr>' +
  25547. '<tr>' +
  25548. '<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>' +
  25549. '</tr>' +
  25550. '<tr>' +
  25551. '<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>' +
  25552. '</tr>' +
  25553. '<tr>' +
  25554. '<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>' +
  25555. '</tr>' +
  25556. '</table>' +
  25557. '<table><tr><td><b>Options:</b></td></tr>' +
  25558. '<tr>' +
  25559. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  25560. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  25561. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  25562. '</tr>' +
  25563. '</table>'
  25564. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  25565. this.optionsDiv = document.createElement("div");
  25566. this.optionsDiv.style.fontSize = "14px";
  25567. this.optionsDiv.style.fontFamily = "verdana";
  25568. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  25569. var rangeElement;
  25570. rangeElement = document.getElementById('graph_BH_gc');
  25571. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  25572. rangeElement = document.getElementById('graph_BH_cg');
  25573. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  25574. rangeElement = document.getElementById('graph_BH_sc');
  25575. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  25576. rangeElement = document.getElementById('graph_BH_sl');
  25577. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  25578. rangeElement = document.getElementById('graph_BH_damp');
  25579. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  25580. rangeElement = document.getElementById('graph_R_nd');
  25581. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  25582. rangeElement = document.getElementById('graph_R_cg');
  25583. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  25584. rangeElement = document.getElementById('graph_R_sc');
  25585. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  25586. rangeElement = document.getElementById('graph_R_sl');
  25587. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  25588. rangeElement = document.getElementById('graph_R_damp');
  25589. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  25590. rangeElement = document.getElementById('graph_H_nd');
  25591. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  25592. rangeElement = document.getElementById('graph_H_cg');
  25593. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  25594. rangeElement = document.getElementById('graph_H_sc');
  25595. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  25596. rangeElement = document.getElementById('graph_H_sl');
  25597. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  25598. rangeElement = document.getElementById('graph_H_damp');
  25599. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  25600. rangeElement = document.getElementById('graph_H_direction');
  25601. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  25602. rangeElement = document.getElementById('graph_H_levsep');
  25603. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  25604. rangeElement = document.getElementById('graph_H_nspac');
  25605. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  25606. var radioButton1 = document.getElementById("graph_physicsMethod1");
  25607. var radioButton2 = document.getElementById("graph_physicsMethod2");
  25608. var radioButton3 = document.getElementById("graph_physicsMethod3");
  25609. radioButton2.checked = true;
  25610. if (this.constants.physics.barnesHut.enabled) {
  25611. radioButton1.checked = true;
  25612. }
  25613. if (this.constants.hierarchicalLayout.enabled) {
  25614. radioButton3.checked = true;
  25615. }
  25616. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  25617. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  25618. var graph_generateOptions = document.getElementById("graph_generateOptions");
  25619. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  25620. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  25621. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  25622. if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) {
  25623. graph_toggleSmooth.style.background = "#A4FF56";
  25624. }
  25625. else {
  25626. graph_toggleSmooth.style.background = "#FF8532";
  25627. }
  25628. switchConfigurations.apply(this);
  25629. radioButton1.onchange = switchConfigurations.bind(this);
  25630. radioButton2.onchange = switchConfigurations.bind(this);
  25631. radioButton3.onchange = switchConfigurations.bind(this);
  25632. }
  25633. };
  25634. /**
  25635. * This overwrites the this.constants.
  25636. *
  25637. * @param constantsVariableName
  25638. * @param value
  25639. * @private
  25640. */
  25641. exports._overWriteGraphConstants = function (constantsVariableName, value) {
  25642. var nameArray = constantsVariableName.split("_");
  25643. if (nameArray.length == 1) {
  25644. this.constants[nameArray[0]] = value;
  25645. }
  25646. else if (nameArray.length == 2) {
  25647. this.constants[nameArray[0]][nameArray[1]] = value;
  25648. }
  25649. else if (nameArray.length == 3) {
  25650. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  25651. }
  25652. };
  25653. /**
  25654. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  25655. */
  25656. function graphToggleSmoothCurves () {
  25657. this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled;
  25658. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  25659. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  25660. else {graph_toggleSmooth.style.background = "#FF8532";}
  25661. this._configureSmoothCurves(false);
  25662. }
  25663. /**
  25664. * this function is used to scramble the nodes
  25665. *
  25666. */
  25667. function graphRepositionNodes () {
  25668. for (var nodeId in this.calculationNodes) {
  25669. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  25670. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  25671. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  25672. }
  25673. }
  25674. if (this.constants.hierarchicalLayout.enabled == true) {
  25675. this._setupHierarchicalLayout();
  25676. showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  25677. showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity");
  25678. showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant");
  25679. showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength");
  25680. showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping");
  25681. }
  25682. else {
  25683. this.repositionNodes();
  25684. }
  25685. this.moving = true;
  25686. this.start();
  25687. }
  25688. /**
  25689. * this is used to generate an options file from the playing with physics system.
  25690. */
  25691. function graphGenerateOptions () {
  25692. var options = "No options are required, default values used.";
  25693. var optionsSpecific = [];
  25694. var radioButton1 = document.getElementById("graph_physicsMethod1");
  25695. var radioButton2 = document.getElementById("graph_physicsMethod2");
  25696. if (radioButton1.checked == true) {
  25697. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  25698. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  25699. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  25700. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  25701. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  25702. if (optionsSpecific.length != 0) {
  25703. options = "var options = {";
  25704. options += "physics: {barnesHut: {";
  25705. for (var i = 0; i < optionsSpecific.length; i++) {
  25706. options += optionsSpecific[i];
  25707. if (i < optionsSpecific.length - 1) {
  25708. options += ", "
  25709. }
  25710. }
  25711. options += '}}'
  25712. }
  25713. if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {
  25714. if (optionsSpecific.length == 0) {options = "var options = {";}
  25715. else {options += ", "}
  25716. options += "smoothCurves: " + this.constants.smoothCurves.enabled;
  25717. }
  25718. if (options != "No options are required, default values used.") {
  25719. options += '};'
  25720. }
  25721. }
  25722. else if (radioButton2.checked == true) {
  25723. options = "var options = {";
  25724. options += "physics: {barnesHut: {enabled: false}";
  25725. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  25726. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  25727. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  25728. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  25729. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  25730. if (optionsSpecific.length != 0) {
  25731. options += ", repulsion: {";
  25732. for (var i = 0; i < optionsSpecific.length; i++) {
  25733. options += optionsSpecific[i];
  25734. if (i < optionsSpecific.length - 1) {
  25735. options += ", "
  25736. }
  25737. }
  25738. options += '}}'
  25739. }
  25740. if (optionsSpecific.length == 0) {options += "}"}
  25741. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  25742. options += ", smoothCurves: " + this.constants.smoothCurves;
  25743. }
  25744. options += '};'
  25745. }
  25746. else {
  25747. options = "var options = {";
  25748. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  25749. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  25750. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  25751. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  25752. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  25753. if (optionsSpecific.length != 0) {
  25754. options += "physics: {hierarchicalRepulsion: {";
  25755. for (var i = 0; i < optionsSpecific.length; i++) {
  25756. options += optionsSpecific[i];
  25757. if (i < optionsSpecific.length - 1) {
  25758. options += ", ";
  25759. }
  25760. }
  25761. options += '}},';
  25762. }
  25763. options += 'hierarchicalLayout: {';
  25764. optionsSpecific = [];
  25765. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  25766. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  25767. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  25768. if (optionsSpecific.length != 0) {
  25769. for (var i = 0; i < optionsSpecific.length; i++) {
  25770. options += optionsSpecific[i];
  25771. if (i < optionsSpecific.length - 1) {
  25772. options += ", "
  25773. }
  25774. }
  25775. options += '}'
  25776. }
  25777. else {
  25778. options += "enabled:true}";
  25779. }
  25780. options += '};'
  25781. }
  25782. this.optionsDiv.innerHTML = options;
  25783. }
  25784. /**
  25785. * this is used to switch between barnesHut, repulsion and hierarchical.
  25786. *
  25787. */
  25788. function switchConfigurations () {
  25789. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  25790. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  25791. var tableId = "graph_" + radioButton + "_table";
  25792. var table = document.getElementById(tableId);
  25793. table.style.display = "block";
  25794. for (var i = 0; i < ids.length; i++) {
  25795. if (ids[i] != tableId) {
  25796. table = document.getElementById(ids[i]);
  25797. table.style.display = "none";
  25798. }
  25799. }
  25800. this._restoreNodes();
  25801. if (radioButton == "R") {
  25802. this.constants.hierarchicalLayout.enabled = false;
  25803. this.constants.physics.hierarchicalRepulsion.enabled = false;
  25804. this.constants.physics.barnesHut.enabled = false;
  25805. }
  25806. else if (radioButton == "H") {
  25807. if (this.constants.hierarchicalLayout.enabled == false) {
  25808. this.constants.hierarchicalLayout.enabled = true;
  25809. this.constants.physics.hierarchicalRepulsion.enabled = true;
  25810. this.constants.physics.barnesHut.enabled = false;
  25811. this.constants.smoothCurves.enabled = false;
  25812. this._setupHierarchicalLayout();
  25813. }
  25814. }
  25815. else {
  25816. this.constants.hierarchicalLayout.enabled = false;
  25817. this.constants.physics.hierarchicalRepulsion.enabled = false;
  25818. this.constants.physics.barnesHut.enabled = true;
  25819. }
  25820. this._loadSelectedForceSolver();
  25821. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  25822. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  25823. else {graph_toggleSmooth.style.background = "#FF8532";}
  25824. this.moving = true;
  25825. this.start();
  25826. }
  25827. /**
  25828. * this generates the ranges depending on the iniital values.
  25829. *
  25830. * @param id
  25831. * @param map
  25832. * @param constantsVariableName
  25833. */
  25834. function showValueOfRange (id,map,constantsVariableName) {
  25835. var valueId = id + "_value";
  25836. var rangeValue = document.getElementById(id).value;
  25837. if (Array.isArray(map)) {
  25838. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  25839. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  25840. }
  25841. else {
  25842. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  25843. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  25844. }
  25845. if (constantsVariableName == "hierarchicalLayout_direction" ||
  25846. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  25847. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  25848. this._setupHierarchicalLayout();
  25849. }
  25850. this.moving = true;
  25851. this.start();
  25852. }
  25853. /***/ },
  25854. /* 63 */
  25855. /***/ function(module, exports, __webpack_require__) {
  25856. /**
  25857. * Creation of the ClusterMixin var.
  25858. *
  25859. * This contains all the functions the Network object can use to employ clustering
  25860. */
  25861. /**
  25862. * This is only called in the constructor of the network object
  25863. *
  25864. */
  25865. exports.startWithClustering = function() {
  25866. // cluster if the data set is big
  25867. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  25868. // updates the lables after clustering
  25869. this.updateLabels();
  25870. // this is called here because if clusterin is disabled, the start and stabilize are called in
  25871. // the setData function.
  25872. if (this.stabilize) {
  25873. this._stabilize();
  25874. }
  25875. this.start();
  25876. };
  25877. /**
  25878. * This function clusters until the initialMaxNodes has been reached
  25879. *
  25880. * @param {Number} maxNumberOfNodes
  25881. * @param {Boolean} reposition
  25882. */
  25883. exports.clusterToFit = function(maxNumberOfNodes, reposition) {
  25884. var numberOfNodes = this.nodeIndices.length;
  25885. var maxLevels = 50;
  25886. var level = 0;
  25887. // we first cluster the hubs, then we pull in the outliers, repeat
  25888. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  25889. if (level % 3 == 0) {
  25890. this.forceAggregateHubs(true);
  25891. this.normalizeClusterLevels();
  25892. }
  25893. else {
  25894. this.increaseClusterLevel(); // this also includes a cluster normalization
  25895. }
  25896. numberOfNodes = this.nodeIndices.length;
  25897. level += 1;
  25898. }
  25899. // after the clustering we reposition the nodes to reduce the initial chaos
  25900. if (level > 0 && reposition == true) {
  25901. this.repositionNodes();
  25902. }
  25903. this._updateCalculationNodes();
  25904. };
  25905. /**
  25906. * This function can be called to open up a specific cluster. It is only called by
  25907. * It will unpack the cluster back one level.
  25908. *
  25909. * @param node | Node object: cluster to open.
  25910. */
  25911. exports.openCluster = function(node) {
  25912. var isMovingBeforeClustering = this.moving;
  25913. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  25914. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  25915. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  25916. this._addSector(node);
  25917. var level = 0;
  25918. // we decluster until we reach a decent number of nodes
  25919. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  25920. this.decreaseClusterLevel();
  25921. level += 1;
  25922. }
  25923. }
  25924. else {
  25925. this._expandClusterNode(node,false,true);
  25926. // update the index list, dynamic edges and labels
  25927. this._updateNodeIndexList();
  25928. this._updateDynamicEdges();
  25929. this._updateCalculationNodes();
  25930. this.updateLabels();
  25931. }
  25932. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  25933. if (this.moving != isMovingBeforeClustering) {
  25934. this.start();
  25935. }
  25936. };
  25937. /**
  25938. * This calls the updateClustes with default arguments
  25939. */
  25940. exports.updateClustersDefault = function() {
  25941. if (this.constants.clustering.enabled == true) {
  25942. this.updateClusters(0,false,false);
  25943. }
  25944. };
  25945. /**
  25946. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  25947. * be clustered with their connected node. This can be repeated as many times as needed.
  25948. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  25949. */
  25950. exports.increaseClusterLevel = function() {
  25951. this.updateClusters(-1,false,true);
  25952. };
  25953. /**
  25954. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  25955. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  25956. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  25957. */
  25958. exports.decreaseClusterLevel = function() {
  25959. this.updateClusters(1,false,true);
  25960. };
  25961. /**
  25962. * This is the main clustering function. It clusters and declusters on zoom or forced
  25963. * This function clusters on zoom, it can be called with a predefined zoom direction
  25964. * If out, check if we can form clusters, if in, check if we can open clusters.
  25965. * This function is only called from _zoom()
  25966. *
  25967. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  25968. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  25969. * @param {Boolean} force | enabled or disable forcing
  25970. * @param {Boolean} doNotStart | if true do not call start
  25971. *
  25972. */
  25973. exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) {
  25974. var isMovingBeforeClustering = this.moving;
  25975. var amountOfNodes = this.nodeIndices.length;
  25976. // on zoom out collapse the sector if the scale is at the level the sector was made
  25977. if (this.previousScale > this.scale && zoomDirection == 0) {
  25978. this._collapseSector();
  25979. }
  25980. // check if we zoom in or out
  25981. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  25982. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  25983. // outer nodes determines if it is being clustered
  25984. this._formClusters(force);
  25985. }
  25986. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  25987. if (force == true) {
  25988. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  25989. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  25990. this._openClusters(recursive,force);
  25991. }
  25992. else {
  25993. // if a cluster takes up a set percentage of the active window
  25994. this._openClustersBySize();
  25995. }
  25996. }
  25997. this._updateNodeIndexList();
  25998. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  25999. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  26000. this._aggregateHubs(force);
  26001. this._updateNodeIndexList();
  26002. }
  26003. // we now reduce chains.
  26004. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  26005. this.handleChains();
  26006. this._updateNodeIndexList();
  26007. }
  26008. this.previousScale = this.scale;
  26009. // rest of the update the index list, dynamic edges and labels
  26010. this._updateDynamicEdges();
  26011. this.updateLabels();
  26012. // if a cluster was formed, we increase the clusterSession
  26013. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  26014. this.clusterSession += 1;
  26015. // if clusters have been made, we normalize the cluster level
  26016. this.normalizeClusterLevels();
  26017. }
  26018. if (doNotStart == false || doNotStart === undefined) {
  26019. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  26020. if (this.moving != isMovingBeforeClustering) {
  26021. this.start();
  26022. }
  26023. }
  26024. this._updateCalculationNodes();
  26025. };
  26026. /**
  26027. * This function handles the chains. It is called on every updateClusters().
  26028. */
  26029. exports.handleChains = function() {
  26030. // after clustering we check how many chains there are
  26031. var chainPercentage = this._getChainFraction();
  26032. if (chainPercentage > this.constants.clustering.chainThreshold) {
  26033. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  26034. }
  26035. };
  26036. /**
  26037. * this functions starts clustering by hubs
  26038. * The minimum hub threshold is set globally
  26039. *
  26040. * @private
  26041. */
  26042. exports._aggregateHubs = function(force) {
  26043. this._getHubSize();
  26044. this._formClustersByHub(force,false);
  26045. };
  26046. /**
  26047. * This function is fired by keypress. It forces hubs to form.
  26048. *
  26049. */
  26050. exports.forceAggregateHubs = function(doNotStart) {
  26051. var isMovingBeforeClustering = this.moving;
  26052. var amountOfNodes = this.nodeIndices.length;
  26053. this._aggregateHubs(true);
  26054. // update the index list, dynamic edges and labels
  26055. this._updateNodeIndexList();
  26056. this._updateDynamicEdges();
  26057. this.updateLabels();
  26058. // if a cluster was formed, we increase the clusterSession
  26059. if (this.nodeIndices.length != amountOfNodes) {
  26060. this.clusterSession += 1;
  26061. }
  26062. if (doNotStart == false || doNotStart === undefined) {
  26063. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  26064. if (this.moving != isMovingBeforeClustering) {
  26065. this.start();
  26066. }
  26067. }
  26068. };
  26069. /**
  26070. * If a cluster takes up more than a set percentage of the screen, open the cluster
  26071. *
  26072. * @private
  26073. */
  26074. exports._openClustersBySize = function() {
  26075. for (var nodeId in this.nodes) {
  26076. if (this.nodes.hasOwnProperty(nodeId)) {
  26077. var node = this.nodes[nodeId];
  26078. if (node.inView() == true) {
  26079. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  26080. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  26081. this.openCluster(node);
  26082. }
  26083. }
  26084. }
  26085. }
  26086. };
  26087. /**
  26088. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  26089. * has to be opened based on the current zoom level.
  26090. *
  26091. * @private
  26092. */
  26093. exports._openClusters = function(recursive,force) {
  26094. for (var i = 0; i < this.nodeIndices.length; i++) {
  26095. var node = this.nodes[this.nodeIndices[i]];
  26096. this._expandClusterNode(node,recursive,force);
  26097. this._updateCalculationNodes();
  26098. }
  26099. };
  26100. /**
  26101. * This function checks if a node has to be opened. This is done by checking the zoom level.
  26102. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  26103. * This recursive behaviour is optional and can be set by the recursive argument.
  26104. *
  26105. * @param {Node} parentNode | to check for cluster and expand
  26106. * @param {Boolean} recursive | enabled or disable recursive calling
  26107. * @param {Boolean} force | enabled or disable forcing
  26108. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  26109. * @private
  26110. */
  26111. exports._expandClusterNode = function(parentNode, recursive, force, openAll) {
  26112. // first check if node is a cluster
  26113. if (parentNode.clusterSize > 1) {
  26114. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  26115. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  26116. openAll = true;
  26117. }
  26118. recursive = openAll ? true : recursive;
  26119. // if the last child has been added on a smaller scale than current scale decluster
  26120. if (parentNode.formationScale < this.scale || force == true) {
  26121. // we will check if any of the contained child nodes should be removed from the cluster
  26122. for (var containedNodeId in parentNode.containedNodes) {
  26123. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  26124. var childNode = parentNode.containedNodes[containedNodeId];
  26125. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  26126. // the largest cluster is the one that comes from outside
  26127. if (force == true) {
  26128. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  26129. || openAll) {
  26130. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  26131. }
  26132. }
  26133. else {
  26134. if (this._nodeInActiveArea(parentNode)) {
  26135. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  26136. }
  26137. }
  26138. }
  26139. }
  26140. }
  26141. }
  26142. };
  26143. /**
  26144. * ONLY CALLED FROM _expandClusterNode
  26145. *
  26146. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  26147. * the child node from the parent contained_node object and put it back into the global nodes object.
  26148. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  26149. *
  26150. * @param {Node} parentNode | the parent node
  26151. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  26152. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  26153. * With force and recursive both true, the entire cluster is unpacked
  26154. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  26155. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  26156. * @private
  26157. */
  26158. exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) {
  26159. var childNode = parentNode.containedNodes[containedNodeId];
  26160. // if child node has been added on smaller scale than current, kick out
  26161. if (childNode.formationScale < this.scale || force == true) {
  26162. // unselect all selected items
  26163. this._unselectAll();
  26164. // put the child node back in the global nodes object
  26165. this.nodes[containedNodeId] = childNode;
  26166. // release the contained edges from this childNode back into the global edges
  26167. this._releaseContainedEdges(parentNode,childNode);
  26168. // reconnect rerouted edges to the childNode
  26169. this._connectEdgeBackToChild(parentNode,childNode);
  26170. // validate all edges in dynamicEdges
  26171. this._validateEdges(parentNode);
  26172. // undo the changes from the clustering operation on the parent node
  26173. parentNode.options.mass -= childNode.options.mass;
  26174. parentNode.clusterSize -= childNode.clusterSize;
  26175. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*(parentNode.clusterSize-1));
  26176. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  26177. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  26178. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  26179. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  26180. // remove node from the list
  26181. delete parentNode.containedNodes[containedNodeId];
  26182. // check if there are other childs with this clusterSession in the parent.
  26183. var othersPresent = false;
  26184. for (var childNodeId in parentNode.containedNodes) {
  26185. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  26186. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  26187. othersPresent = true;
  26188. break;
  26189. }
  26190. }
  26191. }
  26192. // if there are no others, remove the cluster session from the list
  26193. if (othersPresent == false) {
  26194. parentNode.clusterSessions.pop();
  26195. }
  26196. this._repositionBezierNodes(childNode);
  26197. // this._repositionBezierNodes(parentNode);
  26198. // remove the clusterSession from the child node
  26199. childNode.clusterSession = 0;
  26200. // recalculate the size of the node on the next time the node is rendered
  26201. parentNode.clearSizeCache();
  26202. // restart the simulation to reorganise all nodes
  26203. this.moving = true;
  26204. }
  26205. // check if a further expansion step is possible if recursivity is enabled
  26206. if (recursive == true) {
  26207. this._expandClusterNode(childNode,recursive,force,openAll);
  26208. }
  26209. };
  26210. /**
  26211. * position the bezier nodes at the center of the edges
  26212. *
  26213. * @param node
  26214. * @private
  26215. */
  26216. exports._repositionBezierNodes = function(node) {
  26217. for (var i = 0; i < node.dynamicEdges.length; i++) {
  26218. node.dynamicEdges[i].positionBezierNode();
  26219. }
  26220. };
  26221. /**
  26222. * This function checks if any nodes at the end of their trees have edges below a threshold length
  26223. * This function is called only from updateClusters()
  26224. * forceLevelCollapse ignores the length of the edge and collapses one level
  26225. * This means that a node with only one edge will be clustered with its connected node
  26226. *
  26227. * @private
  26228. * @param {Boolean} force
  26229. */
  26230. exports._formClusters = function(force) {
  26231. if (force == false) {
  26232. this._formClustersByZoom();
  26233. }
  26234. else {
  26235. this._forceClustersByZoom();
  26236. }
  26237. };
  26238. /**
  26239. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  26240. *
  26241. * @private
  26242. */
  26243. exports._formClustersByZoom = function() {
  26244. var dx,dy,length,
  26245. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  26246. // check if any edges are shorter than minLength and start the clustering
  26247. // the clustering favours the node with the larger mass
  26248. for (var edgeId in this.edges) {
  26249. if (this.edges.hasOwnProperty(edgeId)) {
  26250. var edge = this.edges[edgeId];
  26251. if (edge.connected) {
  26252. if (edge.toId != edge.fromId) {
  26253. dx = (edge.to.x - edge.from.x);
  26254. dy = (edge.to.y - edge.from.y);
  26255. length = Math.sqrt(dx * dx + dy * dy);
  26256. if (length < minLength) {
  26257. // first check which node is larger
  26258. var parentNode = edge.from;
  26259. var childNode = edge.to;
  26260. if (edge.to.options.mass > edge.from.options.mass) {
  26261. parentNode = edge.to;
  26262. childNode = edge.from;
  26263. }
  26264. if (childNode.dynamicEdgesLength == 1) {
  26265. this._addToCluster(parentNode,childNode,false);
  26266. }
  26267. else if (parentNode.dynamicEdgesLength == 1) {
  26268. this._addToCluster(childNode,parentNode,false);
  26269. }
  26270. }
  26271. }
  26272. }
  26273. }
  26274. }
  26275. };
  26276. /**
  26277. * This function forces the network to cluster all nodes with only one connecting edge to their
  26278. * connected node.
  26279. *
  26280. * @private
  26281. */
  26282. exports._forceClustersByZoom = function() {
  26283. for (var nodeId in this.nodes) {
  26284. // another node could have absorbed this child.
  26285. if (this.nodes.hasOwnProperty(nodeId)) {
  26286. var childNode = this.nodes[nodeId];
  26287. // the edges can be swallowed by another decrease
  26288. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  26289. var edge = childNode.dynamicEdges[0];
  26290. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  26291. // group to the largest node
  26292. if (childNode.id != parentNode.id) {
  26293. if (parentNode.options.mass > childNode.options.mass) {
  26294. this._addToCluster(parentNode,childNode,true);
  26295. }
  26296. else {
  26297. this._addToCluster(childNode,parentNode,true);
  26298. }
  26299. }
  26300. }
  26301. }
  26302. }
  26303. };
  26304. /**
  26305. * To keep the nodes of roughly equal size we normalize the cluster levels.
  26306. * This function clusters a node to its smallest connected neighbour.
  26307. *
  26308. * @param node
  26309. * @private
  26310. */
  26311. exports._clusterToSmallestNeighbour = function(node) {
  26312. var smallestNeighbour = -1;
  26313. var smallestNeighbourNode = null;
  26314. for (var i = 0; i < node.dynamicEdges.length; i++) {
  26315. if (node.dynamicEdges[i] !== undefined) {
  26316. var neighbour = null;
  26317. if (node.dynamicEdges[i].fromId != node.id) {
  26318. neighbour = node.dynamicEdges[i].from;
  26319. }
  26320. else if (node.dynamicEdges[i].toId != node.id) {
  26321. neighbour = node.dynamicEdges[i].to;
  26322. }
  26323. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  26324. smallestNeighbour = neighbour.clusterSessions.length;
  26325. smallestNeighbourNode = neighbour;
  26326. }
  26327. }
  26328. }
  26329. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  26330. this._addToCluster(neighbour, node, true);
  26331. }
  26332. };
  26333. /**
  26334. * This function forms clusters from hubs, it loops over all nodes
  26335. *
  26336. * @param {Boolean} force | Disregard zoom level
  26337. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  26338. * @private
  26339. */
  26340. exports._formClustersByHub = function(force, onlyEqual) {
  26341. // we loop over all nodes in the list
  26342. for (var nodeId in this.nodes) {
  26343. // we check if it is still available since it can be used by the clustering in this loop
  26344. if (this.nodes.hasOwnProperty(nodeId)) {
  26345. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  26346. }
  26347. }
  26348. };
  26349. /**
  26350. * This function forms a cluster from a specific preselected hub node
  26351. *
  26352. * @param {Node} hubNode | the node we will cluster as a hub
  26353. * @param {Boolean} force | Disregard zoom level
  26354. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  26355. * @param {Number} [absorptionSizeOffset] |
  26356. * @private
  26357. */
  26358. exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  26359. if (absorptionSizeOffset === undefined) {
  26360. absorptionSizeOffset = 0;
  26361. }
  26362. // we decide if the node is a hub
  26363. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  26364. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  26365. // initialize variables
  26366. var dx,dy,length;
  26367. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  26368. var allowCluster = false;
  26369. // we create a list of edges because the dynamicEdges change over the course of this loop
  26370. var edgesIdarray = [];
  26371. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  26372. for (var j = 0; j < amountOfInitialEdges; j++) {
  26373. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  26374. }
  26375. // if the hub clustering is not forces, we check if one of the edges connected
  26376. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  26377. if (force == false) {
  26378. allowCluster = false;
  26379. for (j = 0; j < amountOfInitialEdges; j++) {
  26380. var edge = this.edges[edgesIdarray[j]];
  26381. if (edge !== undefined) {
  26382. if (edge.connected) {
  26383. if (edge.toId != edge.fromId) {
  26384. dx = (edge.to.x - edge.from.x);
  26385. dy = (edge.to.y - edge.from.y);
  26386. length = Math.sqrt(dx * dx + dy * dy);
  26387. if (length < minLength) {
  26388. allowCluster = true;
  26389. break;
  26390. }
  26391. }
  26392. }
  26393. }
  26394. }
  26395. }
  26396. // start the clustering if allowed
  26397. if ((!force && allowCluster) || force) {
  26398. // we loop over all edges INITIALLY connected to this hub
  26399. for (j = 0; j < amountOfInitialEdges; j++) {
  26400. edge = this.edges[edgesIdarray[j]];
  26401. // the edge can be clustered by this function in a previous loop
  26402. if (edge !== undefined) {
  26403. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  26404. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  26405. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  26406. (childNode.id != hubNode.id)) {
  26407. this._addToCluster(hubNode,childNode,force);
  26408. }
  26409. }
  26410. }
  26411. }
  26412. }
  26413. };
  26414. /**
  26415. * This function adds the child node to the parent node, creating a cluster if it is not already.
  26416. *
  26417. * @param {Node} parentNode | this is the node that will house the child node
  26418. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  26419. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  26420. * @private
  26421. */
  26422. exports._addToCluster = function(parentNode, childNode, force) {
  26423. // join child node in the parent node
  26424. parentNode.containedNodes[childNode.id] = childNode;
  26425. // manage all the edges connected to the child and parent nodes
  26426. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  26427. var edge = childNode.dynamicEdges[i];
  26428. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  26429. this._addToContainedEdges(parentNode,childNode,edge);
  26430. }
  26431. else {
  26432. this._connectEdgeToCluster(parentNode,childNode,edge);
  26433. }
  26434. }
  26435. // a contained node has no dynamic edges.
  26436. childNode.dynamicEdges = [];
  26437. // remove circular edges from clusters
  26438. this._containCircularEdgesFromNode(parentNode,childNode);
  26439. // remove the childNode from the global nodes object
  26440. delete this.nodes[childNode.id];
  26441. // update the properties of the child and parent
  26442. var massBefore = parentNode.options.mass;
  26443. childNode.clusterSession = this.clusterSession;
  26444. parentNode.options.mass += childNode.options.mass;
  26445. parentNode.clusterSize += childNode.clusterSize;
  26446. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  26447. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  26448. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  26449. parentNode.clusterSessions.push(this.clusterSession);
  26450. }
  26451. // forced clusters only open from screen size and double tap
  26452. if (force == true) {
  26453. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  26454. parentNode.formationScale = 0;
  26455. }
  26456. else {
  26457. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  26458. }
  26459. // recalculate the size of the node on the next time the node is rendered
  26460. parentNode.clearSizeCache();
  26461. // set the pop-out scale for the childnode
  26462. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  26463. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  26464. childNode.clearVelocity();
  26465. // the mass has altered, preservation of energy dictates the velocity to be updated
  26466. parentNode.updateVelocity(massBefore);
  26467. // restart the simulation to reorganise all nodes
  26468. this.moving = true;
  26469. };
  26470. /**
  26471. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  26472. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  26473. * It has to be called if a level is collapsed. It is called by _formClusters().
  26474. * @private
  26475. */
  26476. exports._updateDynamicEdges = function() {
  26477. for (var i = 0; i < this.nodeIndices.length; i++) {
  26478. var node = this.nodes[this.nodeIndices[i]];
  26479. node.dynamicEdgesLength = node.dynamicEdges.length;
  26480. // this corrects for multiple edges pointing at the same other node
  26481. var correction = 0;
  26482. if (node.dynamicEdgesLength > 1) {
  26483. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  26484. var edgeToId = node.dynamicEdges[j].toId;
  26485. var edgeFromId = node.dynamicEdges[j].fromId;
  26486. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  26487. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  26488. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  26489. correction += 1;
  26490. }
  26491. }
  26492. }
  26493. }
  26494. node.dynamicEdgesLength -= correction;
  26495. }
  26496. };
  26497. /**
  26498. * This adds an edge from the childNode to the contained edges of the parent node
  26499. *
  26500. * @param parentNode | Node object
  26501. * @param childNode | Node object
  26502. * @param edge | Edge object
  26503. * @private
  26504. */
  26505. exports._addToContainedEdges = function(parentNode, childNode, edge) {
  26506. // create an array object if it does not yet exist for this childNode
  26507. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  26508. parentNode.containedEdges[childNode.id] = []
  26509. }
  26510. // add this edge to the list
  26511. parentNode.containedEdges[childNode.id].push(edge);
  26512. // remove the edge from the global edges object
  26513. delete this.edges[edge.id];
  26514. // remove the edge from the parent object
  26515. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26516. if (parentNode.dynamicEdges[i].id == edge.id) {
  26517. parentNode.dynamicEdges.splice(i,1);
  26518. break;
  26519. }
  26520. }
  26521. };
  26522. /**
  26523. * This function connects an edge that was connected to a child node to the parent node.
  26524. * It keeps track of which nodes it has been connected to with the originalId array.
  26525. *
  26526. * @param {Node} parentNode | Node object
  26527. * @param {Node} childNode | Node object
  26528. * @param {Edge} edge | Edge object
  26529. * @private
  26530. */
  26531. exports._connectEdgeToCluster = function(parentNode, childNode, edge) {
  26532. // handle circular edges
  26533. if (edge.toId == edge.fromId) {
  26534. this._addToContainedEdges(parentNode, childNode, edge);
  26535. }
  26536. else {
  26537. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  26538. edge.originalToId.push(childNode.id);
  26539. edge.to = parentNode;
  26540. edge.toId = parentNode.id;
  26541. }
  26542. else { // edge connected to other node with the "from" side
  26543. edge.originalFromId.push(childNode.id);
  26544. edge.from = parentNode;
  26545. edge.fromId = parentNode.id;
  26546. }
  26547. this._addToReroutedEdges(parentNode,childNode,edge);
  26548. }
  26549. };
  26550. /**
  26551. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  26552. * these edges inside of the cluster.
  26553. *
  26554. * @param parentNode
  26555. * @param childNode
  26556. * @private
  26557. */
  26558. exports._containCircularEdgesFromNode = function(parentNode, childNode) {
  26559. // manage all the edges connected to the child and parent nodes
  26560. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26561. var edge = parentNode.dynamicEdges[i];
  26562. // handle circular edges
  26563. if (edge.toId == edge.fromId) {
  26564. this._addToContainedEdges(parentNode, childNode, edge);
  26565. }
  26566. }
  26567. };
  26568. /**
  26569. * This adds an edge from the childNode to the rerouted edges of the parent node
  26570. *
  26571. * @param parentNode | Node object
  26572. * @param childNode | Node object
  26573. * @param edge | Edge object
  26574. * @private
  26575. */
  26576. exports._addToReroutedEdges = function(parentNode, childNode, edge) {
  26577. // create an array object if it does not yet exist for this childNode
  26578. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  26579. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  26580. parentNode.reroutedEdges[childNode.id] = [];
  26581. }
  26582. parentNode.reroutedEdges[childNode.id].push(edge);
  26583. // this edge becomes part of the dynamicEdges of the cluster node
  26584. parentNode.dynamicEdges.push(edge);
  26585. };
  26586. /**
  26587. * This function connects an edge that was connected to a cluster node back to the child node.
  26588. *
  26589. * @param parentNode | Node object
  26590. * @param childNode | Node object
  26591. * @private
  26592. */
  26593. exports._connectEdgeBackToChild = function(parentNode, childNode) {
  26594. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  26595. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  26596. var edge = parentNode.reroutedEdges[childNode.id][i];
  26597. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  26598. edge.originalFromId.pop();
  26599. edge.fromId = childNode.id;
  26600. edge.from = childNode;
  26601. }
  26602. else {
  26603. edge.originalToId.pop();
  26604. edge.toId = childNode.id;
  26605. edge.to = childNode;
  26606. }
  26607. // append this edge to the list of edges connecting to the childnode
  26608. childNode.dynamicEdges.push(edge);
  26609. // remove the edge from the parent object
  26610. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  26611. if (parentNode.dynamicEdges[j].id == edge.id) {
  26612. parentNode.dynamicEdges.splice(j,1);
  26613. break;
  26614. }
  26615. }
  26616. }
  26617. // remove the entry from the rerouted edges
  26618. delete parentNode.reroutedEdges[childNode.id];
  26619. }
  26620. };
  26621. /**
  26622. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  26623. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  26624. * parentNode
  26625. *
  26626. * @param parentNode | Node object
  26627. * @private
  26628. */
  26629. exports._validateEdges = function(parentNode) {
  26630. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26631. var edge = parentNode.dynamicEdges[i];
  26632. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  26633. parentNode.dynamicEdges.splice(i,1);
  26634. }
  26635. }
  26636. };
  26637. /**
  26638. * This function released the contained edges back into the global domain and puts them back into the
  26639. * dynamic edges of both parent and child.
  26640. *
  26641. * @param {Node} parentNode |
  26642. * @param {Node} childNode |
  26643. * @private
  26644. */
  26645. exports._releaseContainedEdges = function(parentNode, childNode) {
  26646. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  26647. var edge = parentNode.containedEdges[childNode.id][i];
  26648. // put the edge back in the global edges object
  26649. this.edges[edge.id] = edge;
  26650. // put the edge back in the dynamic edges of the child and parent
  26651. childNode.dynamicEdges.push(edge);
  26652. parentNode.dynamicEdges.push(edge);
  26653. }
  26654. // remove the entry from the contained edges
  26655. delete parentNode.containedEdges[childNode.id];
  26656. };
  26657. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  26658. /**
  26659. * This updates the node labels for all nodes (for debugging purposes)
  26660. */
  26661. exports.updateLabels = function() {
  26662. var nodeId;
  26663. // update node labels
  26664. for (nodeId in this.nodes) {
  26665. if (this.nodes.hasOwnProperty(nodeId)) {
  26666. var node = this.nodes[nodeId];
  26667. if (node.clusterSize > 1) {
  26668. node.label = "[".concat(String(node.clusterSize),"]");
  26669. }
  26670. }
  26671. }
  26672. // update node labels
  26673. for (nodeId in this.nodes) {
  26674. if (this.nodes.hasOwnProperty(nodeId)) {
  26675. node = this.nodes[nodeId];
  26676. if (node.clusterSize == 1) {
  26677. if (node.originalLabel !== undefined) {
  26678. node.label = node.originalLabel;
  26679. }
  26680. else {
  26681. node.label = String(node.id);
  26682. }
  26683. }
  26684. }
  26685. }
  26686. // /* Debug Override */
  26687. // for (nodeId in this.nodes) {
  26688. // if (this.nodes.hasOwnProperty(nodeId)) {
  26689. // node = this.nodes[nodeId];
  26690. // node.label = String(node.level);
  26691. // }
  26692. // }
  26693. };
  26694. /**
  26695. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  26696. * if the rest of the nodes are already a few cluster levels in.
  26697. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  26698. * clustered enough to the clusterToSmallestNeighbours function.
  26699. */
  26700. exports.normalizeClusterLevels = function() {
  26701. var maxLevel = 0;
  26702. var minLevel = 1e9;
  26703. var clusterLevel = 0;
  26704. var nodeId;
  26705. // we loop over all nodes in the list
  26706. for (nodeId in this.nodes) {
  26707. if (this.nodes.hasOwnProperty(nodeId)) {
  26708. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  26709. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  26710. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  26711. }
  26712. }
  26713. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  26714. var amountOfNodes = this.nodeIndices.length;
  26715. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  26716. // we loop over all nodes in the list
  26717. for (nodeId in this.nodes) {
  26718. if (this.nodes.hasOwnProperty(nodeId)) {
  26719. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  26720. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  26721. }
  26722. }
  26723. }
  26724. this._updateNodeIndexList();
  26725. this._updateDynamicEdges();
  26726. // if a cluster was formed, we increase the clusterSession
  26727. if (this.nodeIndices.length != amountOfNodes) {
  26728. this.clusterSession += 1;
  26729. }
  26730. }
  26731. };
  26732. /**
  26733. * This function determines if the cluster we want to decluster is in the active area
  26734. * this means around the zoom center
  26735. *
  26736. * @param {Node} node
  26737. * @returns {boolean}
  26738. * @private
  26739. */
  26740. exports._nodeInActiveArea = function(node) {
  26741. return (
  26742. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  26743. &&
  26744. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  26745. )
  26746. };
  26747. /**
  26748. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  26749. * It puts large clusters away from the center and randomizes the order.
  26750. *
  26751. */
  26752. exports.repositionNodes = function() {
  26753. for (var i = 0; i < this.nodeIndices.length; i++) {
  26754. var node = this.nodes[this.nodeIndices[i]];
  26755. if ((node.xFixed == false || node.yFixed == false)) {
  26756. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass);
  26757. var angle = 2 * Math.PI * Math.random();
  26758. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  26759. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  26760. this._repositionBezierNodes(node);
  26761. }
  26762. }
  26763. };
  26764. /**
  26765. * We determine how many connections denote an important hub.
  26766. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  26767. *
  26768. * @private
  26769. */
  26770. exports._getHubSize = function() {
  26771. var average = 0;
  26772. var averageSquared = 0;
  26773. var hubCounter = 0;
  26774. var largestHub = 0;
  26775. for (var i = 0; i < this.nodeIndices.length; i++) {
  26776. var node = this.nodes[this.nodeIndices[i]];
  26777. if (node.dynamicEdgesLength > largestHub) {
  26778. largestHub = node.dynamicEdgesLength;
  26779. }
  26780. average += node.dynamicEdgesLength;
  26781. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  26782. hubCounter += 1;
  26783. }
  26784. average = average / hubCounter;
  26785. averageSquared = averageSquared / hubCounter;
  26786. var variance = averageSquared - Math.pow(average,2);
  26787. var standardDeviation = Math.sqrt(variance);
  26788. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  26789. // always have at least one to cluster
  26790. if (this.hubThreshold > largestHub) {
  26791. this.hubThreshold = largestHub;
  26792. }
  26793. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  26794. // console.log("hubThreshold:",this.hubThreshold);
  26795. };
  26796. /**
  26797. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  26798. * with this amount we can cluster specifically on these chains.
  26799. *
  26800. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  26801. * @private
  26802. */
  26803. exports._reduceAmountOfChains = function(fraction) {
  26804. this.hubThreshold = 2;
  26805. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  26806. for (var nodeId in this.nodes) {
  26807. if (this.nodes.hasOwnProperty(nodeId)) {
  26808. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  26809. if (reduceAmount > 0) {
  26810. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  26811. reduceAmount -= 1;
  26812. }
  26813. }
  26814. }
  26815. }
  26816. };
  26817. /**
  26818. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  26819. * with this amount we can cluster specifically on these chains.
  26820. *
  26821. * @private
  26822. */
  26823. exports._getChainFraction = function() {
  26824. var chains = 0;
  26825. var total = 0;
  26826. for (var nodeId in this.nodes) {
  26827. if (this.nodes.hasOwnProperty(nodeId)) {
  26828. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  26829. chains += 1;
  26830. }
  26831. total += 1;
  26832. }
  26833. }
  26834. return chains/total;
  26835. };
  26836. /***/ },
  26837. /* 64 */
  26838. /***/ function(module, exports, __webpack_require__) {
  26839. var util = __webpack_require__(1);
  26840. var Node = __webpack_require__(53);
  26841. /**
  26842. * Creation of the SectorMixin var.
  26843. *
  26844. * This contains all the functions the Network object can use to employ the sector system.
  26845. * The sector system is always used by Network, though the benefits only apply to the use of clustering.
  26846. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  26847. */
  26848. /**
  26849. * This function is only called by the setData function of the Network object.
  26850. * This loads the global references into the active sector. This initializes the sector.
  26851. *
  26852. * @private
  26853. */
  26854. exports._putDataInSector = function() {
  26855. this.sectors["active"][this._sector()].nodes = this.nodes;
  26856. this.sectors["active"][this._sector()].edges = this.edges;
  26857. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  26858. };
  26859. /**
  26860. * /**
  26861. * This function sets the global references to nodes, edges and nodeIndices back to
  26862. * those of the supplied (active) sector. If a type is defined, do the specific type
  26863. *
  26864. * @param {String} sectorId
  26865. * @param {String} [sectorType] | "active" or "frozen"
  26866. * @private
  26867. */
  26868. exports._switchToSector = function(sectorId, sectorType) {
  26869. if (sectorType === undefined || sectorType == "active") {
  26870. this._switchToActiveSector(sectorId);
  26871. }
  26872. else {
  26873. this._switchToFrozenSector(sectorId);
  26874. }
  26875. };
  26876. /**
  26877. * This function sets the global references to nodes, edges and nodeIndices back to
  26878. * those of the supplied active sector.
  26879. *
  26880. * @param sectorId
  26881. * @private
  26882. */
  26883. exports._switchToActiveSector = function(sectorId) {
  26884. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  26885. this.nodes = this.sectors["active"][sectorId]["nodes"];
  26886. this.edges = this.sectors["active"][sectorId]["edges"];
  26887. };
  26888. /**
  26889. * This function sets the global references to nodes, edges and nodeIndices back to
  26890. * those of the supplied active sector.
  26891. *
  26892. * @private
  26893. */
  26894. exports._switchToSupportSector = function() {
  26895. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  26896. this.nodes = this.sectors["support"]["nodes"];
  26897. this.edges = this.sectors["support"]["edges"];
  26898. };
  26899. /**
  26900. * This function sets the global references to nodes, edges and nodeIndices back to
  26901. * those of the supplied frozen sector.
  26902. *
  26903. * @param sectorId
  26904. * @private
  26905. */
  26906. exports._switchToFrozenSector = function(sectorId) {
  26907. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  26908. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  26909. this.edges = this.sectors["frozen"][sectorId]["edges"];
  26910. };
  26911. /**
  26912. * This function sets the global references to nodes, edges and nodeIndices back to
  26913. * those of the currently active sector.
  26914. *
  26915. * @private
  26916. */
  26917. exports._loadLatestSector = function() {
  26918. this._switchToSector(this._sector());
  26919. };
  26920. /**
  26921. * This function returns the currently active sector Id
  26922. *
  26923. * @returns {String}
  26924. * @private
  26925. */
  26926. exports._sector = function() {
  26927. return this.activeSector[this.activeSector.length-1];
  26928. };
  26929. /**
  26930. * This function returns the previously active sector Id
  26931. *
  26932. * @returns {String}
  26933. * @private
  26934. */
  26935. exports._previousSector = function() {
  26936. if (this.activeSector.length > 1) {
  26937. return this.activeSector[this.activeSector.length-2];
  26938. }
  26939. else {
  26940. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  26941. }
  26942. };
  26943. /**
  26944. * We add the active sector at the end of the this.activeSector array
  26945. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  26946. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  26947. *
  26948. * @param newId
  26949. * @private
  26950. */
  26951. exports._setActiveSector = function(newId) {
  26952. this.activeSector.push(newId);
  26953. };
  26954. /**
  26955. * We remove the currently active sector id from the active sector stack. This happens when
  26956. * we reactivate the previously active sector
  26957. *
  26958. * @private
  26959. */
  26960. exports._forgetLastSector = function() {
  26961. this.activeSector.pop();
  26962. };
  26963. /**
  26964. * This function creates a new active sector with the supplied newId. This newId
  26965. * is the expanding node id.
  26966. *
  26967. * @param {String} newId | Id of the new active sector
  26968. * @private
  26969. */
  26970. exports._createNewSector = function(newId) {
  26971. // create the new sector
  26972. this.sectors["active"][newId] = {"nodes":{},
  26973. "edges":{},
  26974. "nodeIndices":[],
  26975. "formationScale": this.scale,
  26976. "drawingNode": undefined};
  26977. // create the new sector render node. This gives visual feedback that you are in a new sector.
  26978. this.sectors["active"][newId]['drawingNode'] = new Node(
  26979. {id:newId,
  26980. color: {
  26981. background: "#eaefef",
  26982. border: "495c5e"
  26983. }
  26984. },{},{},this.constants);
  26985. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  26986. };
  26987. /**
  26988. * This function removes the currently active sector. This is called when we create a new
  26989. * active sector.
  26990. *
  26991. * @param {String} sectorId | Id of the active sector that will be removed
  26992. * @private
  26993. */
  26994. exports._deleteActiveSector = function(sectorId) {
  26995. delete this.sectors["active"][sectorId];
  26996. };
  26997. /**
  26998. * This function removes the currently active sector. This is called when we reactivate
  26999. * the previously active sector.
  27000. *
  27001. * @param {String} sectorId | Id of the active sector that will be removed
  27002. * @private
  27003. */
  27004. exports._deleteFrozenSector = function(sectorId) {
  27005. delete this.sectors["frozen"][sectorId];
  27006. };
  27007. /**
  27008. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  27009. * We copy the references, then delete the active entree.
  27010. *
  27011. * @param sectorId
  27012. * @private
  27013. */
  27014. exports._freezeSector = function(sectorId) {
  27015. // we move the set references from the active to the frozen stack.
  27016. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  27017. // we have moved the sector data into the frozen set, we now remove it from the active set
  27018. this._deleteActiveSector(sectorId);
  27019. };
  27020. /**
  27021. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  27022. * object to the "active" object.
  27023. *
  27024. * @param sectorId
  27025. * @private
  27026. */
  27027. exports._activateSector = function(sectorId) {
  27028. // we move the set references from the frozen to the active stack.
  27029. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  27030. // we have moved the sector data into the active set, we now remove it from the frozen stack
  27031. this._deleteFrozenSector(sectorId);
  27032. };
  27033. /**
  27034. * This function merges the data from the currently active sector with a frozen sector. This is used
  27035. * in the process of reverting back to the previously active sector.
  27036. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  27037. * upon the creation of a new active sector.
  27038. *
  27039. * @param sectorId
  27040. * @private
  27041. */
  27042. exports._mergeThisWithFrozen = function(sectorId) {
  27043. // copy all nodes
  27044. for (var nodeId in this.nodes) {
  27045. if (this.nodes.hasOwnProperty(nodeId)) {
  27046. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  27047. }
  27048. }
  27049. // copy all edges (if not fully clustered, else there are no edges)
  27050. for (var edgeId in this.edges) {
  27051. if (this.edges.hasOwnProperty(edgeId)) {
  27052. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  27053. }
  27054. }
  27055. // merge the nodeIndices
  27056. for (var i = 0; i < this.nodeIndices.length; i++) {
  27057. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  27058. }
  27059. };
  27060. /**
  27061. * This clusters the sector to one cluster. It was a single cluster before this process started so
  27062. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  27063. *
  27064. * @private
  27065. */
  27066. exports._collapseThisToSingleCluster = function() {
  27067. this.clusterToFit(1,false);
  27068. };
  27069. /**
  27070. * We create a new active sector from the node that we want to open.
  27071. *
  27072. * @param node
  27073. * @private
  27074. */
  27075. exports._addSector = function(node) {
  27076. // this is the currently active sector
  27077. var sector = this._sector();
  27078. // // this should allow me to select nodes from a frozen set.
  27079. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  27080. // console.log("the node is part of the active sector");
  27081. // }
  27082. // else {
  27083. // console.log("I dont know what the fuck happened!!");
  27084. // }
  27085. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  27086. delete this.nodes[node.id];
  27087. var unqiueIdentifier = util.randomUUID();
  27088. // we fully freeze the currently active sector
  27089. this._freezeSector(sector);
  27090. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  27091. this._createNewSector(unqiueIdentifier);
  27092. // we add the active sector to the sectors array to be able to revert these steps later on
  27093. this._setActiveSector(unqiueIdentifier);
  27094. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  27095. this._switchToSector(this._sector());
  27096. // finally we add the node we removed from our previous active sector to the new active sector
  27097. this.nodes[node.id] = node;
  27098. };
  27099. /**
  27100. * We close the sector that is currently open and revert back to the one before.
  27101. * If the active sector is the "default" sector, nothing happens.
  27102. *
  27103. * @private
  27104. */
  27105. exports._collapseSector = function() {
  27106. // the currently active sector
  27107. var sector = this._sector();
  27108. // we cannot collapse the default sector
  27109. if (sector != "default") {
  27110. if ((this.nodeIndices.length == 1) ||
  27111. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  27112. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  27113. var previousSector = this._previousSector();
  27114. // we collapse the sector back to a single cluster
  27115. this._collapseThisToSingleCluster();
  27116. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  27117. // This previous sector is the one we will reactivate
  27118. this._mergeThisWithFrozen(previousSector);
  27119. // the previously active (frozen) sector now has all the data from the currently active sector.
  27120. // we can now delete the active sector.
  27121. this._deleteActiveSector(sector);
  27122. // we activate the previously active (and currently frozen) sector.
  27123. this._activateSector(previousSector);
  27124. // we load the references from the newly active sector into the global references
  27125. this._switchToSector(previousSector);
  27126. // we forget the previously active sector because we reverted to the one before
  27127. this._forgetLastSector();
  27128. // finally, we update the node index list.
  27129. this._updateNodeIndexList();
  27130. // we refresh the list with calulation nodes and calculation node indices.
  27131. this._updateCalculationNodes();
  27132. }
  27133. }
  27134. };
  27135. /**
  27136. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  27137. *
  27138. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27139. * | we dont pass the function itself because then the "this" is the window object
  27140. * | instead of the Network object
  27141. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27142. * @private
  27143. */
  27144. exports._doInAllActiveSectors = function(runFunction,argument) {
  27145. var returnValues = [];
  27146. if (argument === undefined) {
  27147. for (var sector in this.sectors["active"]) {
  27148. if (this.sectors["active"].hasOwnProperty(sector)) {
  27149. // switch the global references to those of this sector
  27150. this._switchToActiveSector(sector);
  27151. returnValues.push( this[runFunction]() );
  27152. }
  27153. }
  27154. }
  27155. else {
  27156. for (var sector in this.sectors["active"]) {
  27157. if (this.sectors["active"].hasOwnProperty(sector)) {
  27158. // switch the global references to those of this sector
  27159. this._switchToActiveSector(sector);
  27160. var args = Array.prototype.splice.call(arguments, 1);
  27161. if (args.length > 1) {
  27162. returnValues.push( this[runFunction](args[0],args[1]) );
  27163. }
  27164. else {
  27165. returnValues.push( this[runFunction](argument) );
  27166. }
  27167. }
  27168. }
  27169. }
  27170. // we revert the global references back to our active sector
  27171. this._loadLatestSector();
  27172. return returnValues;
  27173. };
  27174. /**
  27175. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  27176. *
  27177. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27178. * | we dont pass the function itself because then the "this" is the window object
  27179. * | instead of the Network object
  27180. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27181. * @private
  27182. */
  27183. exports._doInSupportSector = function(runFunction,argument) {
  27184. var returnValues = false;
  27185. if (argument === undefined) {
  27186. this._switchToSupportSector();
  27187. returnValues = this[runFunction]();
  27188. }
  27189. else {
  27190. this._switchToSupportSector();
  27191. var args = Array.prototype.splice.call(arguments, 1);
  27192. if (args.length > 1) {
  27193. returnValues = this[runFunction](args[0],args[1]);
  27194. }
  27195. else {
  27196. returnValues = this[runFunction](argument);
  27197. }
  27198. }
  27199. // we revert the global references back to our active sector
  27200. this._loadLatestSector();
  27201. return returnValues;
  27202. };
  27203. /**
  27204. * This runs a function in all frozen sectors. This is used in the _redraw().
  27205. *
  27206. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27207. * | we don't pass the function itself because then the "this" is the window object
  27208. * | instead of the Network object
  27209. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27210. * @private
  27211. */
  27212. exports._doInAllFrozenSectors = function(runFunction,argument) {
  27213. if (argument === undefined) {
  27214. for (var sector in this.sectors["frozen"]) {
  27215. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  27216. // switch the global references to those of this sector
  27217. this._switchToFrozenSector(sector);
  27218. this[runFunction]();
  27219. }
  27220. }
  27221. }
  27222. else {
  27223. for (var sector in this.sectors["frozen"]) {
  27224. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  27225. // switch the global references to those of this sector
  27226. this._switchToFrozenSector(sector);
  27227. var args = Array.prototype.splice.call(arguments, 1);
  27228. if (args.length > 1) {
  27229. this[runFunction](args[0],args[1]);
  27230. }
  27231. else {
  27232. this[runFunction](argument);
  27233. }
  27234. }
  27235. }
  27236. }
  27237. this._loadLatestSector();
  27238. };
  27239. /**
  27240. * This runs a function in all sectors. This is used in the _redraw().
  27241. *
  27242. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27243. * | we don't pass the function itself because then the "this" is the window object
  27244. * | instead of the Network object
  27245. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27246. * @private
  27247. */
  27248. exports._doInAllSectors = function(runFunction,argument) {
  27249. var args = Array.prototype.splice.call(arguments, 1);
  27250. if (argument === undefined) {
  27251. this._doInAllActiveSectors(runFunction);
  27252. this._doInAllFrozenSectors(runFunction);
  27253. }
  27254. else {
  27255. if (args.length > 1) {
  27256. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  27257. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  27258. }
  27259. else {
  27260. this._doInAllActiveSectors(runFunction,argument);
  27261. this._doInAllFrozenSectors(runFunction,argument);
  27262. }
  27263. }
  27264. };
  27265. /**
  27266. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  27267. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  27268. *
  27269. * @private
  27270. */
  27271. exports._clearNodeIndexList = function() {
  27272. var sector = this._sector();
  27273. this.sectors["active"][sector]["nodeIndices"] = [];
  27274. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  27275. };
  27276. /**
  27277. * Draw the encompassing sector node
  27278. *
  27279. * @param ctx
  27280. * @param sectorType
  27281. * @private
  27282. */
  27283. exports._drawSectorNodes = function(ctx,sectorType) {
  27284. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  27285. for (var sector in this.sectors[sectorType]) {
  27286. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  27287. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  27288. this._switchToSector(sector,sectorType);
  27289. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  27290. for (var nodeId in this.nodes) {
  27291. if (this.nodes.hasOwnProperty(nodeId)) {
  27292. node = this.nodes[nodeId];
  27293. node.resize(ctx);
  27294. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  27295. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  27296. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  27297. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  27298. }
  27299. }
  27300. node = this.sectors[sectorType][sector]["drawingNode"];
  27301. node.x = 0.5 * (maxX + minX);
  27302. node.y = 0.5 * (maxY + minY);
  27303. node.width = 2 * (node.x - minX);
  27304. node.height = 2 * (node.y - minY);
  27305. node.options.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  27306. node.setScale(this.scale);
  27307. node._drawCircle(ctx);
  27308. }
  27309. }
  27310. }
  27311. };
  27312. exports._drawAllSectorNodes = function(ctx) {
  27313. this._drawSectorNodes(ctx,"frozen");
  27314. this._drawSectorNodes(ctx,"active");
  27315. this._loadLatestSector();
  27316. };
  27317. /***/ },
  27318. /* 65 */
  27319. /***/ function(module, exports, __webpack_require__) {
  27320. var Node = __webpack_require__(53);
  27321. /**
  27322. * This function can be called from the _doInAllSectors function
  27323. *
  27324. * @param object
  27325. * @param overlappingNodes
  27326. * @private
  27327. */
  27328. exports._getNodesOverlappingWith = function(object, overlappingNodes) {
  27329. var nodes = this.nodes;
  27330. for (var nodeId in nodes) {
  27331. if (nodes.hasOwnProperty(nodeId)) {
  27332. if (nodes[nodeId].isOverlappingWith(object)) {
  27333. overlappingNodes.push(nodeId);
  27334. }
  27335. }
  27336. }
  27337. };
  27338. /**
  27339. * retrieve all nodes overlapping with given object
  27340. * @param {Object} object An object with parameters left, top, right, bottom
  27341. * @return {Number[]} An array with id's of the overlapping nodes
  27342. * @private
  27343. */
  27344. exports._getAllNodesOverlappingWith = function (object) {
  27345. var overlappingNodes = [];
  27346. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  27347. return overlappingNodes;
  27348. };
  27349. /**
  27350. * Return a position object in canvasspace from a single point in screenspace
  27351. *
  27352. * @param pointer
  27353. * @returns {{left: number, top: number, right: number, bottom: number}}
  27354. * @private
  27355. */
  27356. exports._pointerToPositionObject = function(pointer) {
  27357. var x = this._XconvertDOMtoCanvas(pointer.x);
  27358. var y = this._YconvertDOMtoCanvas(pointer.y);
  27359. return {
  27360. left: x,
  27361. top: y,
  27362. right: x,
  27363. bottom: y
  27364. };
  27365. };
  27366. /**
  27367. * Get the top node at the a specific point (like a click)
  27368. *
  27369. * @param {{x: Number, y: Number}} pointer
  27370. * @return {Node | null} node
  27371. * @private
  27372. */
  27373. exports._getNodeAt = function (pointer) {
  27374. // we first check if this is an navigation controls element
  27375. var positionObject = this._pointerToPositionObject(pointer);
  27376. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  27377. // if there are overlapping nodes, select the last one, this is the
  27378. // one which is drawn on top of the others
  27379. if (overlappingNodes.length > 0) {
  27380. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  27381. }
  27382. else {
  27383. return null;
  27384. }
  27385. };
  27386. /**
  27387. * retrieve all edges overlapping with given object, selector is around center
  27388. * @param {Object} object An object with parameters left, top, right, bottom
  27389. * @return {Number[]} An array with id's of the overlapping nodes
  27390. * @private
  27391. */
  27392. exports._getEdgesOverlappingWith = function (object, overlappingEdges) {
  27393. var edges = this.edges;
  27394. for (var edgeId in edges) {
  27395. if (edges.hasOwnProperty(edgeId)) {
  27396. if (edges[edgeId].isOverlappingWith(object)) {
  27397. overlappingEdges.push(edgeId);
  27398. }
  27399. }
  27400. }
  27401. };
  27402. /**
  27403. * retrieve all nodes overlapping with given object
  27404. * @param {Object} object An object with parameters left, top, right, bottom
  27405. * @return {Number[]} An array with id's of the overlapping nodes
  27406. * @private
  27407. */
  27408. exports._getAllEdgesOverlappingWith = function (object) {
  27409. var overlappingEdges = [];
  27410. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  27411. return overlappingEdges;
  27412. };
  27413. /**
  27414. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  27415. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  27416. *
  27417. * @param pointer
  27418. * @returns {null}
  27419. * @private
  27420. */
  27421. exports._getEdgeAt = function(pointer) {
  27422. var positionObject = this._pointerToPositionObject(pointer);
  27423. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  27424. if (overlappingEdges.length > 0) {
  27425. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  27426. }
  27427. else {
  27428. return null;
  27429. }
  27430. };
  27431. /**
  27432. * Add object to the selection array.
  27433. *
  27434. * @param obj
  27435. * @private
  27436. */
  27437. exports._addToSelection = function(obj) {
  27438. if (obj instanceof Node) {
  27439. this.selectionObj.nodes[obj.id] = obj;
  27440. }
  27441. else {
  27442. this.selectionObj.edges[obj.id] = obj;
  27443. }
  27444. };
  27445. /**
  27446. * Add object to the selection array.
  27447. *
  27448. * @param obj
  27449. * @private
  27450. */
  27451. exports._addToHover = function(obj) {
  27452. if (obj instanceof Node) {
  27453. this.hoverObj.nodes[obj.id] = obj;
  27454. }
  27455. else {
  27456. this.hoverObj.edges[obj.id] = obj;
  27457. }
  27458. };
  27459. /**
  27460. * Remove a single option from selection.
  27461. *
  27462. * @param {Object} obj
  27463. * @private
  27464. */
  27465. exports._removeFromSelection = function(obj) {
  27466. if (obj instanceof Node) {
  27467. delete this.selectionObj.nodes[obj.id];
  27468. }
  27469. else {
  27470. delete this.selectionObj.edges[obj.id];
  27471. }
  27472. };
  27473. /**
  27474. * Unselect all. The selectionObj is useful for this.
  27475. *
  27476. * @param {Boolean} [doNotTrigger] | ignore trigger
  27477. * @private
  27478. */
  27479. exports._unselectAll = function(doNotTrigger) {
  27480. if (doNotTrigger === undefined) {
  27481. doNotTrigger = false;
  27482. }
  27483. for(var nodeId in this.selectionObj.nodes) {
  27484. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27485. this.selectionObj.nodes[nodeId].unselect();
  27486. }
  27487. }
  27488. for(var edgeId in this.selectionObj.edges) {
  27489. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27490. this.selectionObj.edges[edgeId].unselect();
  27491. }
  27492. }
  27493. this.selectionObj = {nodes:{},edges:{}};
  27494. if (doNotTrigger == false) {
  27495. this.emit('select', this.getSelection());
  27496. }
  27497. };
  27498. /**
  27499. * Unselect all clusters. The selectionObj is useful for this.
  27500. *
  27501. * @param {Boolean} [doNotTrigger] | ignore trigger
  27502. * @private
  27503. */
  27504. exports._unselectClusters = function(doNotTrigger) {
  27505. if (doNotTrigger === undefined) {
  27506. doNotTrigger = false;
  27507. }
  27508. for (var nodeId in this.selectionObj.nodes) {
  27509. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27510. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  27511. this.selectionObj.nodes[nodeId].unselect();
  27512. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  27513. }
  27514. }
  27515. }
  27516. if (doNotTrigger == false) {
  27517. this.emit('select', this.getSelection());
  27518. }
  27519. };
  27520. /**
  27521. * return the number of selected nodes
  27522. *
  27523. * @returns {number}
  27524. * @private
  27525. */
  27526. exports._getSelectedNodeCount = function() {
  27527. var count = 0;
  27528. for (var nodeId in this.selectionObj.nodes) {
  27529. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27530. count += 1;
  27531. }
  27532. }
  27533. return count;
  27534. };
  27535. /**
  27536. * return the selected node
  27537. *
  27538. * @returns {number}
  27539. * @private
  27540. */
  27541. exports._getSelectedNode = function() {
  27542. for (var nodeId in this.selectionObj.nodes) {
  27543. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27544. return this.selectionObj.nodes[nodeId];
  27545. }
  27546. }
  27547. return null;
  27548. };
  27549. /**
  27550. * return the selected edge
  27551. *
  27552. * @returns {number}
  27553. * @private
  27554. */
  27555. exports._getSelectedEdge = function() {
  27556. for (var edgeId in this.selectionObj.edges) {
  27557. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27558. return this.selectionObj.edges[edgeId];
  27559. }
  27560. }
  27561. return null;
  27562. };
  27563. /**
  27564. * return the number of selected edges
  27565. *
  27566. * @returns {number}
  27567. * @private
  27568. */
  27569. exports._getSelectedEdgeCount = function() {
  27570. var count = 0;
  27571. for (var edgeId in this.selectionObj.edges) {
  27572. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27573. count += 1;
  27574. }
  27575. }
  27576. return count;
  27577. };
  27578. /**
  27579. * return the number of selected objects.
  27580. *
  27581. * @returns {number}
  27582. * @private
  27583. */
  27584. exports._getSelectedObjectCount = function() {
  27585. var count = 0;
  27586. for(var nodeId in this.selectionObj.nodes) {
  27587. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27588. count += 1;
  27589. }
  27590. }
  27591. for(var edgeId in this.selectionObj.edges) {
  27592. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27593. count += 1;
  27594. }
  27595. }
  27596. return count;
  27597. };
  27598. /**
  27599. * Check if anything is selected
  27600. *
  27601. * @returns {boolean}
  27602. * @private
  27603. */
  27604. exports._selectionIsEmpty = function() {
  27605. for(var nodeId in this.selectionObj.nodes) {
  27606. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27607. return false;
  27608. }
  27609. }
  27610. for(var edgeId in this.selectionObj.edges) {
  27611. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27612. return false;
  27613. }
  27614. }
  27615. return true;
  27616. };
  27617. /**
  27618. * check if one of the selected nodes is a cluster.
  27619. *
  27620. * @returns {boolean}
  27621. * @private
  27622. */
  27623. exports._clusterInSelection = function() {
  27624. for(var nodeId in this.selectionObj.nodes) {
  27625. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27626. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  27627. return true;
  27628. }
  27629. }
  27630. }
  27631. return false;
  27632. };
  27633. /**
  27634. * select the edges connected to the node that is being selected
  27635. *
  27636. * @param {Node} node
  27637. * @private
  27638. */
  27639. exports._selectConnectedEdges = function(node) {
  27640. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27641. var edge = node.dynamicEdges[i];
  27642. edge.select();
  27643. this._addToSelection(edge);
  27644. }
  27645. };
  27646. /**
  27647. * select the edges connected to the node that is being selected
  27648. *
  27649. * @param {Node} node
  27650. * @private
  27651. */
  27652. exports._hoverConnectedEdges = function(node) {
  27653. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27654. var edge = node.dynamicEdges[i];
  27655. edge.hover = true;
  27656. this._addToHover(edge);
  27657. }
  27658. };
  27659. /**
  27660. * unselect the edges connected to the node that is being selected
  27661. *
  27662. * @param {Node} node
  27663. * @private
  27664. */
  27665. exports._unselectConnectedEdges = function(node) {
  27666. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27667. var edge = node.dynamicEdges[i];
  27668. edge.unselect();
  27669. this._removeFromSelection(edge);
  27670. }
  27671. };
  27672. /**
  27673. * This is called when someone clicks on a node. either select or deselect it.
  27674. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27675. *
  27676. * @param {Node || Edge} object
  27677. * @param {Boolean} append
  27678. * @param {Boolean} [doNotTrigger] | ignore trigger
  27679. * @private
  27680. */
  27681. exports._selectObject = function(object, append, doNotTrigger, highlightEdges, overrideSelectable) {
  27682. if (doNotTrigger === undefined) {
  27683. doNotTrigger = false;
  27684. }
  27685. if (highlightEdges === undefined) {
  27686. highlightEdges = true;
  27687. }
  27688. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  27689. this._unselectAll(true);
  27690. }
  27691. // selectable allows the object to be selected. Override can be used if needed to bypass this.
  27692. if (object.selected == false && (this.constants.selectable == true || overrideSelectable)) {
  27693. object.select();
  27694. this._addToSelection(object);
  27695. if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) {
  27696. this._selectConnectedEdges(object);
  27697. }
  27698. }
  27699. // do not select the object if selectable is false, only add it to selection to allow drag to work
  27700. else if (object.selected == false) {
  27701. this._addToSelection(object);
  27702. doNotTrigger = true;
  27703. }
  27704. else {
  27705. object.unselect();
  27706. this._removeFromSelection(object);
  27707. }
  27708. if (doNotTrigger == false) {
  27709. this.emit('select', this.getSelection());
  27710. }
  27711. };
  27712. /**
  27713. * This is called when someone clicks on a node. either select or deselect it.
  27714. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27715. *
  27716. * @param {Node || Edge} object
  27717. * @private
  27718. */
  27719. exports._blurObject = function(object) {
  27720. if (object.hover == true) {
  27721. object.hover = false;
  27722. this.emit("blurNode",{node:object.id});
  27723. }
  27724. };
  27725. /**
  27726. * This is called when someone clicks on a node. either select or deselect it.
  27727. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27728. *
  27729. * @param {Node || Edge} object
  27730. * @private
  27731. */
  27732. exports._hoverObject = function(object) {
  27733. if (object.hover == false) {
  27734. object.hover = true;
  27735. this._addToHover(object);
  27736. if (object instanceof Node) {
  27737. this.emit("hoverNode",{node:object.id});
  27738. }
  27739. }
  27740. if (object instanceof Node) {
  27741. this._hoverConnectedEdges(object);
  27742. }
  27743. };
  27744. /**
  27745. * handles the selection part of the touch, only for navigation controls elements;
  27746. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  27747. * This is the most responsive solution
  27748. *
  27749. * @param {Object} pointer
  27750. * @private
  27751. */
  27752. exports._handleTouch = function(pointer) {
  27753. };
  27754. /**
  27755. * handles the selection part of the tap;
  27756. *
  27757. * @param {Object} pointer
  27758. * @private
  27759. */
  27760. exports._handleTap = function(pointer) {
  27761. var node = this._getNodeAt(pointer);
  27762. if (node != null) {
  27763. this._selectObject(node, false);
  27764. }
  27765. else {
  27766. var edge = this._getEdgeAt(pointer);
  27767. if (edge != null) {
  27768. this._selectObject(edge, false);
  27769. }
  27770. else {
  27771. this._unselectAll();
  27772. }
  27773. }
  27774. var properties = this.getSelection();
  27775. properties['pointer'] = {
  27776. DOM: {x: pointer.x, y: pointer.y},
  27777. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  27778. }
  27779. this.emit("click", properties);
  27780. this._redraw();
  27781. };
  27782. /**
  27783. * handles the selection part of the double tap and opens a cluster if needed
  27784. *
  27785. * @param {Object} pointer
  27786. * @private
  27787. */
  27788. exports._handleDoubleTap = function(pointer) {
  27789. var node = this._getNodeAt(pointer);
  27790. if (node != null && node !== undefined) {
  27791. // we reset the areaCenter here so the opening of the node will occur
  27792. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  27793. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  27794. this.openCluster(node);
  27795. }
  27796. var properties = this.getSelection();
  27797. properties['pointer'] = {
  27798. DOM: {x: pointer.x, y: pointer.y},
  27799. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  27800. }
  27801. this.emit("doubleClick", properties);
  27802. };
  27803. /**
  27804. * Handle the onHold selection part
  27805. *
  27806. * @param pointer
  27807. * @private
  27808. */
  27809. exports._handleOnHold = function(pointer) {
  27810. var node = this._getNodeAt(pointer);
  27811. if (node != null) {
  27812. this._selectObject(node,true);
  27813. }
  27814. else {
  27815. var edge = this._getEdgeAt(pointer);
  27816. if (edge != null) {
  27817. this._selectObject(edge,true);
  27818. }
  27819. }
  27820. this._redraw();
  27821. };
  27822. /**
  27823. * handle the onRelease event. These functions are here for the navigation controls module
  27824. * and data manipulation module.
  27825. *
  27826. * @private
  27827. */
  27828. exports._handleOnRelease = function(pointer) {
  27829. this._manipulationReleaseOverload(pointer);
  27830. this._navigationReleaseOverload(pointer);
  27831. };
  27832. exports._manipulationReleaseOverload = function (pointer) {};
  27833. exports._navigationReleaseOverload = function (pointer) {};
  27834. /**
  27835. *
  27836. * retrieve the currently selected objects
  27837. * @return {{nodes: Array.<String>, edges: Array.<String>}} selection
  27838. */
  27839. exports.getSelection = function() {
  27840. var nodeIds = this.getSelectedNodes();
  27841. var edgeIds = this.getSelectedEdges();
  27842. return {nodes:nodeIds, edges:edgeIds};
  27843. };
  27844. /**
  27845. *
  27846. * retrieve the currently selected nodes
  27847. * @return {String[]} selection An array with the ids of the
  27848. * selected nodes.
  27849. */
  27850. exports.getSelectedNodes = function() {
  27851. var idArray = [];
  27852. if (this.constants.selectable == true) {
  27853. for (var nodeId in this.selectionObj.nodes) {
  27854. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27855. idArray.push(nodeId);
  27856. }
  27857. }
  27858. }
  27859. return idArray
  27860. };
  27861. /**
  27862. *
  27863. * retrieve the currently selected edges
  27864. * @return {Array} selection An array with the ids of the
  27865. * selected nodes.
  27866. */
  27867. exports.getSelectedEdges = function() {
  27868. var idArray = [];
  27869. if (this.constants.selectable == true) {
  27870. for (var edgeId in this.selectionObj.edges) {
  27871. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27872. idArray.push(edgeId);
  27873. }
  27874. }
  27875. }
  27876. return idArray;
  27877. };
  27878. /**
  27879. * select zero or more nodes DEPRICATED
  27880. * @param {Number[] | String[]} selection An array with the ids of the
  27881. * selected nodes.
  27882. */
  27883. exports.setSelection = function() {
  27884. console.log("setSelection is deprecated. Please use selectNodes instead.")
  27885. };
  27886. /**
  27887. * select zero or more nodes with the option to highlight edges
  27888. * @param {Number[] | String[]} selection An array with the ids of the
  27889. * selected nodes.
  27890. * @param {boolean} [highlightEdges]
  27891. */
  27892. exports.selectNodes = function(selection, highlightEdges) {
  27893. var i, iMax, id;
  27894. if (!selection || (selection.length == undefined))
  27895. throw 'Selection must be an array with ids';
  27896. // first unselect any selected node
  27897. this._unselectAll(true);
  27898. for (i = 0, iMax = selection.length; i < iMax; i++) {
  27899. id = selection[i];
  27900. var node = this.nodes[id];
  27901. if (!node) {
  27902. throw new RangeError('Node with id "' + id + '" not found');
  27903. }
  27904. this._selectObject(node,true,true,highlightEdges,true);
  27905. }
  27906. this.redraw();
  27907. };
  27908. /**
  27909. * select zero or more edges
  27910. * @param {Number[] | String[]} selection An array with the ids of the
  27911. * selected nodes.
  27912. */
  27913. exports.selectEdges = function(selection) {
  27914. var i, iMax, id;
  27915. if (!selection || (selection.length == undefined))
  27916. throw 'Selection must be an array with ids';
  27917. // first unselect any selected node
  27918. this._unselectAll(true);
  27919. for (i = 0, iMax = selection.length; i < iMax; i++) {
  27920. id = selection[i];
  27921. var edge = this.edges[id];
  27922. if (!edge) {
  27923. throw new RangeError('Edge with id "' + id + '" not found');
  27924. }
  27925. this._selectObject(edge,true,true,false,true);
  27926. }
  27927. this.redraw();
  27928. };
  27929. /**
  27930. * Validate the selection: remove ids of nodes which no longer exist
  27931. * @private
  27932. */
  27933. exports._updateSelection = function () {
  27934. for(var nodeId in this.selectionObj.nodes) {
  27935. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27936. if (!this.nodes.hasOwnProperty(nodeId)) {
  27937. delete this.selectionObj.nodes[nodeId];
  27938. }
  27939. }
  27940. }
  27941. for(var edgeId in this.selectionObj.edges) {
  27942. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27943. if (!this.edges.hasOwnProperty(edgeId)) {
  27944. delete this.selectionObj.edges[edgeId];
  27945. }
  27946. }
  27947. }
  27948. };
  27949. /***/ },
  27950. /* 66 */
  27951. /***/ function(module, exports, __webpack_require__) {
  27952. var util = __webpack_require__(1);
  27953. var Node = __webpack_require__(53);
  27954. var Edge = __webpack_require__(52);
  27955. /**
  27956. * clears the toolbar div element of children
  27957. *
  27958. * @private
  27959. */
  27960. exports._clearManipulatorBar = function() {
  27961. while (this.manipulationDiv.hasChildNodes()) {
  27962. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  27963. }
  27964. this.manipulationDOM = {};
  27965. this._manipulationReleaseOverload = function () {};
  27966. delete this.sectors['support']['nodes']['targetNode'];
  27967. delete this.sectors['support']['nodes']['targetViaNode'];
  27968. this.controlNodesActive = false;
  27969. };
  27970. /**
  27971. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  27972. * these functions to their original functionality, we saved them in this.cachedFunctions.
  27973. * This function restores these functions to their original function.
  27974. *
  27975. * @private
  27976. */
  27977. exports._restoreOverloadedFunctions = function() {
  27978. for (var functionName in this.cachedFunctions) {
  27979. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  27980. this[functionName] = this.cachedFunctions[functionName];
  27981. }
  27982. }
  27983. };
  27984. /**
  27985. * Enable or disable edit-mode.
  27986. *
  27987. * @private
  27988. */
  27989. exports._toggleEditMode = function() {
  27990. this.editMode = !this.editMode;
  27991. var toolbar = this.manipulationDiv;
  27992. var closeDiv = this.closeDiv;
  27993. var editModeDiv = this.editModeDiv;
  27994. if (this.editMode == true) {
  27995. toolbar.style.display="block";
  27996. closeDiv.style.display="block";
  27997. editModeDiv.style.display="none";
  27998. closeDiv.onclick = this._toggleEditMode.bind(this);
  27999. }
  28000. else {
  28001. toolbar.style.display="none";
  28002. closeDiv.style.display="none";
  28003. editModeDiv.style.display="block";
  28004. closeDiv.onclick = null;
  28005. }
  28006. this._createManipulatorBar()
  28007. };
  28008. /**
  28009. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  28010. *
  28011. * @private
  28012. */
  28013. exports._createManipulatorBar = function() {
  28014. // remove bound functions
  28015. if (this.boundFunction) {
  28016. this.off('select', this.boundFunction);
  28017. }
  28018. var locale = this.constants.locales[this.constants.locale];
  28019. if (this.edgeBeingEdited !== undefined) {
  28020. this.edgeBeingEdited._disableControlNodes();
  28021. this.edgeBeingEdited = undefined;
  28022. this.selectedControlNode = null;
  28023. this.controlNodesActive = false;
  28024. this._redraw();
  28025. }
  28026. // restore overloaded functions
  28027. this._restoreOverloadedFunctions();
  28028. // resume calculation
  28029. this.freezeSimulation = false;
  28030. // reset global variables
  28031. this.blockConnectingEdgeSelection = false;
  28032. this.forceAppendSelection = false;
  28033. this.manipulationDOM = {};
  28034. if (this.editMode == true) {
  28035. while (this.manipulationDiv.hasChildNodes()) {
  28036. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  28037. }
  28038. this.manipulationDOM['addNodeSpan'] = document.createElement('span');
  28039. this.manipulationDOM['addNodeSpan'].className = 'network-manipulationUI add';
  28040. this.manipulationDOM['addNodeLabelSpan'] = document.createElement('span');
  28041. this.manipulationDOM['addNodeLabelSpan'].className = 'network-manipulationLabel';
  28042. this.manipulationDOM['addNodeLabelSpan'].innerHTML = locale['addNode'];
  28043. this.manipulationDOM['addNodeSpan'].appendChild(this.manipulationDOM['addNodeLabelSpan']);
  28044. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28045. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28046. this.manipulationDOM['addEdgeSpan'] = document.createElement('span');
  28047. this.manipulationDOM['addEdgeSpan'].className = 'network-manipulationUI connect';
  28048. this.manipulationDOM['addEdgeLabelSpan'] = document.createElement('span');
  28049. this.manipulationDOM['addEdgeLabelSpan'].className = 'network-manipulationLabel';
  28050. this.manipulationDOM['addEdgeLabelSpan'].innerHTML = locale['addEdge'];
  28051. this.manipulationDOM['addEdgeSpan'].appendChild(this.manipulationDOM['addEdgeLabelSpan']);
  28052. this.manipulationDiv.appendChild(this.manipulationDOM['addNodeSpan']);
  28053. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28054. this.manipulationDiv.appendChild(this.manipulationDOM['addEdgeSpan']);
  28055. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  28056. this.manipulationDOM['seperatorLineDiv2'] = document.createElement('div');
  28057. this.manipulationDOM['seperatorLineDiv2'].className = 'network-seperatorLine';
  28058. this.manipulationDOM['editNodeSpan'] = document.createElement('span');
  28059. this.manipulationDOM['editNodeSpan'].className = 'network-manipulationUI edit';
  28060. this.manipulationDOM['editNodeLabelSpan'] = document.createElement('span');
  28061. this.manipulationDOM['editNodeLabelSpan'].className = 'network-manipulationLabel';
  28062. this.manipulationDOM['editNodeLabelSpan'].innerHTML = locale['editNode'];
  28063. this.manipulationDOM['editNodeSpan'].appendChild(this.manipulationDOM['editNodeLabelSpan']);
  28064. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv2']);
  28065. this.manipulationDiv.appendChild(this.manipulationDOM['editNodeSpan']);
  28066. }
  28067. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  28068. this.manipulationDOM['seperatorLineDiv3'] = document.createElement('div');
  28069. this.manipulationDOM['seperatorLineDiv3'].className = 'network-seperatorLine';
  28070. this.manipulationDOM['editEdgeSpan'] = document.createElement('span');
  28071. this.manipulationDOM['editEdgeSpan'].className = 'network-manipulationUI edit';
  28072. this.manipulationDOM['editEdgeLabelSpan'] = document.createElement('span');
  28073. this.manipulationDOM['editEdgeLabelSpan'].className = 'network-manipulationLabel';
  28074. this.manipulationDOM['editEdgeLabelSpan'].innerHTML = locale['editEdge'];
  28075. this.manipulationDOM['editEdgeSpan'].appendChild(this.manipulationDOM['editEdgeLabelSpan']);
  28076. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv3']);
  28077. this.manipulationDiv.appendChild(this.manipulationDOM['editEdgeSpan']);
  28078. }
  28079. if (this._selectionIsEmpty() == false) {
  28080. this.manipulationDOM['seperatorLineDiv4'] = document.createElement('div');
  28081. this.manipulationDOM['seperatorLineDiv4'].className = 'network-seperatorLine';
  28082. this.manipulationDOM['deleteSpan'] = document.createElement('span');
  28083. this.manipulationDOM['deleteSpan'].className = 'network-manipulationUI delete';
  28084. this.manipulationDOM['deleteLabelSpan'] = document.createElement('span');
  28085. this.manipulationDOM['deleteLabelSpan'].className = 'network-manipulationLabel';
  28086. this.manipulationDOM['deleteLabelSpan'].innerHTML = locale['del'];
  28087. this.manipulationDOM['deleteSpan'].appendChild(this.manipulationDOM['deleteLabelSpan']);
  28088. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv4']);
  28089. this.manipulationDiv.appendChild(this.manipulationDOM['deleteSpan']);
  28090. }
  28091. // bind the icons
  28092. this.manipulationDOM['addNodeSpan'].onclick = this._createAddNodeToolbar.bind(this);
  28093. this.manipulationDOM['addEdgeSpan'].onclick = this._createAddEdgeToolbar.bind(this);
  28094. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  28095. this.manipulationDOM['editNodeSpan'].onclick = this._editNode.bind(this);
  28096. }
  28097. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  28098. this.manipulationDOM['editEdgeSpan'].onclick = this._createEditEdgeToolbar.bind(this);
  28099. }
  28100. if (this._selectionIsEmpty() == false) {
  28101. this.manipulationDOM['deleteSpan'].onclick = this._deleteSelected.bind(this);
  28102. }
  28103. this.closeDiv.onclick = this._toggleEditMode.bind(this);
  28104. this.boundFunction = this._createManipulatorBar.bind(this);
  28105. this.on('select', this.boundFunction);
  28106. }
  28107. else {
  28108. while (this.editModeDiv.hasChildNodes()) {
  28109. this.editModeDiv.removeChild(this.editModeDiv.firstChild);
  28110. }
  28111. this.manipulationDOM['editModeSpan'] = document.createElement('span');
  28112. this.manipulationDOM['editModeSpan'].className = 'network-manipulationUI edit editmode';
  28113. this.manipulationDOM['editModeLabelSpan'] = document.createElement('span');
  28114. this.manipulationDOM['editModeLabelSpan'].className = 'network-manipulationLabel';
  28115. this.manipulationDOM['editModeLabelSpan'].innerHTML = locale['edit'];
  28116. this.manipulationDOM['editModeSpan'].appendChild(this.manipulationDOM['editModeLabelSpan']);
  28117. this.editModeDiv.appendChild(this.manipulationDOM['editModeSpan']);
  28118. this.manipulationDOM['editModeSpan'].onclick = this._toggleEditMode.bind(this);
  28119. }
  28120. };
  28121. /**
  28122. * Create the toolbar for adding Nodes
  28123. *
  28124. * @private
  28125. */
  28126. exports._createAddNodeToolbar = function() {
  28127. // clear the toolbar
  28128. this._clearManipulatorBar();
  28129. if (this.boundFunction) {
  28130. this.off('select', this.boundFunction);
  28131. }
  28132. var locale = this.constants.locales[this.constants.locale];
  28133. this.manipulationDOM = {};
  28134. this.manipulationDOM['backSpan'] = document.createElement('span');
  28135. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  28136. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  28137. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  28138. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  28139. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  28140. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28141. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28142. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  28143. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  28144. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  28145. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  28146. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['addDescription'];
  28147. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  28148. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  28149. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28150. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  28151. // bind the icon
  28152. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  28153. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  28154. this.boundFunction = this._addNode.bind(this);
  28155. this.on('select', this.boundFunction);
  28156. };
  28157. /**
  28158. * create the toolbar to connect nodes
  28159. *
  28160. * @private
  28161. */
  28162. exports._createAddEdgeToolbar = function() {
  28163. // clear the toolbar
  28164. this._clearManipulatorBar();
  28165. this._unselectAll(true);
  28166. this.freezeSimulation = true;
  28167. var locale = this.constants.locales[this.constants.locale];
  28168. if (this.boundFunction) {
  28169. this.off('select', this.boundFunction);
  28170. }
  28171. this._unselectAll();
  28172. this.forceAppendSelection = false;
  28173. this.blockConnectingEdgeSelection = true;
  28174. this.manipulationDOM = {};
  28175. this.manipulationDOM['backSpan'] = document.createElement('span');
  28176. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  28177. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  28178. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  28179. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  28180. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  28181. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28182. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28183. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  28184. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  28185. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  28186. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  28187. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['edgeDescription'];
  28188. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  28189. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  28190. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28191. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  28192. // bind the icon
  28193. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  28194. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  28195. this.boundFunction = this._handleConnect.bind(this);
  28196. this.on('select', this.boundFunction);
  28197. // temporarily overload functions
  28198. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  28199. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  28200. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  28201. this.cachedFunctions["_handleDragEnd"] = this._handleDragEnd;
  28202. this._handleTouch = this._handleConnect;
  28203. this._manipulationReleaseOverload = function () {};
  28204. this._handleDragStart = function () {};
  28205. this._handleDragEnd = this._finishConnect;
  28206. // redraw to show the unselect
  28207. this._redraw();
  28208. };
  28209. /**
  28210. * create the toolbar to edit edges
  28211. *
  28212. * @private
  28213. */
  28214. exports._createEditEdgeToolbar = function() {
  28215. // clear the toolbar
  28216. this._clearManipulatorBar();
  28217. this.controlNodesActive = true;
  28218. if (this.boundFunction) {
  28219. this.off('select', this.boundFunction);
  28220. }
  28221. this.edgeBeingEdited = this._getSelectedEdge();
  28222. this.edgeBeingEdited._enableControlNodes();
  28223. var locale = this.constants.locales[this.constants.locale];
  28224. this.manipulationDOM = {};
  28225. this.manipulationDOM['backSpan'] = document.createElement('span');
  28226. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  28227. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  28228. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  28229. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  28230. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  28231. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28232. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28233. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  28234. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  28235. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  28236. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  28237. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['editEdgeDescription'];
  28238. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  28239. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  28240. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28241. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  28242. // bind the icon
  28243. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  28244. // temporarily overload functions
  28245. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  28246. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  28247. this.cachedFunctions["_handleTap"] = this._handleTap;
  28248. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  28249. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  28250. this._handleTouch = this._selectControlNode;
  28251. this._handleTap = function () {};
  28252. this._handleOnDrag = this._controlNodeDrag;
  28253. this._handleDragStart = function () {}
  28254. this._manipulationReleaseOverload = this._releaseControlNode;
  28255. // redraw to show the unselect
  28256. this._redraw();
  28257. };
  28258. /**
  28259. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28260. * to walk the user through the process.
  28261. *
  28262. * @private
  28263. */
  28264. exports._selectControlNode = function(pointer) {
  28265. this.edgeBeingEdited.controlNodes.from.unselect();
  28266. this.edgeBeingEdited.controlNodes.to.unselect();
  28267. this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y));
  28268. if (this.selectedControlNode !== null) {
  28269. this.selectedControlNode.select();
  28270. this.freezeSimulation = true;
  28271. }
  28272. this._redraw();
  28273. };
  28274. /**
  28275. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28276. * to walk the user through the process.
  28277. *
  28278. * @private
  28279. */
  28280. exports._controlNodeDrag = function(event) {
  28281. var pointer = this._getPointer(event.gesture.center);
  28282. if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) {
  28283. this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x);
  28284. this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y);
  28285. }
  28286. this._redraw();
  28287. };
  28288. exports._releaseControlNode = function(pointer) {
  28289. var newNode = this._getNodeAt(pointer);
  28290. if (newNode !== null) {
  28291. if (this.edgeBeingEdited.controlNodes.from.selected == true) {
  28292. this._editEdge(newNode.id, this.edgeBeingEdited.to.id);
  28293. this.edgeBeingEdited.controlNodes.from.unselect();
  28294. }
  28295. if (this.edgeBeingEdited.controlNodes.to.selected == true) {
  28296. this._editEdge(this.edgeBeingEdited.from.id, newNode.id);
  28297. this.edgeBeingEdited.controlNodes.to.unselect();
  28298. }
  28299. }
  28300. else {
  28301. this.edgeBeingEdited._restoreControlNodes();
  28302. }
  28303. this.freezeSimulation = false;
  28304. this._redraw();
  28305. };
  28306. /**
  28307. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28308. * to walk the user through the process.
  28309. *
  28310. * @private
  28311. */
  28312. exports._handleConnect = function(pointer) {
  28313. if (this._getSelectedNodeCount() == 0) {
  28314. var node = this._getNodeAt(pointer);
  28315. if (node != null) {
  28316. if (node.clusterSize > 1) {
  28317. alert(this.constants.locales[this.constants.locale]['createEdgeError'])
  28318. }
  28319. else {
  28320. this._selectObject(node,false);
  28321. var supportNodes = this.sectors['support']['nodes'];
  28322. // create a node the temporary line can look at
  28323. supportNodes['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  28324. var targetNode = supportNodes['targetNode'];
  28325. targetNode.x = node.x;
  28326. targetNode.y = node.y;
  28327. // create a temporary edge
  28328. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:targetNode.id}, this, this.constants);
  28329. var connectionEdge = this.edges['connectionEdge'];
  28330. connectionEdge.from = node;
  28331. connectionEdge.connected = true;
  28332. connectionEdge.options.smoothCurves = {enabled: true,
  28333. dynamic: false,
  28334. type: "continuous",
  28335. roundness: 0.5
  28336. };
  28337. connectionEdge.selected = true;
  28338. connectionEdge.to = targetNode;
  28339. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  28340. this._handleOnDrag = function(event) {
  28341. var pointer = this._getPointer(event.gesture.center);
  28342. var connectionEdge = this.edges['connectionEdge'];
  28343. connectionEdge.to.x = this._XconvertDOMtoCanvas(pointer.x);
  28344. connectionEdge.to.y = this._YconvertDOMtoCanvas(pointer.y);
  28345. };
  28346. this.moving = true;
  28347. this.start();
  28348. }
  28349. }
  28350. }
  28351. };
  28352. exports._finishConnect = function(event) {
  28353. if (this._getSelectedNodeCount() == 1) {
  28354. var pointer = this._getPointer(event.gesture.center);
  28355. // restore the drag function
  28356. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  28357. delete this.cachedFunctions["_handleOnDrag"];
  28358. // remember the edge id
  28359. var connectFromId = this.edges['connectionEdge'].fromId;
  28360. // remove the temporary nodes and edge
  28361. delete this.edges['connectionEdge'];
  28362. delete this.sectors['support']['nodes']['targetNode'];
  28363. delete this.sectors['support']['nodes']['targetViaNode'];
  28364. var node = this._getNodeAt(pointer);
  28365. if (node != null) {
  28366. if (node.clusterSize > 1) {
  28367. alert(this.constants.locales[this.constants.locale]["createEdgeError"])
  28368. }
  28369. else {
  28370. this._createEdge(connectFromId,node.id);
  28371. this._createManipulatorBar();
  28372. }
  28373. }
  28374. this._unselectAll();
  28375. }
  28376. };
  28377. /**
  28378. * Adds a node on the specified location
  28379. */
  28380. exports._addNode = function() {
  28381. if (this._selectionIsEmpty() && this.editMode == true) {
  28382. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  28383. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  28384. if (this.triggerFunctions.add) {
  28385. if (this.triggerFunctions.add.length == 2) {
  28386. var me = this;
  28387. this.triggerFunctions.add(defaultData, function(finalizedData) {
  28388. me.nodesData.add(finalizedData);
  28389. me._createManipulatorBar();
  28390. me.moving = true;
  28391. me.start();
  28392. });
  28393. }
  28394. else {
  28395. throw new Error('The function for add does not support two arguments (data,callback)');
  28396. this._createManipulatorBar();
  28397. this.moving = true;
  28398. this.start();
  28399. }
  28400. }
  28401. else {
  28402. this.nodesData.add(defaultData);
  28403. this._createManipulatorBar();
  28404. this.moving = true;
  28405. this.start();
  28406. }
  28407. }
  28408. };
  28409. /**
  28410. * connect two nodes with a new edge.
  28411. *
  28412. * @private
  28413. */
  28414. exports._createEdge = function(sourceNodeId,targetNodeId) {
  28415. if (this.editMode == true) {
  28416. var defaultData = {from:sourceNodeId, to:targetNodeId};
  28417. if (this.triggerFunctions.connect) {
  28418. if (this.triggerFunctions.connect.length == 2) {
  28419. var me = this;
  28420. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  28421. me.edgesData.add(finalizedData);
  28422. me.moving = true;
  28423. me.start();
  28424. });
  28425. }
  28426. else {
  28427. throw new Error('The function for connect does not support two arguments (data,callback)');
  28428. this.moving = true;
  28429. this.start();
  28430. }
  28431. }
  28432. else {
  28433. this.edgesData.add(defaultData);
  28434. this.moving = true;
  28435. this.start();
  28436. }
  28437. }
  28438. };
  28439. /**
  28440. * connect two nodes with a new edge.
  28441. *
  28442. * @private
  28443. */
  28444. exports._editEdge = function(sourceNodeId,targetNodeId) {
  28445. if (this.editMode == true) {
  28446. var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId};
  28447. if (this.triggerFunctions.editEdge) {
  28448. if (this.triggerFunctions.editEdge.length == 2) {
  28449. var me = this;
  28450. this.triggerFunctions.editEdge(defaultData, function(finalizedData) {
  28451. me.edgesData.update(finalizedData);
  28452. me.moving = true;
  28453. me.start();
  28454. });
  28455. }
  28456. else {
  28457. throw new Error('The function for edit does not support two arguments (data, callback)');
  28458. this.moving = true;
  28459. this.start();
  28460. }
  28461. }
  28462. else {
  28463. this.edgesData.update(defaultData);
  28464. this.moving = true;
  28465. this.start();
  28466. }
  28467. }
  28468. };
  28469. /**
  28470. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  28471. *
  28472. * @private
  28473. */
  28474. exports._editNode = function() {
  28475. if (this.triggerFunctions.edit && this.editMode == true) {
  28476. var node = this._getSelectedNode();
  28477. var data = {id:node.id,
  28478. label: node.label,
  28479. group: node.options.group,
  28480. shape: node.options.shape,
  28481. color: {
  28482. background:node.options.color.background,
  28483. border:node.options.color.border,
  28484. highlight: {
  28485. background:node.options.color.highlight.background,
  28486. border:node.options.color.highlight.border
  28487. }
  28488. }};
  28489. if (this.triggerFunctions.edit.length == 2) {
  28490. var me = this;
  28491. this.triggerFunctions.edit(data, function (finalizedData) {
  28492. me.nodesData.update(finalizedData);
  28493. me._createManipulatorBar();
  28494. me.moving = true;
  28495. me.start();
  28496. });
  28497. }
  28498. else {
  28499. throw new Error('The function for edit does not support two arguments (data, callback)');
  28500. }
  28501. }
  28502. else {
  28503. throw new Error('No edit function has been bound to this button');
  28504. }
  28505. };
  28506. /**
  28507. * delete everything in the selection
  28508. *
  28509. * @private
  28510. */
  28511. exports._deleteSelected = function() {
  28512. if (!this._selectionIsEmpty() && this.editMode == true) {
  28513. if (!this._clusterInSelection()) {
  28514. var selectedNodes = this.getSelectedNodes();
  28515. var selectedEdges = this.getSelectedEdges();
  28516. if (this.triggerFunctions.del) {
  28517. var me = this;
  28518. var data = {nodes: selectedNodes, edges: selectedEdges};
  28519. if (this.triggerFunctions.del.length == 2) {
  28520. this.triggerFunctions.del(data, function (finalizedData) {
  28521. me.edgesData.remove(finalizedData.edges);
  28522. me.nodesData.remove(finalizedData.nodes);
  28523. me._unselectAll();
  28524. me.moving = true;
  28525. me.start();
  28526. });
  28527. }
  28528. else {
  28529. throw new Error('The function for delete does not support two arguments (data, callback)')
  28530. }
  28531. }
  28532. else {
  28533. this.edgesData.remove(selectedEdges);
  28534. this.nodesData.remove(selectedNodes);
  28535. this._unselectAll();
  28536. this.moving = true;
  28537. this.start();
  28538. }
  28539. }
  28540. else {
  28541. alert(this.constants.locales[this.constants.locale]["deleteClusterError"]);
  28542. }
  28543. }
  28544. };
  28545. /***/ },
  28546. /* 67 */
  28547. /***/ function(module, exports, __webpack_require__) {
  28548. var util = __webpack_require__(1);
  28549. var Hammer = __webpack_require__(19);
  28550. exports._cleanNavigation = function() {
  28551. // clean hammer bindings
  28552. if (this.navigationHammers.existing.length != 0) {
  28553. for (var i = 0; i < this.navigationHammers.existing.length; i++) {
  28554. this.navigationHammers.existing[i].dispose();
  28555. }
  28556. this.navigationHammers.existing = [];
  28557. }
  28558. this._navigationReleaseOverload = function () {};
  28559. // clean up previous navigation items
  28560. if (this.navigationDivs && this.navigationDivs['wrapper'] && this.navigationDivs['wrapper'].parentNode) {
  28561. this.navigationDivs['wrapper'].parentNode.removeChild(this.navigationDivs['wrapper']);
  28562. }
  28563. };
  28564. /**
  28565. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  28566. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  28567. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  28568. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  28569. *
  28570. * @private
  28571. */
  28572. exports._loadNavigationElements = function() {
  28573. this._cleanNavigation();
  28574. this.navigationDivs = {};
  28575. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  28576. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','_zoomExtent'];
  28577. this.navigationDivs['wrapper'] = document.createElement('div');
  28578. this.frame.appendChild(this.navigationDivs['wrapper']);
  28579. for (var i = 0; i < navigationDivs.length; i++) {
  28580. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  28581. this.navigationDivs[navigationDivs[i]].className = 'network-navigation ' + navigationDivs[i];
  28582. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  28583. var hammer = Hammer(this.navigationDivs[navigationDivs[i]], {prevent_default: true});
  28584. hammer.on('touch', this[navigationDivActions[i]].bind(this));
  28585. this.navigationHammers._new.push(hammer);
  28586. }
  28587. this._navigationReleaseOverload = this._stopMovement;
  28588. this.navigationHammers.existing = this.navigationHammers._new;
  28589. };
  28590. /**
  28591. * this stops all movement induced by the navigation buttons
  28592. *
  28593. * @private
  28594. */
  28595. exports._zoomExtent = function(event) {
  28596. this.zoomExtent({duration:700});
  28597. event.stopPropagation();
  28598. };
  28599. /**
  28600. * this stops all movement induced by the navigation buttons
  28601. *
  28602. * @private
  28603. */
  28604. exports._stopMovement = function() {
  28605. this._xStopMoving();
  28606. this._yStopMoving();
  28607. this._stopZoom();
  28608. };
  28609. /**
  28610. * move the screen up
  28611. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  28612. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  28613. * To avoid this behaviour, we do the translation in the start loop.
  28614. *
  28615. * @private
  28616. */
  28617. exports._moveUp = function(event) {
  28618. this.yIncrement = this.constants.keyboard.speed.y;
  28619. this.start(); // if there is no node movement, the calculation wont be done
  28620. event.preventDefault();
  28621. };
  28622. /**
  28623. * move the screen down
  28624. * @private
  28625. */
  28626. exports._moveDown = function(event) {
  28627. this.yIncrement = -this.constants.keyboard.speed.y;
  28628. this.start(); // if there is no node movement, the calculation wont be done
  28629. event.preventDefault();
  28630. };
  28631. /**
  28632. * move the screen left
  28633. * @private
  28634. */
  28635. exports._moveLeft = function(event) {
  28636. this.xIncrement = this.constants.keyboard.speed.x;
  28637. this.start(); // if there is no node movement, the calculation wont be done
  28638. event.preventDefault();
  28639. };
  28640. /**
  28641. * move the screen right
  28642. * @private
  28643. */
  28644. exports._moveRight = function(event) {
  28645. this.xIncrement = -this.constants.keyboard.speed.y;
  28646. this.start(); // if there is no node movement, the calculation wont be done
  28647. event.preventDefault();
  28648. };
  28649. /**
  28650. * Zoom in, using the same method as the movement.
  28651. * @private
  28652. */
  28653. exports._zoomIn = function(event) {
  28654. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  28655. this.start(); // if there is no node movement, the calculation wont be done
  28656. event.preventDefault();
  28657. };
  28658. /**
  28659. * Zoom out
  28660. * @private
  28661. */
  28662. exports._zoomOut = function(event) {
  28663. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  28664. this.start(); // if there is no node movement, the calculation wont be done
  28665. event.preventDefault();
  28666. };
  28667. /**
  28668. * Stop zooming and unhighlight the zoom controls
  28669. * @private
  28670. */
  28671. exports._stopZoom = function(event) {
  28672. this.zoomIncrement = 0;
  28673. event && event.preventDefault();
  28674. };
  28675. /**
  28676. * Stop moving in the Y direction and unHighlight the up and down
  28677. * @private
  28678. */
  28679. exports._yStopMoving = function(event) {
  28680. this.yIncrement = 0;
  28681. event && event.preventDefault();
  28682. };
  28683. /**
  28684. * Stop moving in the X direction and unHighlight left and right.
  28685. * @private
  28686. */
  28687. exports._xStopMoving = function(event) {
  28688. this.xIncrement = 0;
  28689. event && event.preventDefault();
  28690. };
  28691. /***/ },
  28692. /* 68 */
  28693. /***/ function(module, exports, __webpack_require__) {
  28694. exports._resetLevels = function() {
  28695. for (var nodeId in this.nodes) {
  28696. if (this.nodes.hasOwnProperty(nodeId)) {
  28697. var node = this.nodes[nodeId];
  28698. if (node.preassignedLevel == false) {
  28699. node.level = -1;
  28700. node.hierarchyEnumerated = false;
  28701. }
  28702. }
  28703. }
  28704. };
  28705. /**
  28706. * This is the main function to layout the nodes in a hierarchical way.
  28707. * It checks if the node details are supplied correctly
  28708. *
  28709. * @private
  28710. */
  28711. exports._setupHierarchicalLayout = function() {
  28712. if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) {
  28713. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  28714. this.constants.hierarchicalLayout.levelSeparation = this.constants.hierarchicalLayout.levelSeparation < 0 ? this.constants.hierarchicalLayout.levelSeparation : this.constants.hierarchicalLayout.levelSeparation * -1;
  28715. }
  28716. else {
  28717. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  28718. }
  28719. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") {
  28720. if (this.constants.smoothCurves.enabled == true) {
  28721. this.constants.smoothCurves.type = "vertical";
  28722. }
  28723. }
  28724. else {
  28725. if (this.constants.smoothCurves.enabled == true) {
  28726. this.constants.smoothCurves.type = "horizontal";
  28727. }
  28728. }
  28729. // get the size of the largest hubs and check if the user has defined a level for a node.
  28730. var hubsize = 0;
  28731. var node, nodeId;
  28732. var definedLevel = false;
  28733. var undefinedLevel = false;
  28734. for (nodeId in this.nodes) {
  28735. if (this.nodes.hasOwnProperty(nodeId)) {
  28736. node = this.nodes[nodeId];
  28737. if (node.level != -1) {
  28738. definedLevel = true;
  28739. }
  28740. else {
  28741. undefinedLevel = true;
  28742. }
  28743. if (hubsize < node.edges.length) {
  28744. hubsize = node.edges.length;
  28745. }
  28746. }
  28747. }
  28748. // if the user defined some levels but not all, alert and run without hierarchical layout
  28749. if (undefinedLevel == true && definedLevel == true) {
  28750. throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  28751. this.zoomExtent(undefined,true,this.constants.clustering.enabled);
  28752. if (!this.constants.clustering.enabled) {
  28753. this.start();
  28754. }
  28755. }
  28756. else {
  28757. // setup the system to use hierarchical method.
  28758. this._changeConstants();
  28759. // define levels if undefined by the users. Based on hubsize
  28760. if (undefinedLevel == true) {
  28761. if (this.constants.hierarchicalLayout.layout == "hubsize") {
  28762. this._determineLevels(hubsize);
  28763. }
  28764. else {
  28765. this._determineLevelsDirected();
  28766. }
  28767. }
  28768. // check the distribution of the nodes per level.
  28769. var distribution = this._getDistribution();
  28770. // place the nodes on the canvas. This also stablilizes the system.
  28771. this._placeNodesByHierarchy(distribution);
  28772. // start the simulation.
  28773. this.start();
  28774. }
  28775. }
  28776. };
  28777. /**
  28778. * This function places the nodes on the canvas based on the hierarchial distribution.
  28779. *
  28780. * @param {Object} distribution | obtained by the function this._getDistribution()
  28781. * @private
  28782. */
  28783. exports._placeNodesByHierarchy = function(distribution) {
  28784. var nodeId, node;
  28785. // start placing all the level 0 nodes first. Then recursively position their branches.
  28786. for (var level in distribution) {
  28787. if (distribution.hasOwnProperty(level)) {
  28788. for (nodeId in distribution[level].nodes) {
  28789. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  28790. node = distribution[level].nodes[nodeId];
  28791. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  28792. if (node.xFixed) {
  28793. node.x = distribution[level].minPos;
  28794. node.xFixed = false;
  28795. distribution[level].minPos += distribution[level].nodeSpacing;
  28796. }
  28797. }
  28798. else {
  28799. if (node.yFixed) {
  28800. node.y = distribution[level].minPos;
  28801. node.yFixed = false;
  28802. distribution[level].minPos += distribution[level].nodeSpacing;
  28803. }
  28804. }
  28805. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  28806. }
  28807. }
  28808. }
  28809. }
  28810. // stabilize the system after positioning. This function calls zoomExtent.
  28811. this._stabilize();
  28812. };
  28813. /**
  28814. * This function get the distribution of levels based on hubsize
  28815. *
  28816. * @returns {Object}
  28817. * @private
  28818. */
  28819. exports._getDistribution = function() {
  28820. var distribution = {};
  28821. var nodeId, node, level;
  28822. // 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.
  28823. // the fix of X is removed after the x value has been set.
  28824. for (nodeId in this.nodes) {
  28825. if (this.nodes.hasOwnProperty(nodeId)) {
  28826. node = this.nodes[nodeId];
  28827. node.xFixed = true;
  28828. node.yFixed = true;
  28829. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  28830. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  28831. }
  28832. else {
  28833. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  28834. }
  28835. if (distribution[node.level] === undefined) {
  28836. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  28837. }
  28838. distribution[node.level].amount += 1;
  28839. distribution[node.level].nodes[nodeId] = node;
  28840. }
  28841. }
  28842. // determine the largest amount of nodes of all levels
  28843. var maxCount = 0;
  28844. for (level in distribution) {
  28845. if (distribution.hasOwnProperty(level)) {
  28846. if (maxCount < distribution[level].amount) {
  28847. maxCount = distribution[level].amount;
  28848. }
  28849. }
  28850. }
  28851. // set the initial position and spacing of each nodes accordingly
  28852. for (level in distribution) {
  28853. if (distribution.hasOwnProperty(level)) {
  28854. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  28855. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  28856. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  28857. }
  28858. }
  28859. return distribution;
  28860. };
  28861. /**
  28862. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  28863. *
  28864. * @param hubsize
  28865. * @private
  28866. */
  28867. exports._determineLevels = function(hubsize) {
  28868. var nodeId, node;
  28869. // determine hubs
  28870. for (nodeId in this.nodes) {
  28871. if (this.nodes.hasOwnProperty(nodeId)) {
  28872. node = this.nodes[nodeId];
  28873. if (node.edges.length == hubsize) {
  28874. node.level = 0;
  28875. }
  28876. }
  28877. }
  28878. // branch from hubs
  28879. for (nodeId in this.nodes) {
  28880. if (this.nodes.hasOwnProperty(nodeId)) {
  28881. node = this.nodes[nodeId];
  28882. if (node.level == 0) {
  28883. this._setLevel(1,node.edges,node.id);
  28884. }
  28885. }
  28886. }
  28887. };
  28888. /**
  28889. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  28890. *
  28891. * @param hubsize
  28892. * @private
  28893. */
  28894. exports._determineLevelsDirected = function() {
  28895. var nodeId, node;
  28896. // set first node to source
  28897. for (nodeId in this.nodes) {
  28898. if (this.nodes.hasOwnProperty(nodeId)) {
  28899. this.nodes[nodeId].level = 10000;
  28900. break;
  28901. }
  28902. }
  28903. // branch from hubs
  28904. for (nodeId in this.nodes) {
  28905. if (this.nodes.hasOwnProperty(nodeId)) {
  28906. node = this.nodes[nodeId];
  28907. if (node.level == 10000) {
  28908. this._setLevelDirected(10000,node.edges,node.id);
  28909. }
  28910. }
  28911. }
  28912. // branch from hubs
  28913. var minLevel = 10000;
  28914. for (nodeId in this.nodes) {
  28915. if (this.nodes.hasOwnProperty(nodeId)) {
  28916. node = this.nodes[nodeId];
  28917. minLevel = node.level < minLevel ? node.level : minLevel;
  28918. }
  28919. }
  28920. // branch from hubs
  28921. for (nodeId in this.nodes) {
  28922. if (this.nodes.hasOwnProperty(nodeId)) {
  28923. node = this.nodes[nodeId];
  28924. node.level -= minLevel;
  28925. }
  28926. }
  28927. };
  28928. /**
  28929. * Since hierarchical layout does not support:
  28930. * - smooth curves (based on the physics),
  28931. * - clustering (based on dynamic node counts)
  28932. *
  28933. * We disable both features so there will be no problems.
  28934. *
  28935. * @private
  28936. */
  28937. exports._changeConstants = function() {
  28938. this.constants.clustering.enabled = false;
  28939. this.constants.physics.barnesHut.enabled = false;
  28940. this.constants.physics.hierarchicalRepulsion.enabled = true;
  28941. this._loadSelectedForceSolver();
  28942. if (this.constants.smoothCurves.enabled == true) {
  28943. this.constants.smoothCurves.dynamic = false;
  28944. }
  28945. this._configureSmoothCurves();
  28946. };
  28947. /**
  28948. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  28949. * on a X position that ensures there will be no overlap.
  28950. *
  28951. * @param edges
  28952. * @param parentId
  28953. * @param distribution
  28954. * @param parentLevel
  28955. * @private
  28956. */
  28957. exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) {
  28958. for (var i = 0; i < edges.length; i++) {
  28959. var childNode = null;
  28960. if (edges[i].toId == parentId) {
  28961. childNode = edges[i].from;
  28962. }
  28963. else {
  28964. childNode = edges[i].to;
  28965. }
  28966. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  28967. var nodeMoved = false;
  28968. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  28969. if (childNode.xFixed && childNode.level > parentLevel) {
  28970. childNode.xFixed = false;
  28971. childNode.x = distribution[childNode.level].minPos;
  28972. nodeMoved = true;
  28973. }
  28974. }
  28975. else {
  28976. if (childNode.yFixed && childNode.level > parentLevel) {
  28977. childNode.yFixed = false;
  28978. childNode.y = distribution[childNode.level].minPos;
  28979. nodeMoved = true;
  28980. }
  28981. }
  28982. if (nodeMoved == true) {
  28983. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  28984. if (childNode.edges.length > 1) {
  28985. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  28986. }
  28987. }
  28988. }
  28989. };
  28990. /**
  28991. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  28992. *
  28993. * @param level
  28994. * @param edges
  28995. * @param parentId
  28996. * @private
  28997. */
  28998. exports._setLevel = function(level, edges, parentId) {
  28999. for (var i = 0; i < edges.length; i++) {
  29000. var childNode = null;
  29001. if (edges[i].toId == parentId) {
  29002. childNode = edges[i].from;
  29003. }
  29004. else {
  29005. childNode = edges[i].to;
  29006. }
  29007. if (childNode.level == -1 || childNode.level > level) {
  29008. childNode.level = level;
  29009. if (childNode.edges.length > 1) {
  29010. this._setLevel(level+1, childNode.edges, childNode.id);
  29011. }
  29012. }
  29013. }
  29014. };
  29015. /**
  29016. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  29017. *
  29018. * @param level
  29019. * @param edges
  29020. * @param parentId
  29021. * @private
  29022. */
  29023. exports._setLevelDirected = function(level, edges, parentId) {
  29024. this.nodes[parentId].hierarchyEnumerated = true;
  29025. for (var i = 0; i < edges.length; i++) {
  29026. var childNode = null;
  29027. var direction = 1;
  29028. if (edges[i].toId == parentId) {
  29029. childNode = edges[i].from;
  29030. direction = -1;
  29031. }
  29032. else {
  29033. childNode = edges[i].to;
  29034. }
  29035. if (childNode.level == -1) {
  29036. childNode.level = level + direction;
  29037. }
  29038. }
  29039. for (var i = 0; i < edges.length; i++) {
  29040. var childNode = null;
  29041. if (edges[i].toId == parentId) {childNode = edges[i].from;}
  29042. else {childNode = edges[i].to;}
  29043. if (childNode.edges.length > 1 && childNode.hierarchyEnumerated === false) {
  29044. this._setLevelDirected(childNode.level, childNode.edges, childNode.id);
  29045. }
  29046. }
  29047. };
  29048. /**
  29049. * Unfix nodes
  29050. *
  29051. * @private
  29052. */
  29053. exports._restoreNodes = function() {
  29054. for (var nodeId in this.nodes) {
  29055. if (this.nodes.hasOwnProperty(nodeId)) {
  29056. this.nodes[nodeId].xFixed = false;
  29057. this.nodes[nodeId].yFixed = false;
  29058. }
  29059. }
  29060. };
  29061. /***/ },
  29062. /* 69 */
  29063. /***/ function(module, exports, __webpack_require__) {
  29064. /**
  29065. * Calculate the forces the nodes apply on each other based on a repulsion field.
  29066. * This field is linearly approximated.
  29067. *
  29068. * @private
  29069. */
  29070. exports._calculateNodeForces = function () {
  29071. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  29072. repulsingForce, node1, node2, i, j;
  29073. var nodes = this.calculationNodes;
  29074. var nodeIndices = this.calculationNodeIndices;
  29075. // approximation constants
  29076. var a_base = -2 / 3;
  29077. var b = 4 / 3;
  29078. // repulsing forces between nodes
  29079. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  29080. var minimumDistance = nodeDistance;
  29081. // we loop from i over all but the last entree in the array
  29082. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  29083. for (i = 0; i < nodeIndices.length - 1; i++) {
  29084. node1 = nodes[nodeIndices[i]];
  29085. for (j = i + 1; j < nodeIndices.length; j++) {
  29086. node2 = nodes[nodeIndices[j]];
  29087. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  29088. dx = node2.x - node1.x;
  29089. dy = node2.y - node1.y;
  29090. distance = Math.sqrt(dx * dx + dy * dy);
  29091. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  29092. var a = a_base / minimumDistance;
  29093. if (distance < 2 * minimumDistance) {
  29094. if (distance < 0.5 * minimumDistance) {
  29095. repulsingForce = 1.0;
  29096. }
  29097. else {
  29098. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  29099. }
  29100. // amplify the repulsion for clusters.
  29101. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  29102. repulsingForce = repulsingForce / distance;
  29103. fx = dx * repulsingForce;
  29104. fy = dy * repulsingForce;
  29105. node1.fx -= fx;
  29106. node1.fy -= fy;
  29107. node2.fx += fx;
  29108. node2.fy += fy;
  29109. }
  29110. }
  29111. }
  29112. };
  29113. /***/ },
  29114. /* 70 */
  29115. /***/ function(module, exports, __webpack_require__) {
  29116. /**
  29117. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  29118. * This field is linearly approximated.
  29119. *
  29120. * @private
  29121. */
  29122. exports._calculateNodeForces = function () {
  29123. var dx, dy, distance, fx, fy,
  29124. repulsingForce, node1, node2, i, j;
  29125. var nodes = this.calculationNodes;
  29126. var nodeIndices = this.calculationNodeIndices;
  29127. // repulsing forces between nodes
  29128. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  29129. // we loop from i over all but the last entree in the array
  29130. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  29131. for (i = 0; i < nodeIndices.length - 1; i++) {
  29132. node1 = nodes[nodeIndices[i]];
  29133. for (j = i + 1; j < nodeIndices.length; j++) {
  29134. node2 = nodes[nodeIndices[j]];
  29135. // nodes only affect nodes on their level
  29136. if (node1.level == node2.level) {
  29137. dx = node2.x - node1.x;
  29138. dy = node2.y - node1.y;
  29139. distance = Math.sqrt(dx * dx + dy * dy);
  29140. var steepness = 0.05;
  29141. if (distance < nodeDistance) {
  29142. repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2);
  29143. }
  29144. else {
  29145. repulsingForce = 0;
  29146. }
  29147. // normalize force with
  29148. if (distance == 0) {
  29149. distance = 0.01;
  29150. }
  29151. else {
  29152. repulsingForce = repulsingForce / distance;
  29153. }
  29154. fx = dx * repulsingForce;
  29155. fy = dy * repulsingForce;
  29156. node1.fx -= fx;
  29157. node1.fy -= fy;
  29158. node2.fx += fx;
  29159. node2.fy += fy;
  29160. }
  29161. }
  29162. }
  29163. };
  29164. /**
  29165. * this function calculates the effects of the springs in the case of unsmooth curves.
  29166. *
  29167. * @private
  29168. */
  29169. exports._calculateHierarchicalSpringForces = function () {
  29170. var edgeLength, edge, edgeId;
  29171. var dx, dy, fx, fy, springForce, distance;
  29172. var edges = this.edges;
  29173. var nodes = this.calculationNodes;
  29174. var nodeIndices = this.calculationNodeIndices;
  29175. for (var i = 0; i < nodeIndices.length; i++) {
  29176. var node1 = nodes[nodeIndices[i]];
  29177. node1.springFx = 0;
  29178. node1.springFy = 0;
  29179. }
  29180. // forces caused by the edges, modelled as springs
  29181. for (edgeId in edges) {
  29182. if (edges.hasOwnProperty(edgeId)) {
  29183. edge = edges[edgeId];
  29184. if (edge.connected) {
  29185. // only calculate forces if nodes are in the same sector
  29186. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  29187. edgeLength = edge.physics.springLength;
  29188. // this implies that the edges between big clusters are longer
  29189. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  29190. dx = (edge.from.x - edge.to.x);
  29191. dy = (edge.from.y - edge.to.y);
  29192. distance = Math.sqrt(dx * dx + dy * dy);
  29193. if (distance == 0) {
  29194. distance = 0.01;
  29195. }
  29196. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  29197. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  29198. fx = dx * springForce;
  29199. fy = dy * springForce;
  29200. if (edge.to.level != edge.from.level) {
  29201. edge.to.springFx -= fx;
  29202. edge.to.springFy -= fy;
  29203. edge.from.springFx += fx;
  29204. edge.from.springFy += fy;
  29205. }
  29206. else {
  29207. var factor = 0.5;
  29208. edge.to.fx -= factor*fx;
  29209. edge.to.fy -= factor*fy;
  29210. edge.from.fx += factor*fx;
  29211. edge.from.fy += factor*fy;
  29212. }
  29213. }
  29214. }
  29215. }
  29216. }
  29217. // normalize spring forces
  29218. var springForce = 1;
  29219. var springFx, springFy;
  29220. for (i = 0; i < nodeIndices.length; i++) {
  29221. var node = nodes[nodeIndices[i]];
  29222. springFx = Math.min(springForce,Math.max(-springForce,node.springFx));
  29223. springFy = Math.min(springForce,Math.max(-springForce,node.springFy));
  29224. node.fx += springFx;
  29225. node.fy += springFy;
  29226. }
  29227. // retain energy balance
  29228. var totalFx = 0;
  29229. var totalFy = 0;
  29230. for (i = 0; i < nodeIndices.length; i++) {
  29231. var node = nodes[nodeIndices[i]];
  29232. totalFx += node.fx;
  29233. totalFy += node.fy;
  29234. }
  29235. var correctionFx = totalFx / nodeIndices.length;
  29236. var correctionFy = totalFy / nodeIndices.length;
  29237. for (i = 0; i < nodeIndices.length; i++) {
  29238. var node = nodes[nodeIndices[i]];
  29239. node.fx -= correctionFx;
  29240. node.fy -= correctionFy;
  29241. }
  29242. };
  29243. /***/ },
  29244. /* 71 */
  29245. /***/ function(module, exports, __webpack_require__) {
  29246. /**
  29247. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  29248. * The Barnes Hut method is used to speed up this N-body simulation.
  29249. *
  29250. * @private
  29251. */
  29252. exports._calculateNodeForces = function() {
  29253. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  29254. var node;
  29255. var nodes = this.calculationNodes;
  29256. var nodeIndices = this.calculationNodeIndices;
  29257. var nodeCount = nodeIndices.length;
  29258. this._formBarnesHutTree(nodes,nodeIndices);
  29259. var barnesHutTree = this.barnesHutTree;
  29260. // place the nodes one by one recursively
  29261. for (var i = 0; i < nodeCount; i++) {
  29262. node = nodes[nodeIndices[i]];
  29263. if (node.options.mass > 0) {
  29264. // starting with root is irrelevant, it never passes the BarnesHut condition
  29265. this._getForceContribution(barnesHutTree.root.children.NW,node);
  29266. this._getForceContribution(barnesHutTree.root.children.NE,node);
  29267. this._getForceContribution(barnesHutTree.root.children.SW,node);
  29268. this._getForceContribution(barnesHutTree.root.children.SE,node);
  29269. }
  29270. }
  29271. }
  29272. };
  29273. /**
  29274. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  29275. * If a region contains a single node, we check if it is not itself, then we apply the force.
  29276. *
  29277. * @param parentBranch
  29278. * @param node
  29279. * @private
  29280. */
  29281. exports._getForceContribution = function(parentBranch,node) {
  29282. // we get no force contribution from an empty region
  29283. if (parentBranch.childrenCount > 0) {
  29284. var dx,dy,distance;
  29285. // get the distance from the center of mass to the node.
  29286. dx = parentBranch.centerOfMass.x - node.x;
  29287. dy = parentBranch.centerOfMass.y - node.y;
  29288. distance = Math.sqrt(dx * dx + dy * dy);
  29289. // BarnesHut condition
  29290. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  29291. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  29292. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  29293. // duplicate code to reduce function calls to speed up program
  29294. if (distance == 0) {
  29295. distance = 0.1*Math.random();
  29296. dx = distance;
  29297. }
  29298. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  29299. var fx = dx * gravityForce;
  29300. var fy = dy * gravityForce;
  29301. node.fx += fx;
  29302. node.fy += fy;
  29303. }
  29304. else {
  29305. // Did not pass the condition, go into children if available
  29306. if (parentBranch.childrenCount == 4) {
  29307. this._getForceContribution(parentBranch.children.NW,node);
  29308. this._getForceContribution(parentBranch.children.NE,node);
  29309. this._getForceContribution(parentBranch.children.SW,node);
  29310. this._getForceContribution(parentBranch.children.SE,node);
  29311. }
  29312. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  29313. if (parentBranch.children.data.id != node.id) { // if it is not self
  29314. // duplicate code to reduce function calls to speed up program
  29315. if (distance == 0) {
  29316. distance = 0.5*Math.random();
  29317. dx = distance;
  29318. }
  29319. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  29320. var fx = dx * gravityForce;
  29321. var fy = dy * gravityForce;
  29322. node.fx += fx;
  29323. node.fy += fy;
  29324. }
  29325. }
  29326. }
  29327. }
  29328. };
  29329. /**
  29330. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  29331. *
  29332. * @param nodes
  29333. * @param nodeIndices
  29334. * @private
  29335. */
  29336. exports._formBarnesHutTree = function(nodes,nodeIndices) {
  29337. var node;
  29338. var nodeCount = nodeIndices.length;
  29339. var minX = Number.MAX_VALUE,
  29340. minY = Number.MAX_VALUE,
  29341. maxX =-Number.MAX_VALUE,
  29342. maxY =-Number.MAX_VALUE;
  29343. // get the range of the nodes
  29344. for (var i = 0; i < nodeCount; i++) {
  29345. var x = nodes[nodeIndices[i]].x;
  29346. var y = nodes[nodeIndices[i]].y;
  29347. if (nodes[nodeIndices[i]].options.mass > 0) {
  29348. if (x < minX) { minX = x; }
  29349. if (x > maxX) { maxX = x; }
  29350. if (y < minY) { minY = y; }
  29351. if (y > maxY) { maxY = y; }
  29352. }
  29353. }
  29354. // make the range a square
  29355. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  29356. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  29357. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  29358. var minimumTreeSize = 1e-5;
  29359. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  29360. var halfRootSize = 0.5 * rootSize;
  29361. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  29362. // construct the barnesHutTree
  29363. var barnesHutTree = {
  29364. root:{
  29365. centerOfMass: {x:0, y:0},
  29366. mass:0,
  29367. range: {
  29368. minX: centerX-halfRootSize,maxX:centerX+halfRootSize,
  29369. minY: centerY-halfRootSize,maxY:centerY+halfRootSize
  29370. },
  29371. size: rootSize,
  29372. calcSize: 1 / rootSize,
  29373. children: { data:null},
  29374. maxWidth: 0,
  29375. level: 0,
  29376. childrenCount: 4
  29377. }
  29378. };
  29379. this._splitBranch(barnesHutTree.root);
  29380. // place the nodes one by one recursively
  29381. for (i = 0; i < nodeCount; i++) {
  29382. node = nodes[nodeIndices[i]];
  29383. if (node.options.mass > 0) {
  29384. this._placeInTree(barnesHutTree.root,node);
  29385. }
  29386. }
  29387. // make global
  29388. this.barnesHutTree = barnesHutTree
  29389. };
  29390. /**
  29391. * this updates the mass of a branch. this is increased by adding a node.
  29392. *
  29393. * @param parentBranch
  29394. * @param node
  29395. * @private
  29396. */
  29397. exports._updateBranchMass = function(parentBranch, node) {
  29398. var totalMass = parentBranch.mass + node.options.mass;
  29399. var totalMassInv = 1/totalMass;
  29400. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  29401. parentBranch.centerOfMass.x *= totalMassInv;
  29402. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  29403. parentBranch.centerOfMass.y *= totalMassInv;
  29404. parentBranch.mass = totalMass;
  29405. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  29406. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  29407. };
  29408. /**
  29409. * determine in which branch the node will be placed.
  29410. *
  29411. * @param parentBranch
  29412. * @param node
  29413. * @param skipMassUpdate
  29414. * @private
  29415. */
  29416. exports._placeInTree = function(parentBranch,node,skipMassUpdate) {
  29417. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  29418. // update the mass of the branch.
  29419. this._updateBranchMass(parentBranch,node);
  29420. }
  29421. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  29422. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  29423. this._placeInRegion(parentBranch,node,"NW");
  29424. }
  29425. else { // in SW
  29426. this._placeInRegion(parentBranch,node,"SW");
  29427. }
  29428. }
  29429. else { // in NE or SE
  29430. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  29431. this._placeInRegion(parentBranch,node,"NE");
  29432. }
  29433. else { // in SE
  29434. this._placeInRegion(parentBranch,node,"SE");
  29435. }
  29436. }
  29437. };
  29438. /**
  29439. * actually place the node in a region (or branch)
  29440. *
  29441. * @param parentBranch
  29442. * @param node
  29443. * @param region
  29444. * @private
  29445. */
  29446. exports._placeInRegion = function(parentBranch,node,region) {
  29447. switch (parentBranch.children[region].childrenCount) {
  29448. case 0: // place node here
  29449. parentBranch.children[region].children.data = node;
  29450. parentBranch.children[region].childrenCount = 1;
  29451. this._updateBranchMass(parentBranch.children[region],node);
  29452. break;
  29453. case 1: // convert into children
  29454. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  29455. // we move one node a pixel and we do not put it in the tree.
  29456. if (parentBranch.children[region].children.data.x == node.x &&
  29457. parentBranch.children[region].children.data.y == node.y) {
  29458. node.x += Math.random();
  29459. node.y += Math.random();
  29460. }
  29461. else {
  29462. this._splitBranch(parentBranch.children[region]);
  29463. this._placeInTree(parentBranch.children[region],node);
  29464. }
  29465. break;
  29466. case 4: // place in branch
  29467. this._placeInTree(parentBranch.children[region],node);
  29468. break;
  29469. }
  29470. };
  29471. /**
  29472. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  29473. * after the split is complete.
  29474. *
  29475. * @param parentBranch
  29476. * @private
  29477. */
  29478. exports._splitBranch = function(parentBranch) {
  29479. // if the branch is shaded with a node, replace the node in the new subset.
  29480. var containedNode = null;
  29481. if (parentBranch.childrenCount == 1) {
  29482. containedNode = parentBranch.children.data;
  29483. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  29484. }
  29485. parentBranch.childrenCount = 4;
  29486. parentBranch.children.data = null;
  29487. this._insertRegion(parentBranch,"NW");
  29488. this._insertRegion(parentBranch,"NE");
  29489. this._insertRegion(parentBranch,"SW");
  29490. this._insertRegion(parentBranch,"SE");
  29491. if (containedNode != null) {
  29492. this._placeInTree(parentBranch,containedNode);
  29493. }
  29494. };
  29495. /**
  29496. * This function subdivides the region into four new segments.
  29497. * Specifically, this inserts a single new segment.
  29498. * It fills the children section of the parentBranch
  29499. *
  29500. * @param parentBranch
  29501. * @param region
  29502. * @param parentRange
  29503. * @private
  29504. */
  29505. exports._insertRegion = function(parentBranch, region) {
  29506. var minX,maxX,minY,maxY;
  29507. var childSize = 0.5 * parentBranch.size;
  29508. switch (region) {
  29509. case "NW":
  29510. minX = parentBranch.range.minX;
  29511. maxX = parentBranch.range.minX + childSize;
  29512. minY = parentBranch.range.minY;
  29513. maxY = parentBranch.range.minY + childSize;
  29514. break;
  29515. case "NE":
  29516. minX = parentBranch.range.minX + childSize;
  29517. maxX = parentBranch.range.maxX;
  29518. minY = parentBranch.range.minY;
  29519. maxY = parentBranch.range.minY + childSize;
  29520. break;
  29521. case "SW":
  29522. minX = parentBranch.range.minX;
  29523. maxX = parentBranch.range.minX + childSize;
  29524. minY = parentBranch.range.minY + childSize;
  29525. maxY = parentBranch.range.maxY;
  29526. break;
  29527. case "SE":
  29528. minX = parentBranch.range.minX + childSize;
  29529. maxX = parentBranch.range.maxX;
  29530. minY = parentBranch.range.minY + childSize;
  29531. maxY = parentBranch.range.maxY;
  29532. break;
  29533. }
  29534. parentBranch.children[region] = {
  29535. centerOfMass:{x:0,y:0},
  29536. mass:0,
  29537. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  29538. size: 0.5 * parentBranch.size,
  29539. calcSize: 2 * parentBranch.calcSize,
  29540. children: {data:null},
  29541. maxWidth: 0,
  29542. level: parentBranch.level+1,
  29543. childrenCount: 0
  29544. };
  29545. };
  29546. /**
  29547. * This function is for debugging purposed, it draws the tree.
  29548. *
  29549. * @param ctx
  29550. * @param color
  29551. * @private
  29552. */
  29553. exports._drawTree = function(ctx,color) {
  29554. if (this.barnesHutTree !== undefined) {
  29555. ctx.lineWidth = 1;
  29556. this._drawBranch(this.barnesHutTree.root,ctx,color);
  29557. }
  29558. };
  29559. /**
  29560. * This function is for debugging purposes. It draws the branches recursively.
  29561. *
  29562. * @param branch
  29563. * @param ctx
  29564. * @param color
  29565. * @private
  29566. */
  29567. exports._drawBranch = function(branch,ctx,color) {
  29568. if (color === undefined) {
  29569. color = "#FF0000";
  29570. }
  29571. if (branch.childrenCount == 4) {
  29572. this._drawBranch(branch.children.NW,ctx);
  29573. this._drawBranch(branch.children.NE,ctx);
  29574. this._drawBranch(branch.children.SE,ctx);
  29575. this._drawBranch(branch.children.SW,ctx);
  29576. }
  29577. ctx.strokeStyle = color;
  29578. ctx.beginPath();
  29579. ctx.moveTo(branch.range.minX,branch.range.minY);
  29580. ctx.lineTo(branch.range.maxX,branch.range.minY);
  29581. ctx.stroke();
  29582. ctx.beginPath();
  29583. ctx.moveTo(branch.range.maxX,branch.range.minY);
  29584. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  29585. ctx.stroke();
  29586. ctx.beginPath();
  29587. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  29588. ctx.lineTo(branch.range.minX,branch.range.maxY);
  29589. ctx.stroke();
  29590. ctx.beginPath();
  29591. ctx.moveTo(branch.range.minX,branch.range.maxY);
  29592. ctx.lineTo(branch.range.minX,branch.range.minY);
  29593. ctx.stroke();
  29594. /*
  29595. if (branch.mass > 0) {
  29596. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  29597. ctx.stroke();
  29598. }
  29599. */
  29600. };
  29601. /***/ }
  29602. /******/ ])
  29603. });