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.

34004 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-22
  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__(50),
  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__(45),
  120. Group: __webpack_require__(27),
  121. BackgroundGroup: __webpack_require__(31),
  122. ItemSet: __webpack_require__(26),
  123. Legend: __webpack_require__(49),
  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__(57),
  132. Groups: __webpack_require__(54),
  133. Images: __webpack_require__(55),
  134. Node: __webpack_require__(56),
  135. Popup: __webpack_require__(58),
  136. dotparser: __webpack_require__(52),
  137. gephiParser: __webpack_require__(53)
  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__(45);
  17056. var Legend = __webpack_require__(49);
  17057. var BarGraphFunctions = __webpack_require__(48);
  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__(50);
  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. var util = __webpack_require__(1);
  18473. var DOMutil = __webpack_require__(6);
  18474. var Line = __webpack_require__(46);
  18475. var Bar = __webpack_require__(48);
  18476. var Points = __webpack_require__(47);
  18477. /**
  18478. * /**
  18479. * @param {object} group | the object of the group from the dataset
  18480. * @param {string} groupId | ID of the group
  18481. * @param {object} options | the default options
  18482. * @param {array} groupsUsingDefaultStyles | this array has one entree.
  18483. * It is passed as an array so it is passed by reference.
  18484. * It enumerates through the default styles
  18485. * @constructor
  18486. */
  18487. function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) {
  18488. this.id = groupId;
  18489. var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom']
  18490. this.options = util.selectiveBridgeObject(fields,options);
  18491. this.usingDefaultStyle = group.className === undefined;
  18492. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  18493. this.zeroPosition = 0;
  18494. this.update(group);
  18495. if (this.usingDefaultStyle == true) {
  18496. this.groupsUsingDefaultStyles[0] += 1;
  18497. }
  18498. this.itemsData = [];
  18499. this.visible = group.visible === undefined ? true : group.visible;
  18500. }
  18501. /**
  18502. * this loads a reference to all items in this group into this group.
  18503. * @param {array} items
  18504. */
  18505. GraphGroup.prototype.setItems = function(items) {
  18506. if (items != null) {
  18507. this.itemsData = items;
  18508. if (this.options.sort == true) {
  18509. this.itemsData.sort(function (a,b) {return a.x - b.x;})
  18510. }
  18511. }
  18512. else {
  18513. this.itemsData = [];
  18514. }
  18515. };
  18516. /**
  18517. * this is used for plotting barcharts, this way, we only have to calculate it once.
  18518. * @param pos
  18519. */
  18520. GraphGroup.prototype.setZeroPosition = function(pos) {
  18521. this.zeroPosition = pos;
  18522. };
  18523. /**
  18524. * set the options of the graph group over the default options.
  18525. * @param options
  18526. */
  18527. GraphGroup.prototype.setOptions = function(options) {
  18528. if (options !== undefined) {
  18529. var fields = ['sampling','style','sort','yAxisOrientation','barChart'];
  18530. util.selectiveDeepExtend(fields, this.options, options);
  18531. util.mergeOptions(this.options, options,'catmullRom');
  18532. util.mergeOptions(this.options, options,'drawPoints');
  18533. util.mergeOptions(this.options, options,'shaded');
  18534. if (options.catmullRom) {
  18535. if (typeof options.catmullRom == 'object') {
  18536. if (options.catmullRom.parametrization) {
  18537. if (options.catmullRom.parametrization == 'uniform') {
  18538. this.options.catmullRom.alpha = 0;
  18539. }
  18540. else if (options.catmullRom.parametrization == 'chordal') {
  18541. this.options.catmullRom.alpha = 1.0;
  18542. }
  18543. else {
  18544. this.options.catmullRom.parametrization = 'centripetal';
  18545. this.options.catmullRom.alpha = 0.5;
  18546. }
  18547. }
  18548. }
  18549. }
  18550. }
  18551. if (this.options.style == 'line') {
  18552. this.type = new Line(this.id, this.options);
  18553. }
  18554. else if (this.options.style == 'bar') {
  18555. this.type = new Bar(this.id, this.options);
  18556. }
  18557. else if (this.options.style == 'points') {
  18558. this.type = new Points(this.id, this.options);
  18559. }
  18560. };
  18561. /**
  18562. * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
  18563. * @param group
  18564. */
  18565. GraphGroup.prototype.update = function(group) {
  18566. this.group = group;
  18567. this.content = group.content || 'graph';
  18568. this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10;
  18569. this.visible = group.visible === undefined ? true : group.visible;
  18570. this.style = group.style;
  18571. this.setOptions(group.options);
  18572. };
  18573. /**
  18574. * draw the icon for the legend.
  18575. *
  18576. * @param x
  18577. * @param y
  18578. * @param JSONcontainer
  18579. * @param SVGcontainer
  18580. * @param iconWidth
  18581. * @param iconHeight
  18582. */
  18583. GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) {
  18584. var fillHeight = iconHeight * 0.5;
  18585. var path, fillPath;
  18586. var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer);
  18587. outline.setAttributeNS(null, "x", x);
  18588. outline.setAttributeNS(null, "y", y - fillHeight);
  18589. outline.setAttributeNS(null, "width", iconWidth);
  18590. outline.setAttributeNS(null, "height", 2*fillHeight);
  18591. outline.setAttributeNS(null, "class", "outline");
  18592. if (this.options.style == 'line') {
  18593. path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  18594. path.setAttributeNS(null, "class", this.className);
  18595. if(this.style !== undefined) {
  18596. path.setAttributeNS(null, "style", this.style);
  18597. }
  18598. path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+"");
  18599. if (this.options.shaded.enabled == true) {
  18600. fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  18601. if (this.options.shaded.orientation == 'top') {
  18602. fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) +
  18603. "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight));
  18604. }
  18605. else {
  18606. fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " +
  18607. "L"+x+"," + (y + fillHeight) + " " +
  18608. "L"+ (x + iconWidth) + "," + (y + fillHeight) +
  18609. "L"+ (x + iconWidth) + ","+y);
  18610. }
  18611. fillPath.setAttributeNS(null, "class", this.className + " iconFill");
  18612. }
  18613. if (this.options.drawPoints.enabled == true) {
  18614. DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer);
  18615. }
  18616. }
  18617. else {
  18618. var barWidth = Math.round(0.3 * iconWidth);
  18619. var bar1Height = Math.round(0.4 * iconHeight);
  18620. var bar2Height = Math.round(0.75 * iconHeight);
  18621. var offset = Math.round((iconWidth - (2 * barWidth))/3);
  18622. DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  18623. DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  18624. }
  18625. };
  18626. /**
  18627. * return the legend entree for this group.
  18628. *
  18629. * @param iconWidth
  18630. * @param iconHeight
  18631. * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
  18632. */
  18633. GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) {
  18634. var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  18635. this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight);
  18636. return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation};
  18637. }
  18638. GraphGroup.prototype.getYRange = function(groupData) {
  18639. return this.type.getYRange(groupData);
  18640. }
  18641. GraphGroup.prototype.draw = function(dataset, group, framework) {
  18642. this.type.draw(dataset, group, framework);
  18643. }
  18644. module.exports = GraphGroup;
  18645. /***/ },
  18646. /* 46 */
  18647. /***/ function(module, exports, __webpack_require__) {
  18648. /**
  18649. * Created by Alex on 11/11/2014.
  18650. */
  18651. var DOMutil = __webpack_require__(6);
  18652. var Points = __webpack_require__(47);
  18653. function Line(groupId, options) {
  18654. this.groupId = groupId;
  18655. this.options = options;
  18656. }
  18657. Line.prototype.getYRange = function(groupData) {
  18658. var yMin = groupData[0].y;
  18659. var yMax = groupData[0].y;
  18660. for (var j = 0; j < groupData.length; j++) {
  18661. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  18662. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  18663. }
  18664. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  18665. };
  18666. /**
  18667. * draw a line graph
  18668. *
  18669. * @param dataset
  18670. * @param group
  18671. */
  18672. Line.prototype.draw = function (dataset, group, framework) {
  18673. if (dataset != null) {
  18674. if (dataset.length > 0) {
  18675. var path, d;
  18676. var svgHeight = Number(framework.svg.style.height.replace('px',''));
  18677. path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  18678. path.setAttributeNS(null, "class", group.className);
  18679. if(group.style !== undefined) {
  18680. path.setAttributeNS(null, "style", group.style);
  18681. }
  18682. // construct path from dataset
  18683. if (group.options.catmullRom.enabled == true) {
  18684. d = Line._catmullRom(dataset, group);
  18685. }
  18686. else {
  18687. d = Line._linear(dataset);
  18688. }
  18689. // append with points for fill and finalize the path
  18690. if (group.options.shaded.enabled == true) {
  18691. var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  18692. var dFill;
  18693. if (group.options.shaded.orientation == 'top') {
  18694. dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0;
  18695. }
  18696. else {
  18697. dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight;
  18698. }
  18699. fillPath.setAttributeNS(null, "class", group.className + " fill");
  18700. if(group.options.shaded.style !== undefined) {
  18701. fillPath.setAttributeNS(null, "style", group.options.shaded.style);
  18702. }
  18703. fillPath.setAttributeNS(null, "d", dFill);
  18704. }
  18705. // copy properties to path for drawing.
  18706. path.setAttributeNS(null, 'd', 'M' + d);
  18707. // draw points
  18708. if (group.options.drawPoints.enabled == true) {
  18709. Points.draw(dataset, group, framework);
  18710. }
  18711. }
  18712. }
  18713. };
  18714. /**
  18715. * This uses an uniform parametrization of the CatmullRom algorithm:
  18716. * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
  18717. * @param data
  18718. * @returns {string}
  18719. * @private
  18720. */
  18721. Line._catmullRomUniform = function(data) {
  18722. // catmull rom
  18723. var p0, p1, p2, p3, bp1, bp2;
  18724. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  18725. var normalization = 1/6;
  18726. var length = data.length;
  18727. for (var i = 0; i < length - 1; i++) {
  18728. p0 = (i == 0) ? data[0] : data[i-1];
  18729. p1 = data[i];
  18730. p2 = data[i+1];
  18731. p3 = (i + 2 < length) ? data[i+2] : p2;
  18732. // Catmull-Rom to Cubic Bezier conversion matrix
  18733. // 0 1 0 0
  18734. // -1/6 1 1/6 0
  18735. // 0 1/6 1 -1/6
  18736. // 0 0 1 0
  18737. // bp0 = { x: p1.x, y: p1.y };
  18738. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  18739. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  18740. // bp0 = { x: p2.x, y: p2.y };
  18741. d += 'C' +
  18742. bp1.x + ',' +
  18743. bp1.y + ' ' +
  18744. bp2.x + ',' +
  18745. bp2.y + ' ' +
  18746. p2.x + ',' +
  18747. p2.y + ' ';
  18748. }
  18749. return d;
  18750. };
  18751. /**
  18752. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  18753. * By default, the centripetal parameterization is used because this gives the nicest results.
  18754. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  18755. *
  18756. * One optimization can be used to reuse distances since this is a sliding window approach.
  18757. * @param data
  18758. * @param group
  18759. * @returns {string}
  18760. * @private
  18761. */
  18762. Line._catmullRom = function(data, group) {
  18763. var alpha = group.options.catmullRom.alpha;
  18764. if (alpha == 0 || alpha === undefined) {
  18765. return this._catmullRomUniform(data);
  18766. }
  18767. else {
  18768. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  18769. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  18770. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  18771. var length = data.length;
  18772. for (var i = 0; i < length - 1; i++) {
  18773. p0 = (i == 0) ? data[0] : data[i-1];
  18774. p1 = data[i];
  18775. p2 = data[i+1];
  18776. p3 = (i + 2 < length) ? data[i+2] : p2;
  18777. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  18778. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  18779. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  18780. // Catmull-Rom to Cubic Bezier conversion matrix
  18781. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  18782. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  18783. // [ 0 1 0 0 ]
  18784. // [ -d2^2a /N A/N d1^2a /N 0 ]
  18785. // [ 0 d3^2a /M B/M -d2^2a /M ]
  18786. // [ 0 0 1 0 ]
  18787. d3powA = Math.pow(d3, alpha);
  18788. d3pow2A = Math.pow(d3,2*alpha);
  18789. d2powA = Math.pow(d2, alpha);
  18790. d2pow2A = Math.pow(d2,2*alpha);
  18791. d1powA = Math.pow(d1, alpha);
  18792. d1pow2A = Math.pow(d1,2*alpha);
  18793. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  18794. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  18795. N = 3*d1powA * (d1powA + d2powA);
  18796. if (N > 0) {N = 1 / N;}
  18797. M = 3*d3powA * (d3powA + d2powA);
  18798. if (M > 0) {M = 1 / M;}
  18799. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  18800. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  18801. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  18802. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  18803. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  18804. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  18805. d += 'C' +
  18806. bp1.x + ',' +
  18807. bp1.y + ' ' +
  18808. bp2.x + ',' +
  18809. bp2.y + ' ' +
  18810. p2.x + ',' +
  18811. p2.y + ' ';
  18812. }
  18813. return d;
  18814. }
  18815. };
  18816. /**
  18817. * this generates the SVG path for a linear drawing between datapoints.
  18818. * @param data
  18819. * @returns {string}
  18820. * @private
  18821. */
  18822. Line._linear = function(data) {
  18823. // linear
  18824. var d = '';
  18825. for (var i = 0; i < data.length; i++) {
  18826. if (i == 0) {
  18827. d += data[i].x + ',' + data[i].y;
  18828. }
  18829. else {
  18830. d += ' ' + data[i].x + ',' + data[i].y;
  18831. }
  18832. }
  18833. return d;
  18834. };
  18835. module.exports = Line;
  18836. /***/ },
  18837. /* 47 */
  18838. /***/ function(module, exports, __webpack_require__) {
  18839. /**
  18840. * Created by Alex on 11/11/2014.
  18841. */
  18842. var DOMutil = __webpack_require__(6);
  18843. function Points(groupId, options) {
  18844. this.groupId = groupId;
  18845. this.options = options;
  18846. }
  18847. Points.prototype.getYRange = function(groupData) {
  18848. var yMin = groupData[0].y;
  18849. var yMax = groupData[0].y;
  18850. for (var j = 0; j < groupData.length; j++) {
  18851. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  18852. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  18853. }
  18854. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  18855. };
  18856. Points.prototype.draw = function(dataset, group, framework, offset) {
  18857. Points.draw(dataset, group, framework, offset);
  18858. }
  18859. /**
  18860. * draw the data points
  18861. *
  18862. * @param {Array} dataset
  18863. * @param {Object} JSONcontainer
  18864. * @param {Object} svg | SVG DOM element
  18865. * @param {GraphGroup} group
  18866. * @param {Number} [offset]
  18867. */
  18868. Points.draw = function (dataset, group, framework, offset) {
  18869. if (offset === undefined) {offset = 0;}
  18870. for (var i = 0; i < dataset.length; i++) {
  18871. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg);
  18872. }
  18873. };
  18874. module.exports = Points;
  18875. /***/ },
  18876. /* 48 */
  18877. /***/ function(module, exports, __webpack_require__) {
  18878. /**
  18879. * Created by Alex on 11/11/2014.
  18880. */
  18881. var DOMutil = __webpack_require__(6);
  18882. var Points = __webpack_require__(47);
  18883. function Bargraph(groupId, options) {
  18884. this.groupId = groupId;
  18885. this.options = options;
  18886. }
  18887. Bargraph.prototype.getYRange = function(groupData) {
  18888. if (this.options.barChart.handleOverlap != 'stack') {
  18889. var yMin = groupData[0].y;
  18890. var yMax = groupData[0].y;
  18891. for (var j = 0; j < groupData.length; j++) {
  18892. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  18893. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  18894. }
  18895. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  18896. }
  18897. else {
  18898. var barCombinedData = [];
  18899. for (var j = 0; j < groupData.length; j++) {
  18900. barCombinedData.push({
  18901. x: groupData[j].x,
  18902. y: groupData[j].y,
  18903. groupId: this.groupId
  18904. });
  18905. }
  18906. return barCombinedData;
  18907. }
  18908. };
  18909. /**
  18910. * draw a bar graph
  18911. *
  18912. * @param groupIds
  18913. * @param processedGroupData
  18914. */
  18915. Bargraph.draw = function (groupIds, processedGroupData, framework) {
  18916. var combinedData = [];
  18917. var intersections = {};
  18918. var coreDistance;
  18919. var key, drawData;
  18920. var group;
  18921. var i,j;
  18922. var barPoints = 0;
  18923. // combine all barchart data
  18924. for (i = 0; i < groupIds.length; i++) {
  18925. group = framework.groups[groupIds[i]];
  18926. if (group.options.style == 'bar') {
  18927. if (group.visible == true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] == true)) {
  18928. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  18929. combinedData.push({
  18930. x: processedGroupData[groupIds[i]][j].x,
  18931. y: processedGroupData[groupIds[i]][j].y,
  18932. groupId: groupIds[i]
  18933. });
  18934. barPoints += 1;
  18935. }
  18936. }
  18937. }
  18938. }
  18939. if (barPoints == 0) {return;}
  18940. // sort by time and by group
  18941. combinedData.sort(function (a, b) {
  18942. if (a.x == b.x) {
  18943. return a.groupId - b.groupId;
  18944. } else {
  18945. return a.x - b.x;
  18946. }
  18947. });
  18948. // get intersections
  18949. Bargraph._getDataIntersections(intersections, combinedData);
  18950. // plot barchart
  18951. for (i = 0; i < combinedData.length; i++) {
  18952. group = framework.groups[combinedData[i].groupId];
  18953. var minWidth = 0.1 * group.options.barChart.width;
  18954. key = combinedData[i].x;
  18955. var heightOffset = 0;
  18956. if (intersections[key] === undefined) {
  18957. if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);}
  18958. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));}
  18959. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  18960. }
  18961. else {
  18962. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  18963. var prevKey = i - (intersections[key].resolved + 1);
  18964. if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);}
  18965. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));}
  18966. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  18967. intersections[key].resolved += 1;
  18968. if (group.options.barChart.handleOverlap == 'stack') {
  18969. heightOffset = intersections[key].accumulated;
  18970. intersections[key].accumulated += group.zeroPosition - combinedData[i].y;
  18971. }
  18972. else if (group.options.barChart.handleOverlap == 'sideBySide') {
  18973. drawData.width = drawData.width / intersections[key].amount;
  18974. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  18975. if (group.options.barChart.align == 'left') {drawData.offset -= 0.5*drawData.width;}
  18976. else if (group.options.barChart.align == 'right') {drawData.offset += 0.5*drawData.width;}
  18977. }
  18978. }
  18979. 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);
  18980. // draw points
  18981. if (group.options.drawPoints.enabled == true) {
  18982. DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg);
  18983. }
  18984. }
  18985. };
  18986. /**
  18987. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  18988. * @param intersections
  18989. * @param combinedData
  18990. * @private
  18991. */
  18992. Bargraph._getDataIntersections = function (intersections, combinedData) {
  18993. // get intersections
  18994. var coreDistance;
  18995. for (var i = 0; i < combinedData.length; i++) {
  18996. if (i + 1 < combinedData.length) {
  18997. coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x);
  18998. }
  18999. if (i > 0) {
  19000. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x));
  19001. }
  19002. if (coreDistance == 0) {
  19003. if (intersections[combinedData[i].x] === undefined) {
  19004. intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0};
  19005. }
  19006. intersections[combinedData[i].x].amount += 1;
  19007. }
  19008. }
  19009. };
  19010. /**
  19011. * Get the width and offset for bargraphs based on the coredistance between datapoints
  19012. *
  19013. * @param coreDistance
  19014. * @param group
  19015. * @param minWidth
  19016. * @returns {{width: Number, offset: Number}}
  19017. * @private
  19018. */
  19019. Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) {
  19020. var width, offset;
  19021. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  19022. width = coreDistance < minWidth ? minWidth : coreDistance;
  19023. offset = 0; // recalculate offset with the new width;
  19024. if (group.options.barChart.align == 'left') {
  19025. offset -= 0.5 * coreDistance;
  19026. }
  19027. else if (group.options.barChart.align == 'right') {
  19028. offset += 0.5 * coreDistance;
  19029. }
  19030. }
  19031. else {
  19032. // default settings
  19033. width = group.options.barChart.width;
  19034. offset = 0;
  19035. if (group.options.barChart.align == 'left') {
  19036. offset -= 0.5 * group.options.barChart.width;
  19037. }
  19038. else if (group.options.barChart.align == 'right') {
  19039. offset += 0.5 * group.options.barChart.width;
  19040. }
  19041. }
  19042. return {width: width, offset: offset};
  19043. };
  19044. Bargraph.getStackedBarYRange = function(barCombinedData, groupRanges, groupIds, groupLabel, orientation) {
  19045. if (barCombinedData.length > 0) {
  19046. // sort by time and by group
  19047. barCombinedData.sort(function (a, b) {
  19048. if (a.x == b.x) {
  19049. return a.groupId - b.groupId;
  19050. } else {
  19051. return a.x - b.x;
  19052. }
  19053. });
  19054. var intersections = {};
  19055. Bargraph._getDataIntersections(intersections, barCombinedData);
  19056. groupRanges[groupLabel] = Bargraph._getStackedBarYRange(intersections, barCombinedData);
  19057. groupRanges[groupLabel].yAxisOrientation = orientation;
  19058. groupIds.push(groupLabel);
  19059. }
  19060. }
  19061. Bargraph._getStackedBarYRange = function (intersections, combinedData) {
  19062. var key;
  19063. var yMin = combinedData[0].y;
  19064. var yMax = combinedData[0].y;
  19065. for (var i = 0; i < combinedData.length; i++) {
  19066. key = combinedData[i].x;
  19067. if (intersections[key] === undefined) {
  19068. yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin;
  19069. yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax;
  19070. }
  19071. else {
  19072. intersections[key].accumulated += combinedData[i].y;
  19073. }
  19074. }
  19075. for (var xpos in intersections) {
  19076. if (intersections.hasOwnProperty(xpos)) {
  19077. yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin;
  19078. yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax;
  19079. }
  19080. }
  19081. return {min: yMin, max: yMax};
  19082. };
  19083. module.exports = Bargraph;
  19084. /***/ },
  19085. /* 49 */
  19086. /***/ function(module, exports, __webpack_require__) {
  19087. var util = __webpack_require__(1);
  19088. var DOMutil = __webpack_require__(6);
  19089. var Component = __webpack_require__(23);
  19090. /**
  19091. * Legend for Graph2d
  19092. */
  19093. function Legend(body, options, side, linegraphOptions) {
  19094. this.body = body;
  19095. this.defaultOptions = {
  19096. enabled: true,
  19097. icons: true,
  19098. iconSize: 20,
  19099. iconSpacing: 6,
  19100. left: {
  19101. visible: true,
  19102. position: 'top-left' // top/bottom - left,center,right
  19103. },
  19104. right: {
  19105. visible: true,
  19106. position: 'top-left' // top/bottom - left,center,right
  19107. }
  19108. }
  19109. this.side = side;
  19110. this.options = util.extend({},this.defaultOptions);
  19111. this.linegraphOptions = linegraphOptions;
  19112. this.svgElements = {};
  19113. this.dom = {};
  19114. this.groups = {};
  19115. this.amountOfGroups = 0;
  19116. this._create();
  19117. this.setOptions(options);
  19118. }
  19119. Legend.prototype = new Component();
  19120. Legend.prototype.clear = function() {
  19121. this.groups = {};
  19122. this.amountOfGroups = 0;
  19123. }
  19124. Legend.prototype.addGroup = function(label, graphOptions) {
  19125. if (!this.groups.hasOwnProperty(label)) {
  19126. this.groups[label] = graphOptions;
  19127. }
  19128. this.amountOfGroups += 1;
  19129. };
  19130. Legend.prototype.updateGroup = function(label, graphOptions) {
  19131. this.groups[label] = graphOptions;
  19132. };
  19133. Legend.prototype.removeGroup = function(label) {
  19134. if (this.groups.hasOwnProperty(label)) {
  19135. delete this.groups[label];
  19136. this.amountOfGroups -= 1;
  19137. }
  19138. };
  19139. Legend.prototype._create = function() {
  19140. this.dom.frame = document.createElement('div');
  19141. this.dom.frame.className = 'legend';
  19142. this.dom.frame.style.position = "absolute";
  19143. this.dom.frame.style.top = "10px";
  19144. this.dom.frame.style.display = "block";
  19145. this.dom.textArea = document.createElement('div');
  19146. this.dom.textArea.className = 'legendText';
  19147. this.dom.textArea.style.position = "relative";
  19148. this.dom.textArea.style.top = "0px";
  19149. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  19150. this.svg.style.position = 'absolute';
  19151. this.svg.style.top = 0 +'px';
  19152. this.svg.style.width = this.options.iconSize + 5 + 'px';
  19153. this.svg.style.height = '100%';
  19154. this.dom.frame.appendChild(this.svg);
  19155. this.dom.frame.appendChild(this.dom.textArea);
  19156. };
  19157. /**
  19158. * Hide the component from the DOM
  19159. */
  19160. Legend.prototype.hide = function() {
  19161. // remove the frame containing the items
  19162. if (this.dom.frame.parentNode) {
  19163. this.dom.frame.parentNode.removeChild(this.dom.frame);
  19164. }
  19165. };
  19166. /**
  19167. * Show the component in the DOM (when not already visible).
  19168. * @return {Boolean} changed
  19169. */
  19170. Legend.prototype.show = function() {
  19171. // show frame containing the items
  19172. if (!this.dom.frame.parentNode) {
  19173. this.body.dom.center.appendChild(this.dom.frame);
  19174. }
  19175. };
  19176. Legend.prototype.setOptions = function(options) {
  19177. var fields = ['enabled','orientation','icons','left','right'];
  19178. util.selectiveDeepExtend(fields, this.options, options);
  19179. };
  19180. Legend.prototype.redraw = function() {
  19181. var activeGroups = 0;
  19182. for (var groupId in this.groups) {
  19183. if (this.groups.hasOwnProperty(groupId)) {
  19184. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  19185. activeGroups++;
  19186. }
  19187. }
  19188. }
  19189. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  19190. this.hide();
  19191. }
  19192. else {
  19193. this.show();
  19194. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  19195. this.dom.frame.style.left = '4px';
  19196. this.dom.frame.style.textAlign = "left";
  19197. this.dom.textArea.style.textAlign = "left";
  19198. this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px';
  19199. this.dom.textArea.style.right = '';
  19200. this.svg.style.left = 0 +'px';
  19201. this.svg.style.right = '';
  19202. }
  19203. else {
  19204. this.dom.frame.style.right = '4px';
  19205. this.dom.frame.style.textAlign = "right";
  19206. this.dom.textArea.style.textAlign = "right";
  19207. this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px';
  19208. this.dom.textArea.style.left = '';
  19209. this.svg.style.right = 0 +'px';
  19210. this.svg.style.left = '';
  19211. }
  19212. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  19213. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  19214. this.dom.frame.style.bottom = '';
  19215. }
  19216. else {
  19217. var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height;
  19218. this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  19219. this.dom.frame.style.top = '';
  19220. }
  19221. if (this.options.icons == false) {
  19222. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  19223. this.dom.textArea.style.right = '';
  19224. this.dom.textArea.style.left = '';
  19225. this.svg.style.width = '0px';
  19226. }
  19227. else {
  19228. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'
  19229. this.drawLegendIcons();
  19230. }
  19231. var content = '';
  19232. for (var groupId in this.groups) {
  19233. if (this.groups.hasOwnProperty(groupId)) {
  19234. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  19235. content += this.groups[groupId].content + '<br />';
  19236. }
  19237. }
  19238. }
  19239. this.dom.textArea.innerHTML = content;
  19240. this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px';
  19241. }
  19242. };
  19243. Legend.prototype.drawLegendIcons = function() {
  19244. if (this.dom.frame.parentNode) {
  19245. DOMutil.prepareElements(this.svgElements);
  19246. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  19247. var iconOffset = Number(padding.replace('px',''));
  19248. var x = iconOffset;
  19249. var iconWidth = this.options.iconSize;
  19250. var iconHeight = 0.75 * this.options.iconSize;
  19251. var y = iconOffset + 0.5 * iconHeight + 3;
  19252. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  19253. for (var groupId in this.groups) {
  19254. if (this.groups.hasOwnProperty(groupId)) {
  19255. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  19256. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  19257. y += iconHeight + this.options.iconSpacing;
  19258. }
  19259. }
  19260. }
  19261. DOMutil.cleanupElements(this.svgElements);
  19262. }
  19263. };
  19264. module.exports = Legend;
  19265. /***/ },
  19266. /* 50 */
  19267. /***/ function(module, exports, __webpack_require__) {
  19268. /**
  19269. * @constructor DataStep
  19270. * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
  19271. * end data point. The class itself determines the best scale (step size) based on the
  19272. * provided start Date, end Date, and minimumStep.
  19273. *
  19274. * If minimumStep is provided, the step size is chosen as close as possible
  19275. * to the minimumStep but larger than minimumStep. If minimumStep is not
  19276. * provided, the scale is set to 1 DAY.
  19277. * The minimumStep should correspond with the onscreen size of about 6 characters
  19278. *
  19279. * Alternatively, you can set a scale by hand.
  19280. * After creation, you can initialize the class by executing first(). Then you
  19281. * can iterate from the start date to the end date via next(). You can check if
  19282. * the end date is reached with the function hasNext(). After each step, you can
  19283. * retrieve the current date via getCurrent().
  19284. * The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
  19285. * days, to years.
  19286. *
  19287. * Version: 1.2
  19288. *
  19289. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  19290. * or new Date(2010, 9, 21, 23, 45, 00)
  19291. * @param {Date} [end] The end date
  19292. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  19293. */
  19294. function DataStep(start, end, minimumStep, containerHeight, customRange, alignZeros) {
  19295. // variables
  19296. this.current = 0;
  19297. this.autoScale = true;
  19298. this.stepIndex = 0;
  19299. this.step = 1;
  19300. this.scale = 1;
  19301. this.marginStart;
  19302. this.marginEnd;
  19303. this.deadSpace = 0;
  19304. this.majorSteps = [1, 2, 5, 10];
  19305. this.minorSteps = [0.25, 0.5, 1, 2];
  19306. this.alignZeros = alignZeros;
  19307. this.setRange(start, end, minimumStep, containerHeight, customRange);
  19308. }
  19309. /**
  19310. * Set a new range
  19311. * If minimumStep is provided, the step size is chosen as close as possible
  19312. * to the minimumStep but larger than minimumStep. If minimumStep is not
  19313. * provided, the scale is set to 1 DAY.
  19314. * The minimumStep should correspond with the onscreen size of about 6 characters
  19315. * @param {Number} [start] The start date and time.
  19316. * @param {Number} [end] The end date and time.
  19317. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  19318. */
  19319. DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, customRange) {
  19320. this._start = customRange.min === undefined ? start : customRange.min;
  19321. this._end = customRange.max === undefined ? end : customRange.max;
  19322. if (this._start == this._end) {
  19323. this._start -= 0.75;
  19324. this._end += 1;
  19325. }
  19326. if (this.autoScale == true) {
  19327. this.setMinimumStep(minimumStep, containerHeight);
  19328. }
  19329. this.setFirst(customRange);
  19330. };
  19331. /**
  19332. * Automatically determine the scale that bests fits the provided minimum step
  19333. * @param {Number} [minimumStep] The minimum step size in milliseconds
  19334. */
  19335. DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
  19336. // round to floor
  19337. var size = this._end - this._start;
  19338. var safeSize = size * 1.2;
  19339. var minimumStepValue = minimumStep * (safeSize / containerHeight);
  19340. var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
  19341. var minorStepIdx = -1;
  19342. var magnitudefactor = Math.pow(10,orderOfMagnitude);
  19343. var start = 0;
  19344. if (orderOfMagnitude < 0) {
  19345. start = orderOfMagnitude;
  19346. }
  19347. var solutionFound = false;
  19348. for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) {
  19349. magnitudefactor = Math.pow(10,i);
  19350. for (var j = 0; j < this.minorSteps.length; j++) {
  19351. var stepSize = magnitudefactor * this.minorSteps[j];
  19352. if (stepSize >= minimumStepValue) {
  19353. solutionFound = true;
  19354. minorStepIdx = j;
  19355. break;
  19356. }
  19357. }
  19358. if (solutionFound == true) {
  19359. break;
  19360. }
  19361. }
  19362. this.stepIndex = minorStepIdx;
  19363. this.scale = magnitudefactor;
  19364. this.step = magnitudefactor * this.minorSteps[minorStepIdx];
  19365. };
  19366. /**
  19367. * Round the current date to the first minor date value
  19368. * This must be executed once when the current date is set to start Date
  19369. */
  19370. DataStep.prototype.setFirst = function(customRange) {
  19371. if (customRange === undefined) {
  19372. customRange = {};
  19373. }
  19374. var niceStart = customRange.min === undefined ? this._start - (this.scale * 2 * this.minorSteps[this.stepIndex]) : customRange.min;
  19375. var niceEnd = customRange.max === undefined ? this._end + (this.scale * this.minorSteps[this.stepIndex]) : customRange.max;
  19376. this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max;
  19377. this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min;
  19378. // if we need to align the zero's we need to make sure that there is a zero to use.
  19379. if (this.alignZeros == true && (this.marginEnd - this.marginStart) % this.step != 0) {
  19380. this.marginEnd += this.marginEnd % this.step;
  19381. }
  19382. this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart;
  19383. this.marginRange = this.marginEnd - this.marginStart;
  19384. this.current = this.marginEnd;
  19385. };
  19386. DataStep.prototype.roundToMinor = function(value) {
  19387. var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
  19388. if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
  19389. return rounded + (this.scale * this.minorSteps[this.stepIndex]);
  19390. }
  19391. else {
  19392. return rounded;
  19393. }
  19394. }
  19395. /**
  19396. * Check if the there is a next step
  19397. * @return {boolean} true if the current date has not passed the end date
  19398. */
  19399. DataStep.prototype.hasNext = function () {
  19400. return (this.current >= this.marginStart);
  19401. };
  19402. /**
  19403. * Do the next step
  19404. */
  19405. DataStep.prototype.next = function() {
  19406. var prev = this.current;
  19407. this.current -= this.step;
  19408. // safety mechanism: if current time is still unchanged, move to the end
  19409. if (this.current == prev) {
  19410. this.current = this._end;
  19411. }
  19412. };
  19413. /**
  19414. * Do the next step
  19415. */
  19416. DataStep.prototype.previous = function() {
  19417. this.current += this.step;
  19418. this.marginEnd += this.step;
  19419. this.marginRange = this.marginEnd - this.marginStart;
  19420. };
  19421. /**
  19422. * Get the current datetime
  19423. * @return {String} current The current date
  19424. */
  19425. DataStep.prototype.getCurrent = function(decimals) {
  19426. // prevent round-off errors when close to zero
  19427. var current = (Math.abs(this.current) < this.step / 2) ? 0 : this.current;
  19428. var toPrecision = '' + Number(current).toPrecision(5);
  19429. // If decimals is specified, then limit or extend the string as required
  19430. if(decimals !== undefined && !isNaN(Number(decimals))) {
  19431. // If string includes exponent, then we need to add it to the end
  19432. var exp = "";
  19433. var index = toPrecision.indexOf("e");
  19434. if(index != -1) {
  19435. // Get the exponent
  19436. exp = toPrecision.slice(index);
  19437. // Remove the exponent in case we need to zero-extend
  19438. toPrecision = toPrecision.slice(0, index);
  19439. }
  19440. index = Math.max(toPrecision.indexOf(","), toPrecision.indexOf("."));
  19441. if(index === -1) {
  19442. // No decimal found - if we want decimals, then we need to add it
  19443. if(decimals !== 0) {
  19444. toPrecision += '.';
  19445. }
  19446. // Calculate how long the string should be
  19447. index = toPrecision.length + decimals;
  19448. }
  19449. else if(decimals !== 0) {
  19450. // Calculate how long the string should be - accounting for the decimal place
  19451. index += decimals + 1;
  19452. }
  19453. if(index > toPrecision.length) {
  19454. // We need to add zeros!
  19455. for(var cnt = index - toPrecision.length; cnt > 0; cnt--) {
  19456. toPrecision += '0';
  19457. }
  19458. }
  19459. else {
  19460. // we need to remove characters
  19461. toPrecision = toPrecision.slice(0, index);
  19462. }
  19463. // Add the exponent if there is one
  19464. toPrecision += exp;
  19465. }
  19466. else {
  19467. if (toPrecision.indexOf(",") != -1 || toPrecision.indexOf(".") != -1) {
  19468. // If no decimal is specified, and there are decimal places, remove trailing zeros
  19469. for (var i = toPrecision.length - 1; i > 0; i--) {
  19470. if (toPrecision[i] == "0") {
  19471. toPrecision = toPrecision.slice(0, i);
  19472. }
  19473. else if (toPrecision[i] == "." || toPrecision[i] == ",") {
  19474. toPrecision = toPrecision.slice(0, i);
  19475. break;
  19476. }
  19477. else {
  19478. break;
  19479. }
  19480. }
  19481. }
  19482. }
  19483. return toPrecision;
  19484. };
  19485. /**
  19486. * Snap a date to a rounded value.
  19487. * The snap intervals are dependent on the current scale and step.
  19488. * @param {Date} date the date to be snapped.
  19489. * @return {Date} snappedDate
  19490. */
  19491. DataStep.prototype.snap = function(date) {
  19492. };
  19493. /**
  19494. * Check if the current value is a major value (for example when the step
  19495. * is DAY, a major value is each first day of the MONTH)
  19496. * @return {boolean} true if current date is major, else false.
  19497. */
  19498. DataStep.prototype.isMajor = function() {
  19499. return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
  19500. };
  19501. module.exports = DataStep;
  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__(52);
  19513. var gephiParser = __webpack_require__(53);
  19514. var Groups = __webpack_require__(54);
  19515. var Images = __webpack_require__(55);
  19516. var Node = __webpack_require__(56);
  19517. var Edge = __webpack_require__(57);
  19518. var Popup = __webpack_require__(58);
  19519. var MixinLoader = __webpack_require__(59);
  19520. var Activator = __webpack_require__(35);
  19521. var locales = __webpack_require__(70);
  19522. // Load custom shapes into CanvasRenderingContext2D
  19523. __webpack_require__(71);
  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. locale: 'en',
  19691. locales: locales,
  19692. tooltip: {
  19693. delay: 300,
  19694. fontColor: 'black',
  19695. fontSize: 14, // px
  19696. fontFace: 'verdana',
  19697. color: {
  19698. border: '#666',
  19699. background: '#FFFFC6'
  19700. }
  19701. },
  19702. dragNetwork: true,
  19703. dragNodes: true,
  19704. zoomable: true,
  19705. hover: false,
  19706. hideEdgesOnDrag: false,
  19707. hideNodesOnDrag: false,
  19708. width : '100%',
  19709. height : '100%',
  19710. selectable: true
  19711. };
  19712. this.constants = util.extend({}, this.defaultOptions);
  19713. this.pixelRatio = 1;
  19714. this.hoverObj = {nodes:{},edges:{}};
  19715. this.controlNodesActive = false;
  19716. this.navigationHammers = {existing:[], _new: []};
  19717. // animation properties
  19718. this.animationSpeed = 1/this.renderRefreshRate;
  19719. this.animationEasingFunction = "easeInOutQuint";
  19720. this.easingTime = 0;
  19721. this.sourceScale = 0;
  19722. this.targetScale = 0;
  19723. this.sourceTranslation = 0;
  19724. this.targetTranslation = 0;
  19725. this.lockedOnNodeId = null;
  19726. this.lockedOnNodeOffset = null;
  19727. this.touchTime = 0;
  19728. // Node variables
  19729. var network = this;
  19730. this.groups = new Groups(); // object with groups
  19731. this.images = new Images(); // object with images
  19732. this.images.setOnloadCallback(function () {
  19733. network._redraw();
  19734. });
  19735. // keyboard navigation variables
  19736. this.xIncrement = 0;
  19737. this.yIncrement = 0;
  19738. this.zoomIncrement = 0;
  19739. // loading all the mixins:
  19740. // load the force calculation functions, grouped under the physics system.
  19741. this._loadPhysicsSystem();
  19742. // create a frame and canvas
  19743. this._create();
  19744. // load the sector system. (mandatory, fully integrated with Network)
  19745. this._loadSectorSystem();
  19746. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  19747. this._loadClusterSystem();
  19748. // load the selection system. (mandatory, required by Network)
  19749. this._loadSelectionSystem();
  19750. // load the selection system. (mandatory, required by Network)
  19751. this._loadHierarchySystem();
  19752. // apply options
  19753. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  19754. this._setScale(1);
  19755. this.setOptions(options);
  19756. // other vars
  19757. this.freezeSimulation = false;// freeze the simulation
  19758. this.cachedFunctions = {};
  19759. this.startedStabilization = false;
  19760. this.stabilized = false;
  19761. this.stabilizationIterations = null;
  19762. this.draggingNodes = false;
  19763. // containers for nodes and edges
  19764. this.calculationNodes = {};
  19765. this.calculationNodeIndices = [];
  19766. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  19767. this.nodes = {}; // object with Node objects
  19768. this.edges = {}; // object with Edge objects
  19769. // position and scale variables and objects
  19770. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  19771. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  19772. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  19773. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  19774. this.scale = 1; // defining the global scale variable in the constructor
  19775. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  19776. // datasets or dataviews
  19777. this.nodesData = null; // A DataSet or DataView
  19778. this.edgesData = null; // A DataSet or DataView
  19779. // create event listeners used to subscribe on the DataSets of the nodes and edges
  19780. this.nodesListeners = {
  19781. 'add': function (event, params) {
  19782. network._addNodes(params.items);
  19783. network.start();
  19784. },
  19785. 'update': function (event, params) {
  19786. network._updateNodes(params.items, params.data);
  19787. network.start();
  19788. },
  19789. 'remove': function (event, params) {
  19790. network._removeNodes(params.items);
  19791. network.start();
  19792. }
  19793. };
  19794. this.edgesListeners = {
  19795. 'add': function (event, params) {
  19796. network._addEdges(params.items);
  19797. network.start();
  19798. },
  19799. 'update': function (event, params) {
  19800. network._updateEdges(params.items);
  19801. network.start();
  19802. },
  19803. 'remove': function (event, params) {
  19804. network._removeEdges(params.items);
  19805. network.start();
  19806. }
  19807. };
  19808. // properties for the animation
  19809. this.moving = true;
  19810. this.timer = undefined; // Scheduling function. Is definded in this.start();
  19811. // load data (the disable start variable will be the same as the enabled clustering)
  19812. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  19813. // hierarchical layout
  19814. this.initializing = false;
  19815. if (this.constants.hierarchicalLayout.enabled == true) {
  19816. this._setupHierarchicalLayout();
  19817. }
  19818. else {
  19819. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  19820. if (this.constants.stabilize == false) {
  19821. this.zoomExtent(undefined, true,this.constants.clustering.enabled);
  19822. }
  19823. }
  19824. // if clustering is disabled, the simulation will have started in the setData function
  19825. if (this.constants.clustering.enabled) {
  19826. this.startWithClustering();
  19827. }
  19828. }
  19829. // Extend Network with an Emitter mixin
  19830. Emitter(Network.prototype);
  19831. /**
  19832. * Get the script path where the vis.js library is located
  19833. *
  19834. * @returns {string | null} path Path or null when not found. Path does not
  19835. * end with a slash.
  19836. * @private
  19837. */
  19838. Network.prototype._getScriptPath = function() {
  19839. var scripts = document.getElementsByTagName( 'script' );
  19840. // find script named vis.js or vis.min.js
  19841. for (var i = 0; i < scripts.length; i++) {
  19842. var src = scripts[i].src;
  19843. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  19844. if (match) {
  19845. // return path without the script name
  19846. return src.substring(0, src.length - match[0].length);
  19847. }
  19848. }
  19849. return null;
  19850. };
  19851. /**
  19852. * Find the center position of the network
  19853. * @private
  19854. */
  19855. Network.prototype._getRange = function() {
  19856. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  19857. for (var nodeId in this.nodes) {
  19858. if (this.nodes.hasOwnProperty(nodeId)) {
  19859. node = this.nodes[nodeId];
  19860. if (minX > (node.x)) {minX = node.x;}
  19861. if (maxX < (node.x)) {maxX = node.x;}
  19862. if (minY > (node.y)) {minY = node.y;}
  19863. if (maxY < (node.y)) {maxY = node.y;}
  19864. }
  19865. }
  19866. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  19867. minY = 0, maxY = 0, minX = 0, maxX = 0;
  19868. }
  19869. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  19870. };
  19871. /**
  19872. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  19873. * @returns {{x: number, y: number}}
  19874. * @private
  19875. */
  19876. Network.prototype._findCenter = function(range) {
  19877. return {x: (0.5 * (range.maxX + range.minX)),
  19878. y: (0.5 * (range.maxY + range.minY))};
  19879. };
  19880. /**
  19881. * This function zooms out to fit all data on screen based on amount of nodes
  19882. *
  19883. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  19884. * @param {Boolean} [disableStart] | If true, start is not called.
  19885. */
  19886. Network.prototype.zoomExtent = function(animationOptions, initialZoom, disableStart) {
  19887. if (initialZoom === undefined) {
  19888. initialZoom = false;
  19889. }
  19890. if (disableStart === undefined) {
  19891. disableStart = false;
  19892. }
  19893. if (animationOptions === undefined) {
  19894. animationOptions = false;
  19895. }
  19896. var range = this._getRange();
  19897. var zoomLevel;
  19898. if (initialZoom == true) {
  19899. var numberOfNodes = this.nodeIndices.length;
  19900. if (this.constants.smoothCurves == true) {
  19901. if (this.constants.clustering.enabled == true &&
  19902. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  19903. 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.
  19904. }
  19905. else {
  19906. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  19907. }
  19908. }
  19909. else {
  19910. if (this.constants.clustering.enabled == true &&
  19911. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  19912. 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.
  19913. }
  19914. else {
  19915. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  19916. }
  19917. }
  19918. // correct for larger canvasses.
  19919. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  19920. zoomLevel *= factor;
  19921. }
  19922. else {
  19923. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  19924. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  19925. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  19926. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  19927. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  19928. }
  19929. if (zoomLevel > 1.0) {
  19930. zoomLevel = 1.0;
  19931. }
  19932. var center = this._findCenter(range);
  19933. if (disableStart == false) {
  19934. var options = {position: center, scale: zoomLevel, animation: animationOptions};
  19935. this.moveTo(options);
  19936. this.moving = true;
  19937. this.start();
  19938. }
  19939. else {
  19940. center.x *= zoomLevel;
  19941. center.y *= zoomLevel;
  19942. center.x -= 0.5 * this.frame.canvas.clientWidth;
  19943. center.y -= 0.5 * this.frame.canvas.clientHeight;
  19944. this._setScale(zoomLevel);
  19945. this._setTranslation(-center.x,-center.y);
  19946. }
  19947. };
  19948. /**
  19949. * Update the this.nodeIndices with the most recent node index list
  19950. * @private
  19951. */
  19952. Network.prototype._updateNodeIndexList = function() {
  19953. this._clearNodeIndexList();
  19954. for (var idx in this.nodes) {
  19955. if (this.nodes.hasOwnProperty(idx)) {
  19956. this.nodeIndices.push(idx);
  19957. }
  19958. }
  19959. };
  19960. /**
  19961. * Set nodes and edges, and optionally options as well.
  19962. *
  19963. * @param {Object} data Object containing parameters:
  19964. * {Array | DataSet | DataView} [nodes] Array with nodes
  19965. * {Array | DataSet | DataView} [edges] Array with edges
  19966. * {String} [dot] String containing data in DOT format
  19967. * {String} [gephi] String containing data in gephi JSON format
  19968. * {Options} [options] Object with options
  19969. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  19970. */
  19971. Network.prototype.setData = function(data, disableStart) {
  19972. if (disableStart === undefined) {
  19973. disableStart = false;
  19974. }
  19975. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  19976. this.initializing = true;
  19977. if (data && data.dot && (data.nodes || data.edges)) {
  19978. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  19979. ' parameter pair "nodes" and "edges", but not both.');
  19980. }
  19981. // set options
  19982. this.setOptions(data && data.options);
  19983. // set all data
  19984. if (data && data.dot) {
  19985. // parse DOT file
  19986. if(data && data.dot) {
  19987. var dotData = dotparser.DOTToGraph(data.dot);
  19988. this.setData(dotData);
  19989. return;
  19990. }
  19991. }
  19992. else if (data && data.gephi) {
  19993. // parse DOT file
  19994. if(data && data.gephi) {
  19995. var gephiData = gephiParser.parseGephi(data.gephi);
  19996. this.setData(gephiData);
  19997. return;
  19998. }
  19999. }
  20000. else {
  20001. this._setNodes(data && data.nodes);
  20002. this._setEdges(data && data.edges);
  20003. }
  20004. this._putDataInSector();
  20005. if (disableStart == false) {
  20006. if (this.constants.hierarchicalLayout.enabled == true) {
  20007. this._resetLevels();
  20008. this._setupHierarchicalLayout();
  20009. }
  20010. else {
  20011. // find a stable position or start animating to a stable position
  20012. if (this.constants.stabilize) {
  20013. this._stabilize();
  20014. }
  20015. }
  20016. this.start();
  20017. }
  20018. this.initializing = false;
  20019. };
  20020. /**
  20021. * Set options
  20022. * @param {Object} options
  20023. */
  20024. Network.prototype.setOptions = function (options) {
  20025. if (options) {
  20026. var prop;
  20027. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation',
  20028. 'keyboard','dataManipulation','onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  20029. ];
  20030. // extend all but the values in fields
  20031. util.selectiveNotDeepExtend(fields,this.constants, options);
  20032. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  20033. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  20034. if (options.physics) {
  20035. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  20036. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  20037. if (options.physics.hierarchicalRepulsion) {
  20038. this.constants.hierarchicalLayout.enabled = true;
  20039. this.constants.physics.hierarchicalRepulsion.enabled = true;
  20040. this.constants.physics.barnesHut.enabled = false;
  20041. for (prop in options.physics.hierarchicalRepulsion) {
  20042. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  20043. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  20044. }
  20045. }
  20046. }
  20047. }
  20048. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  20049. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  20050. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  20051. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  20052. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  20053. util.mergeOptions(this.constants, options,'smoothCurves');
  20054. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  20055. util.mergeOptions(this.constants, options,'clustering');
  20056. util.mergeOptions(this.constants, options,'navigation');
  20057. util.mergeOptions(this.constants, options,'keyboard');
  20058. util.mergeOptions(this.constants, options,'dataManipulation');
  20059. if (options.dataManipulation) {
  20060. this.editMode = this.constants.dataManipulation.initiallyVisible;
  20061. }
  20062. // TODO: work out these options and document them
  20063. if (options.edges) {
  20064. if (options.edges.color !== undefined) {
  20065. if (util.isString(options.edges.color)) {
  20066. this.constants.edges.color = {};
  20067. this.constants.edges.color.color = options.edges.color;
  20068. this.constants.edges.color.highlight = options.edges.color;
  20069. this.constants.edges.color.hover = options.edges.color;
  20070. }
  20071. else {
  20072. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  20073. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  20074. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  20075. }
  20076. }
  20077. if (!options.edges.fontColor) {
  20078. if (options.edges.color !== undefined) {
  20079. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  20080. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  20081. }
  20082. }
  20083. }
  20084. if (options.nodes) {
  20085. if (options.nodes.color) {
  20086. var newColorObj = util.parseColor(options.nodes.color);
  20087. this.constants.nodes.color.background = newColorObj.background;
  20088. this.constants.nodes.color.border = newColorObj.border;
  20089. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  20090. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  20091. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  20092. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  20093. }
  20094. }
  20095. if (options.groups) {
  20096. for (var groupname in options.groups) {
  20097. if (options.groups.hasOwnProperty(groupname)) {
  20098. var group = options.groups[groupname];
  20099. this.groups.add(groupname, group);
  20100. }
  20101. }
  20102. }
  20103. if (options.tooltip) {
  20104. for (prop in options.tooltip) {
  20105. if (options.tooltip.hasOwnProperty(prop)) {
  20106. this.constants.tooltip[prop] = options.tooltip[prop];
  20107. }
  20108. }
  20109. if (options.tooltip.color) {
  20110. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  20111. }
  20112. }
  20113. if ('clickToUse' in options) {
  20114. if (options.clickToUse) {
  20115. this.activator = new Activator(this.frame);
  20116. this.activator.on('change', this._createKeyBinds.bind(this));
  20117. }
  20118. else {
  20119. if (this.activator) {
  20120. this.activator.destroy();
  20121. delete this.activator;
  20122. }
  20123. }
  20124. }
  20125. if (options.labels) {
  20126. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  20127. }
  20128. }
  20129. // (Re)loading the mixins that can be enabled or disabled in the options.
  20130. // load the force calculation functions, grouped under the physics system.
  20131. this._loadPhysicsSystem();
  20132. // load the navigation system.
  20133. this._loadNavigationControls();
  20134. // load the data manipulation system
  20135. this._loadManipulationSystem();
  20136. // configure the smooth curves
  20137. this._configureSmoothCurves();
  20138. // bind keys. If disabled, this will not do anything;
  20139. this._createKeyBinds();
  20140. this.setSize(this.constants.width, this.constants.height);
  20141. this.moving = true;
  20142. this.start();
  20143. };
  20144. /**
  20145. * Create the main frame for the Network.
  20146. * This function is executed once when a Network object is created. The frame
  20147. * contains a canvas, and this canvas contains all objects like the axis and
  20148. * nodes.
  20149. * @private
  20150. */
  20151. Network.prototype._create = function () {
  20152. // remove all elements from the container element.
  20153. while (this.containerElement.hasChildNodes()) {
  20154. this.containerElement.removeChild(this.containerElement.firstChild);
  20155. }
  20156. this.frame = document.createElement('div');
  20157. this.frame.className = 'vis network-frame';
  20158. this.frame.style.position = 'relative';
  20159. this.frame.style.overflow = 'hidden';
  20160. //////////////////////////////////////////////////////////////////
  20161. this.frame.canvas = document.createElement("canvas");
  20162. this.frame.canvas.style.position = 'relative';
  20163. this.frame.appendChild(this.frame.canvas);
  20164. if (!this.frame.canvas.getContext) {
  20165. var noCanvas = document.createElement( 'DIV' );
  20166. noCanvas.style.color = 'red';
  20167. noCanvas.style.fontWeight = 'bold' ;
  20168. noCanvas.style.padding = '10px';
  20169. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  20170. this.frame.canvas.appendChild(noCanvas);
  20171. }
  20172. else {
  20173. var ctx = this.frame.canvas.getContext("2d");
  20174. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  20175. ctx.mozBackingStorePixelRatio ||
  20176. ctx.msBackingStorePixelRatio ||
  20177. ctx.oBackingStorePixelRatio ||
  20178. ctx.backingStorePixelRatio || 1);
  20179. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  20180. }
  20181. //////////////////////////////////////////////////////////////////
  20182. var me = this;
  20183. this.drag = {};
  20184. this.pinch = {};
  20185. this.hammer = Hammer(this.frame.canvas, {
  20186. prevent_default: true
  20187. });
  20188. this.hammer.on('tap', me._onTap.bind(me) );
  20189. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  20190. this.hammer.on('hold', me._onHold.bind(me) );
  20191. this.hammer.on('pinch', me._onPinch.bind(me) );
  20192. this.hammer.on('touch', me._onTouch.bind(me) );
  20193. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  20194. this.hammer.on('drag', me._onDrag.bind(me) );
  20195. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  20196. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  20197. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  20198. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  20199. this.hammerFrame = Hammer(this.frame, {
  20200. prevent_default: true
  20201. });
  20202. this.hammerFrame.on('release', me._onRelease.bind(me) );
  20203. // add the frame to the container element
  20204. this.containerElement.appendChild(this.frame);
  20205. };
  20206. /**
  20207. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  20208. * @private
  20209. */
  20210. Network.prototype._createKeyBinds = function() {
  20211. var me = this;
  20212. if (this.keycharm !== undefined) {
  20213. this.keycharm.destroy();
  20214. }
  20215. this.keycharm = keycharm();
  20216. this.keycharm.reset();
  20217. if (this.constants.keyboard.enabled && this.isActive()) {
  20218. this.keycharm.bind("up", this._moveUp.bind(me) , "keydown");
  20219. this.keycharm.bind("up", this._yStopMoving.bind(me), "keyup");
  20220. this.keycharm.bind("down", this._moveDown.bind(me) , "keydown");
  20221. this.keycharm.bind("down", this._yStopMoving.bind(me), "keyup");
  20222. this.keycharm.bind("left", this._moveLeft.bind(me) , "keydown");
  20223. this.keycharm.bind("left", this._xStopMoving.bind(me), "keyup");
  20224. this.keycharm.bind("right",this._moveRight.bind(me), "keydown");
  20225. this.keycharm.bind("right",this._xStopMoving.bind(me), "keyup");
  20226. this.keycharm.bind("=", this._zoomIn.bind(me), "keydown");
  20227. this.keycharm.bind("=", this._stopZoom.bind(me), "keyup");
  20228. this.keycharm.bind("num+", this._zoomIn.bind(me), "keydown");
  20229. this.keycharm.bind("num+", this._stopZoom.bind(me), "keyup");
  20230. this.keycharm.bind("num-", this._zoomOut.bind(me), "keydown");
  20231. this.keycharm.bind("num-", this._stopZoom.bind(me), "keyup");
  20232. this.keycharm.bind("-", this._zoomOut.bind(me), "keydown");
  20233. this.keycharm.bind("-", this._stopZoom.bind(me), "keyup");
  20234. this.keycharm.bind("[", this._zoomIn.bind(me), "keydown");
  20235. this.keycharm.bind("[", this._stopZoom.bind(me), "keyup");
  20236. this.keycharm.bind("]", this._zoomOut.bind(me), "keydown");
  20237. this.keycharm.bind("]", this._stopZoom.bind(me), "keyup");
  20238. this.keycharm.bind("pageup",this._zoomIn.bind(me), "keydown");
  20239. this.keycharm.bind("pageup",this._stopZoom.bind(me), "keyup");
  20240. this.keycharm.bind("pagedown",this._zoomOut.bind(me),"keydown");
  20241. this.keycharm.bind("pagedown",this._stopZoom.bind(me), "keyup");
  20242. }
  20243. if (this.constants.dataManipulation.enabled == true) {
  20244. this.keycharm.bind("esc",this._createManipulatorBar.bind(me));
  20245. this.keycharm.bind("delete",this._deleteSelected.bind(me));
  20246. }
  20247. };
  20248. /**
  20249. * Get the pointer location from a touch location
  20250. * @param {{pageX: Number, pageY: Number}} touch
  20251. * @return {{x: Number, y: Number}} pointer
  20252. * @private
  20253. */
  20254. Network.prototype._getPointer = function (touch) {
  20255. return {
  20256. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  20257. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  20258. };
  20259. };
  20260. /**
  20261. * On start of a touch gesture, store the pointer
  20262. * @param event
  20263. * @private
  20264. */
  20265. Network.prototype._onTouch = function (event) {
  20266. if (new Date().valueOf() - this.touchTime > 100) {
  20267. this.drag.pointer = this._getPointer(event.gesture.center);
  20268. this.drag.pinched = false;
  20269. this.pinch.scale = this._getScale();
  20270. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  20271. this.touchTime = new Date().valueOf();
  20272. this._handleTouch(this.drag.pointer);
  20273. }
  20274. };
  20275. /**
  20276. * handle drag start event
  20277. * @private
  20278. */
  20279. Network.prototype._onDragStart = function () {
  20280. this._handleDragStart();
  20281. };
  20282. /**
  20283. * This function is called by _onDragStart.
  20284. * It is separated out because we can then overload it for the datamanipulation system.
  20285. *
  20286. * @private
  20287. */
  20288. Network.prototype._handleDragStart = function() {
  20289. var drag = this.drag;
  20290. var node = this._getNodeAt(drag.pointer);
  20291. // note: drag.pointer is set in _onTouch to get the initial touch location
  20292. drag.dragging = true;
  20293. drag.selection = [];
  20294. drag.translation = this._getTranslation();
  20295. drag.nodeId = null;
  20296. this.draggingNodes = false;
  20297. if (node != null && this.constants.dragNodes == true) {
  20298. this.draggingNodes = true;
  20299. drag.nodeId = node.id;
  20300. // select the clicked node if not yet selected
  20301. if (!node.isSelected()) {
  20302. this._selectObject(node,false);
  20303. }
  20304. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  20305. // create an array with the selected nodes and their original location and status
  20306. for (var objectId in this.selectionObj.nodes) {
  20307. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  20308. var object = this.selectionObj.nodes[objectId];
  20309. var s = {
  20310. id: object.id,
  20311. node: object,
  20312. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  20313. x: object.x,
  20314. y: object.y,
  20315. xFixed: object.xFixed,
  20316. yFixed: object.yFixed
  20317. };
  20318. object.xFixed = true;
  20319. object.yFixed = true;
  20320. drag.selection.push(s);
  20321. }
  20322. }
  20323. }
  20324. };
  20325. /**
  20326. * handle drag event
  20327. * @private
  20328. */
  20329. Network.prototype._onDrag = function (event) {
  20330. this._handleOnDrag(event)
  20331. };
  20332. /**
  20333. * This function is called by _onDrag.
  20334. * It is separated out because we can then overload it for the datamanipulation system.
  20335. *
  20336. * @private
  20337. */
  20338. Network.prototype._handleOnDrag = function(event) {
  20339. if (this.drag.pinched) {
  20340. return;
  20341. }
  20342. // remove the focus on node if it is focussed on by the focusOnNode
  20343. this.releaseNode();
  20344. var pointer = this._getPointer(event.gesture.center);
  20345. var me = this;
  20346. var drag = this.drag;
  20347. var selection = drag.selection;
  20348. if (selection && selection.length && this.constants.dragNodes == true) {
  20349. // calculate delta's and new location
  20350. var deltaX = pointer.x - drag.pointer.x;
  20351. var deltaY = pointer.y - drag.pointer.y;
  20352. // update position of all selected nodes
  20353. selection.forEach(function (s) {
  20354. var node = s.node;
  20355. if (!s.xFixed) {
  20356. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  20357. }
  20358. if (!s.yFixed) {
  20359. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  20360. }
  20361. });
  20362. // start _animationStep if not yet running
  20363. if (!this.moving) {
  20364. this.moving = true;
  20365. this.start();
  20366. }
  20367. }
  20368. else {
  20369. if (this.constants.dragNetwork == true) {
  20370. // move the network
  20371. var diffX = pointer.x - this.drag.pointer.x;
  20372. var diffY = pointer.y - this.drag.pointer.y;
  20373. this._setTranslation(
  20374. this.drag.translation.x + diffX,
  20375. this.drag.translation.y + diffY
  20376. );
  20377. this._redraw();
  20378. // this.moving = true;
  20379. // this.start();
  20380. }
  20381. }
  20382. };
  20383. /**
  20384. * handle drag start event
  20385. * @private
  20386. */
  20387. Network.prototype._onDragEnd = function (event) {
  20388. this._handleDragEnd(event);
  20389. };
  20390. Network.prototype._handleDragEnd = function(event) {
  20391. this.drag.dragging = false;
  20392. var selection = this.drag.selection;
  20393. if (selection && selection.length) {
  20394. selection.forEach(function (s) {
  20395. // restore original xFixed and yFixed
  20396. s.node.xFixed = s.xFixed;
  20397. s.node.yFixed = s.yFixed;
  20398. });
  20399. this.moving = true;
  20400. this.start();
  20401. }
  20402. else {
  20403. this._redraw();
  20404. }
  20405. if (this.draggingNodes == false) {
  20406. this.emit("dragEnd",{nodeIds:[]});
  20407. }
  20408. else {
  20409. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  20410. }
  20411. }
  20412. /**
  20413. * handle tap/click event: select/unselect a node
  20414. * @private
  20415. */
  20416. Network.prototype._onTap = function (event) {
  20417. var pointer = this._getPointer(event.gesture.center);
  20418. this.pointerPosition = pointer;
  20419. this._handleTap(pointer);
  20420. };
  20421. /**
  20422. * handle doubletap event
  20423. * @private
  20424. */
  20425. Network.prototype._onDoubleTap = function (event) {
  20426. var pointer = this._getPointer(event.gesture.center);
  20427. this._handleDoubleTap(pointer);
  20428. };
  20429. /**
  20430. * handle long tap event: multi select nodes
  20431. * @private
  20432. */
  20433. Network.prototype._onHold = function (event) {
  20434. var pointer = this._getPointer(event.gesture.center);
  20435. this.pointerPosition = pointer;
  20436. this._handleOnHold(pointer);
  20437. };
  20438. /**
  20439. * handle the release of the screen
  20440. *
  20441. * @private
  20442. */
  20443. Network.prototype._onRelease = function (event) {
  20444. var pointer = this._getPointer(event.gesture.center);
  20445. this._handleOnRelease(pointer);
  20446. };
  20447. /**
  20448. * Handle pinch event
  20449. * @param event
  20450. * @private
  20451. */
  20452. Network.prototype._onPinch = function (event) {
  20453. var pointer = this._getPointer(event.gesture.center);
  20454. this.drag.pinched = true;
  20455. if (!('scale' in this.pinch)) {
  20456. this.pinch.scale = 1;
  20457. }
  20458. // TODO: enabled moving while pinching?
  20459. var scale = this.pinch.scale * event.gesture.scale;
  20460. this._zoom(scale, pointer)
  20461. };
  20462. /**
  20463. * Zoom the network in or out
  20464. * @param {Number} scale a number around 1, and between 0.01 and 10
  20465. * @param {{x: Number, y: Number}} pointer Position on screen
  20466. * @return {Number} appliedScale scale is limited within the boundaries
  20467. * @private
  20468. */
  20469. Network.prototype._zoom = function(scale, pointer) {
  20470. if (this.constants.zoomable == true) {
  20471. var scaleOld = this._getScale();
  20472. if (scale < 0.00001) {
  20473. scale = 0.00001;
  20474. }
  20475. if (scale > 10) {
  20476. scale = 10;
  20477. }
  20478. var preScaleDragPointer = null;
  20479. if (this.drag !== undefined) {
  20480. if (this.drag.dragging == true) {
  20481. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  20482. }
  20483. }
  20484. // + this.frame.canvas.clientHeight / 2
  20485. var translation = this._getTranslation();
  20486. var scaleFrac = scale / scaleOld;
  20487. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  20488. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  20489. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  20490. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  20491. this._setScale(scale);
  20492. this._setTranslation(tx, ty);
  20493. this.updateClustersDefault();
  20494. if (preScaleDragPointer != null) {
  20495. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  20496. this.drag.pointer.x = postScaleDragPointer.x;
  20497. this.drag.pointer.y = postScaleDragPointer.y;
  20498. }
  20499. this._redraw();
  20500. if (scaleOld < scale) {
  20501. this.emit("zoom", {direction:"+"});
  20502. }
  20503. else {
  20504. this.emit("zoom", {direction:"-"});
  20505. }
  20506. return scale;
  20507. }
  20508. };
  20509. /**
  20510. * Event handler for mouse wheel event, used to zoom the timeline
  20511. * See http://adomas.org/javascript-mouse-wheel/
  20512. * https://github.com/EightMedia/hammer.js/issues/256
  20513. * @param {MouseEvent} event
  20514. * @private
  20515. */
  20516. Network.prototype._onMouseWheel = function(event) {
  20517. // retrieve delta
  20518. var delta = 0;
  20519. if (event.wheelDelta) { /* IE/Opera. */
  20520. delta = event.wheelDelta/120;
  20521. } else if (event.detail) { /* Mozilla case. */
  20522. // In Mozilla, sign of delta is different than in IE.
  20523. // Also, delta is multiple of 3.
  20524. delta = -event.detail/3;
  20525. }
  20526. // If delta is nonzero, handle it.
  20527. // Basically, delta is now positive if wheel was scrolled up,
  20528. // and negative, if wheel was scrolled down.
  20529. if (delta) {
  20530. // calculate the new scale
  20531. var scale = this._getScale();
  20532. var zoom = delta / 10;
  20533. if (delta < 0) {
  20534. zoom = zoom / (1 - zoom);
  20535. }
  20536. scale *= (1 + zoom);
  20537. // calculate the pointer location
  20538. var gesture = hammerUtil.fakeGesture(this, event);
  20539. var pointer = this._getPointer(gesture.center);
  20540. // apply the new scale
  20541. this._zoom(scale, pointer);
  20542. }
  20543. // Prevent default actions caused by mouse wheel.
  20544. event.preventDefault();
  20545. };
  20546. /**
  20547. * Mouse move handler for checking whether the title moves over a node with a title.
  20548. * @param {Event} event
  20549. * @private
  20550. */
  20551. Network.prototype._onMouseMoveTitle = function (event) {
  20552. var gesture = hammerUtil.fakeGesture(this, event);
  20553. var pointer = this._getPointer(gesture.center);
  20554. // check if the previously selected node is still selected
  20555. if (this.popupObj) {
  20556. this._checkHidePopup(pointer);
  20557. }
  20558. // start a timeout that will check if the mouse is positioned above
  20559. // an element
  20560. var me = this;
  20561. var checkShow = function() {
  20562. me._checkShowPopup(pointer);
  20563. };
  20564. if (this.popupTimer) {
  20565. clearInterval(this.popupTimer); // stop any running calculationTimer
  20566. }
  20567. if (!this.drag.dragging) {
  20568. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  20569. }
  20570. /**
  20571. * Adding hover highlights
  20572. */
  20573. if (this.constants.hover == true) {
  20574. // removing all hover highlights
  20575. for (var edgeId in this.hoverObj.edges) {
  20576. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  20577. this.hoverObj.edges[edgeId].hover = false;
  20578. delete this.hoverObj.edges[edgeId];
  20579. }
  20580. }
  20581. // adding hover highlights
  20582. var obj = this._getNodeAt(pointer);
  20583. if (obj == null) {
  20584. obj = this._getEdgeAt(pointer);
  20585. }
  20586. if (obj != null) {
  20587. this._hoverObject(obj);
  20588. }
  20589. // removing all node hover highlights except for the selected one.
  20590. for (var nodeId in this.hoverObj.nodes) {
  20591. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  20592. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  20593. this._blurObject(this.hoverObj.nodes[nodeId]);
  20594. delete this.hoverObj.nodes[nodeId];
  20595. }
  20596. }
  20597. }
  20598. this.redraw();
  20599. }
  20600. };
  20601. /**
  20602. * Check if there is an element on the given position in the network
  20603. * (a node or edge). If so, and if this element has a title,
  20604. * show a popup window with its title.
  20605. *
  20606. * @param {{x:Number, y:Number}} pointer
  20607. * @private
  20608. */
  20609. Network.prototype._checkShowPopup = function (pointer) {
  20610. var obj = {
  20611. left: this._XconvertDOMtoCanvas(pointer.x),
  20612. top: this._YconvertDOMtoCanvas(pointer.y),
  20613. right: this._XconvertDOMtoCanvas(pointer.x),
  20614. bottom: this._YconvertDOMtoCanvas(pointer.y)
  20615. };
  20616. var id;
  20617. var lastPopupNode = this.popupObj;
  20618. if (this.popupObj == undefined) {
  20619. // search the nodes for overlap, select the top one in case of multiple nodes
  20620. var nodes = this.nodes;
  20621. for (id in nodes) {
  20622. if (nodes.hasOwnProperty(id)) {
  20623. var node = nodes[id];
  20624. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  20625. this.popupObj = node;
  20626. break;
  20627. }
  20628. }
  20629. }
  20630. }
  20631. if (this.popupObj === undefined) {
  20632. // search the edges for overlap
  20633. var edges = this.edges;
  20634. for (id in edges) {
  20635. if (edges.hasOwnProperty(id)) {
  20636. var edge = edges[id];
  20637. if (edge.connected && (edge.getTitle() !== undefined) &&
  20638. edge.isOverlappingWith(obj)) {
  20639. this.popupObj = edge;
  20640. break;
  20641. }
  20642. }
  20643. }
  20644. }
  20645. if (this.popupObj) {
  20646. // show popup message window
  20647. if (this.popupObj != lastPopupNode) {
  20648. var me = this;
  20649. if (!me.popup) {
  20650. me.popup = new Popup(me.frame, me.constants.tooltip);
  20651. }
  20652. // adjust a small offset such that the mouse cursor is located in the
  20653. // bottom left location of the popup, and you can easily move over the
  20654. // popup area
  20655. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  20656. me.popup.setText(me.popupObj.getTitle());
  20657. me.popup.show();
  20658. }
  20659. }
  20660. else {
  20661. if (this.popup) {
  20662. this.popup.hide();
  20663. }
  20664. }
  20665. };
  20666. /**
  20667. * Check if the popup must be hided, which is the case when the mouse is no
  20668. * longer hovering on the object
  20669. * @param {{x:Number, y:Number}} pointer
  20670. * @private
  20671. */
  20672. Network.prototype._checkHidePopup = function (pointer) {
  20673. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  20674. this.popupObj = undefined;
  20675. if (this.popup) {
  20676. this.popup.hide();
  20677. }
  20678. }
  20679. };
  20680. /**
  20681. * Set a new size for the network
  20682. * @param {string} width Width in pixels or percentage (for example '800px'
  20683. * or '50%')
  20684. * @param {string} height Height in pixels or percentage (for example '400px'
  20685. * or '30%')
  20686. */
  20687. Network.prototype.setSize = function(width, height) {
  20688. var emitEvent = false;
  20689. var oldWidth = this.frame.canvas.width;
  20690. var oldHeight = this.frame.canvas.height;
  20691. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  20692. this.frame.style.width = width;
  20693. this.frame.style.height = height;
  20694. this.frame.canvas.style.width = '100%';
  20695. this.frame.canvas.style.height = '100%';
  20696. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  20697. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  20698. this.constants.width = width;
  20699. this.constants.height = height;
  20700. emitEvent = true;
  20701. }
  20702. else {
  20703. // this would adapt the width of the canvas to the width from 100% if and only if
  20704. // there is a change.
  20705. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  20706. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  20707. emitEvent = true;
  20708. }
  20709. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  20710. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  20711. emitEvent = true;
  20712. }
  20713. }
  20714. if (emitEvent == true) {
  20715. 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});
  20716. }
  20717. };
  20718. /**
  20719. * Set a data set with nodes for the network
  20720. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  20721. * @private
  20722. */
  20723. Network.prototype._setNodes = function(nodes) {
  20724. var oldNodesData = this.nodesData;
  20725. if (nodes instanceof DataSet || nodes instanceof DataView) {
  20726. this.nodesData = nodes;
  20727. }
  20728. else if (Array.isArray(nodes)) {
  20729. this.nodesData = new DataSet();
  20730. this.nodesData.add(nodes);
  20731. }
  20732. else if (!nodes) {
  20733. this.nodesData = new DataSet();
  20734. }
  20735. else {
  20736. throw new TypeError('Array or DataSet expected');
  20737. }
  20738. if (oldNodesData) {
  20739. // unsubscribe from old dataset
  20740. util.forEach(this.nodesListeners, function (callback, event) {
  20741. oldNodesData.off(event, callback);
  20742. });
  20743. }
  20744. // remove drawn nodes
  20745. this.nodes = {};
  20746. if (this.nodesData) {
  20747. // subscribe to new dataset
  20748. var me = this;
  20749. util.forEach(this.nodesListeners, function (callback, event) {
  20750. me.nodesData.on(event, callback);
  20751. });
  20752. // draw all new nodes
  20753. var ids = this.nodesData.getIds();
  20754. this._addNodes(ids);
  20755. }
  20756. this._updateSelection();
  20757. };
  20758. /**
  20759. * Add nodes
  20760. * @param {Number[] | String[]} ids
  20761. * @private
  20762. */
  20763. Network.prototype._addNodes = function(ids) {
  20764. var id;
  20765. for (var i = 0, len = ids.length; i < len; i++) {
  20766. id = ids[i];
  20767. var data = this.nodesData.get(id);
  20768. var node = new Node(data, this.images, this.groups, this.constants);
  20769. this.nodes[id] = node; // note: this may replace an existing node
  20770. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  20771. var radius = 10 * 0.1*ids.length + 10;
  20772. var angle = 2 * Math.PI * Math.random();
  20773. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  20774. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  20775. }
  20776. this.moving = true;
  20777. }
  20778. this._updateNodeIndexList();
  20779. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20780. this._resetLevels();
  20781. this._setupHierarchicalLayout();
  20782. }
  20783. this._updateCalculationNodes();
  20784. this._reconnectEdges();
  20785. this._updateValueRange(this.nodes);
  20786. this.updateLabels();
  20787. };
  20788. /**
  20789. * Update existing nodes, or create them when not yet existing
  20790. * @param {Number[] | String[]} ids
  20791. * @private
  20792. */
  20793. Network.prototype._updateNodes = function(ids,changedData) {
  20794. var nodes = this.nodes;
  20795. for (var i = 0, len = ids.length; i < len; i++) {
  20796. var id = ids[i];
  20797. var node = nodes[id];
  20798. var data = changedData[i];
  20799. if (node) {
  20800. // update node
  20801. node.setProperties(data, this.constants);
  20802. }
  20803. else {
  20804. // create node
  20805. node = new Node(properties, this.images, this.groups, this.constants);
  20806. nodes[id] = node;
  20807. }
  20808. }
  20809. this.moving = true;
  20810. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20811. this._resetLevels();
  20812. this._setupHierarchicalLayout();
  20813. }
  20814. this._updateNodeIndexList();
  20815. this._updateValueRange(nodes);
  20816. };
  20817. /**
  20818. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  20819. * @param {Number[] | String[]} ids
  20820. * @private
  20821. */
  20822. Network.prototype._removeNodes = function(ids) {
  20823. var nodes = this.nodes;
  20824. for (var i = 0, len = ids.length; i < len; i++) {
  20825. var id = ids[i];
  20826. delete nodes[id];
  20827. }
  20828. this._updateNodeIndexList();
  20829. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20830. this._resetLevels();
  20831. this._setupHierarchicalLayout();
  20832. }
  20833. this._updateCalculationNodes();
  20834. this._reconnectEdges();
  20835. this._updateSelection();
  20836. this._updateValueRange(nodes);
  20837. };
  20838. /**
  20839. * Load edges by reading the data table
  20840. * @param {Array | DataSet | DataView} edges The data containing the edges.
  20841. * @private
  20842. * @private
  20843. */
  20844. Network.prototype._setEdges = function(edges) {
  20845. var oldEdgesData = this.edgesData;
  20846. if (edges instanceof DataSet || edges instanceof DataView) {
  20847. this.edgesData = edges;
  20848. }
  20849. else if (Array.isArray(edges)) {
  20850. this.edgesData = new DataSet();
  20851. this.edgesData.add(edges);
  20852. }
  20853. else if (!edges) {
  20854. this.edgesData = new DataSet();
  20855. }
  20856. else {
  20857. throw new TypeError('Array or DataSet expected');
  20858. }
  20859. if (oldEdgesData) {
  20860. // unsubscribe from old dataset
  20861. util.forEach(this.edgesListeners, function (callback, event) {
  20862. oldEdgesData.off(event, callback);
  20863. });
  20864. }
  20865. // remove drawn edges
  20866. this.edges = {};
  20867. if (this.edgesData) {
  20868. // subscribe to new dataset
  20869. var me = this;
  20870. util.forEach(this.edgesListeners, function (callback, event) {
  20871. me.edgesData.on(event, callback);
  20872. });
  20873. // draw all new nodes
  20874. var ids = this.edgesData.getIds();
  20875. this._addEdges(ids);
  20876. }
  20877. this._reconnectEdges();
  20878. };
  20879. /**
  20880. * Add edges
  20881. * @param {Number[] | String[]} ids
  20882. * @private
  20883. */
  20884. Network.prototype._addEdges = function (ids) {
  20885. var edges = this.edges,
  20886. edgesData = this.edgesData;
  20887. for (var i = 0, len = ids.length; i < len; i++) {
  20888. var id = ids[i];
  20889. var oldEdge = edges[id];
  20890. if (oldEdge) {
  20891. oldEdge.disconnect();
  20892. }
  20893. var data = edgesData.get(id, {"showInternalIds" : true});
  20894. edges[id] = new Edge(data, this, this.constants);
  20895. }
  20896. this.moving = true;
  20897. this._updateValueRange(edges);
  20898. this._createBezierNodes();
  20899. this._updateCalculationNodes();
  20900. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20901. this._resetLevels();
  20902. this._setupHierarchicalLayout();
  20903. }
  20904. };
  20905. /**
  20906. * Update existing edges, or create them when not yet existing
  20907. * @param {Number[] | String[]} ids
  20908. * @private
  20909. */
  20910. Network.prototype._updateEdges = function (ids) {
  20911. var edges = this.edges,
  20912. edgesData = this.edgesData;
  20913. for (var i = 0, len = ids.length; i < len; i++) {
  20914. var id = ids[i];
  20915. var data = edgesData.get(id);
  20916. var edge = edges[id];
  20917. if (edge) {
  20918. // update edge
  20919. edge.disconnect();
  20920. edge.setProperties(data, this.constants);
  20921. edge.connect();
  20922. }
  20923. else {
  20924. // create edge
  20925. edge = new Edge(data, this, this.constants);
  20926. this.edges[id] = edge;
  20927. }
  20928. }
  20929. this._createBezierNodes();
  20930. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20931. this._resetLevels();
  20932. this._setupHierarchicalLayout();
  20933. }
  20934. this.moving = true;
  20935. this._updateValueRange(edges);
  20936. };
  20937. /**
  20938. * Remove existing edges. Non existing ids will be ignored
  20939. * @param {Number[] | String[]} ids
  20940. * @private
  20941. */
  20942. Network.prototype._removeEdges = function (ids) {
  20943. var edges = this.edges;
  20944. for (var i = 0, len = ids.length; i < len; i++) {
  20945. var id = ids[i];
  20946. var edge = edges[id];
  20947. if (edge) {
  20948. if (edge.via != null) {
  20949. delete this.sectors['support']['nodes'][edge.via.id];
  20950. }
  20951. edge.disconnect();
  20952. delete edges[id];
  20953. }
  20954. }
  20955. this.moving = true;
  20956. this._updateValueRange(edges);
  20957. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  20958. this._resetLevels();
  20959. this._setupHierarchicalLayout();
  20960. }
  20961. this._updateCalculationNodes();
  20962. };
  20963. /**
  20964. * Reconnect all edges
  20965. * @private
  20966. */
  20967. Network.prototype._reconnectEdges = function() {
  20968. var id,
  20969. nodes = this.nodes,
  20970. edges = this.edges;
  20971. for (id in nodes) {
  20972. if (nodes.hasOwnProperty(id)) {
  20973. nodes[id].edges = [];
  20974. nodes[id].dynamicEdges = [];
  20975. }
  20976. }
  20977. for (id in edges) {
  20978. if (edges.hasOwnProperty(id)) {
  20979. var edge = edges[id];
  20980. edge.from = null;
  20981. edge.to = null;
  20982. edge.connect();
  20983. }
  20984. }
  20985. };
  20986. /**
  20987. * Update the values of all object in the given array according to the current
  20988. * value range of the objects in the array.
  20989. * @param {Object} obj An object containing a set of Edges or Nodes
  20990. * The objects must have a method getValue() and
  20991. * setValueRange(min, max).
  20992. * @private
  20993. */
  20994. Network.prototype._updateValueRange = function(obj) {
  20995. var id;
  20996. // determine the range of the objects
  20997. var valueMin = undefined;
  20998. var valueMax = undefined;
  20999. for (id in obj) {
  21000. if (obj.hasOwnProperty(id)) {
  21001. var value = obj[id].getValue();
  21002. if (value !== undefined) {
  21003. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  21004. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  21005. }
  21006. }
  21007. }
  21008. // adjust the range of all objects
  21009. if (valueMin !== undefined && valueMax !== undefined) {
  21010. for (id in obj) {
  21011. if (obj.hasOwnProperty(id)) {
  21012. obj[id].setValueRange(valueMin, valueMax);
  21013. }
  21014. }
  21015. }
  21016. };
  21017. /**
  21018. * Redraw the network with the current data
  21019. * chart will be resized too.
  21020. */
  21021. Network.prototype.redraw = function() {
  21022. this.setSize(this.constants.width, this.constants.height);
  21023. this._redraw();
  21024. };
  21025. /**
  21026. * Redraw the network with the current data
  21027. * @private
  21028. */
  21029. Network.prototype._redraw = function() {
  21030. var ctx = this.frame.canvas.getContext('2d');
  21031. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  21032. // clear the canvas
  21033. var w = this.frame.canvas.width * this.pixelRatio;
  21034. var h = this.frame.canvas.height * this.pixelRatio;
  21035. ctx.clearRect(0, 0, w, h);
  21036. // set scaling and translation
  21037. ctx.save();
  21038. ctx.translate(this.translation.x, this.translation.y);
  21039. ctx.scale(this.scale, this.scale);
  21040. this.canvasTopLeft = {
  21041. "x": this._XconvertDOMtoCanvas(0),
  21042. "y": this._YconvertDOMtoCanvas(0)
  21043. };
  21044. this.canvasBottomRight = {
  21045. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth * this.pixelRatio),
  21046. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight * this.pixelRatio)
  21047. };
  21048. this._doInAllSectors("_drawAllSectorNodes",ctx);
  21049. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  21050. this._doInAllSectors("_drawEdges",ctx);
  21051. }
  21052. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  21053. this._doInAllSectors("_drawNodes",ctx,false);
  21054. }
  21055. if (this.controlNodesActive == true) {
  21056. this._doInAllSectors("_drawControlNodes",ctx);
  21057. }
  21058. // this._doInSupportSector("_drawNodes",ctx,true);
  21059. // this._drawTree(ctx,"#F00F0F");
  21060. // restore original scaling and translation
  21061. ctx.restore();
  21062. };
  21063. /**
  21064. * Set the translation of the network
  21065. * @param {Number} offsetX Horizontal offset
  21066. * @param {Number} offsetY Vertical offset
  21067. * @private
  21068. */
  21069. Network.prototype._setTranslation = function(offsetX, offsetY) {
  21070. if (this.translation === undefined) {
  21071. this.translation = {
  21072. x: 0,
  21073. y: 0
  21074. };
  21075. }
  21076. if (offsetX !== undefined) {
  21077. this.translation.x = offsetX;
  21078. }
  21079. if (offsetY !== undefined) {
  21080. this.translation.y = offsetY;
  21081. }
  21082. this.emit('viewChanged');
  21083. };
  21084. /**
  21085. * Get the translation of the network
  21086. * @return {Object} translation An object with parameters x and y, both a number
  21087. * @private
  21088. */
  21089. Network.prototype._getTranslation = function() {
  21090. return {
  21091. x: this.translation.x,
  21092. y: this.translation.y
  21093. };
  21094. };
  21095. /**
  21096. * Scale the network
  21097. * @param {Number} scale Scaling factor 1.0 is unscaled
  21098. * @private
  21099. */
  21100. Network.prototype._setScale = function(scale) {
  21101. this.scale = scale;
  21102. };
  21103. /**
  21104. * Get the current scale of the network
  21105. * @return {Number} scale Scaling factor 1.0 is unscaled
  21106. * @private
  21107. */
  21108. Network.prototype._getScale = function() {
  21109. return this.scale;
  21110. };
  21111. /**
  21112. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  21113. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  21114. * @param {number} x
  21115. * @returns {number}
  21116. * @private
  21117. */
  21118. Network.prototype._XconvertDOMtoCanvas = function(x) {
  21119. return (x - this.translation.x) / this.scale;
  21120. };
  21121. /**
  21122. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  21123. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  21124. * @param {number} x
  21125. * @returns {number}
  21126. * @private
  21127. */
  21128. Network.prototype._XconvertCanvasToDOM = function(x) {
  21129. return x * this.scale + this.translation.x;
  21130. };
  21131. /**
  21132. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  21133. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  21134. * @param {number} y
  21135. * @returns {number}
  21136. * @private
  21137. */
  21138. Network.prototype._YconvertDOMtoCanvas = function(y) {
  21139. return (y - this.translation.y) / this.scale;
  21140. };
  21141. /**
  21142. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  21143. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  21144. * @param {number} y
  21145. * @returns {number}
  21146. * @private
  21147. */
  21148. Network.prototype._YconvertCanvasToDOM = function(y) {
  21149. return y * this.scale + this.translation.y ;
  21150. };
  21151. /**
  21152. *
  21153. * @param {object} pos = {x: number, y: number}
  21154. * @returns {{x: number, y: number}}
  21155. * @constructor
  21156. */
  21157. Network.prototype.canvasToDOM = function (pos) {
  21158. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  21159. };
  21160. /**
  21161. *
  21162. * @param {object} pos = {x: number, y: number}
  21163. * @returns {{x: number, y: number}}
  21164. * @constructor
  21165. */
  21166. Network.prototype.DOMtoCanvas = function (pos) {
  21167. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  21168. };
  21169. /**
  21170. * Redraw all nodes
  21171. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  21172. * @param {CanvasRenderingContext2D} ctx
  21173. * @param {Boolean} [alwaysShow]
  21174. * @private
  21175. */
  21176. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  21177. if (alwaysShow === undefined) {
  21178. alwaysShow = false;
  21179. }
  21180. // first draw the unselected nodes
  21181. var nodes = this.nodes;
  21182. var selected = [];
  21183. for (var id in nodes) {
  21184. if (nodes.hasOwnProperty(id)) {
  21185. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  21186. if (nodes[id].isSelected()) {
  21187. selected.push(id);
  21188. }
  21189. else {
  21190. if (nodes[id].inArea() || alwaysShow) {
  21191. nodes[id].draw(ctx);
  21192. }
  21193. }
  21194. }
  21195. }
  21196. // draw the selected nodes on top
  21197. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  21198. if (nodes[selected[s]].inArea() || alwaysShow) {
  21199. nodes[selected[s]].draw(ctx);
  21200. }
  21201. }
  21202. };
  21203. /**
  21204. * Redraw all edges
  21205. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  21206. * @param {CanvasRenderingContext2D} ctx
  21207. * @private
  21208. */
  21209. Network.prototype._drawEdges = function(ctx) {
  21210. var edges = this.edges;
  21211. for (var id in edges) {
  21212. if (edges.hasOwnProperty(id)) {
  21213. var edge = edges[id];
  21214. edge.setScale(this.scale);
  21215. if (edge.connected) {
  21216. edges[id].draw(ctx);
  21217. }
  21218. }
  21219. }
  21220. };
  21221. /**
  21222. * Redraw all edges
  21223. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  21224. * @param {CanvasRenderingContext2D} ctx
  21225. * @private
  21226. */
  21227. Network.prototype._drawControlNodes = function(ctx) {
  21228. var edges = this.edges;
  21229. for (var id in edges) {
  21230. if (edges.hasOwnProperty(id)) {
  21231. edges[id]._drawControlNodes(ctx);
  21232. }
  21233. }
  21234. };
  21235. /**
  21236. * Find a stable position for all nodes
  21237. * @private
  21238. */
  21239. Network.prototype._stabilize = function() {
  21240. if (this.constants.freezeForStabilization == true) {
  21241. this._freezeDefinedNodes();
  21242. }
  21243. // find stable position
  21244. var count = 0;
  21245. while (this.moving && count < this.constants.stabilizationIterations) {
  21246. this._physicsTick();
  21247. count++;
  21248. }
  21249. this.zoomExtent(undefined,false,true);
  21250. if (this.constants.freezeForStabilization == true) {
  21251. this._restoreFrozenNodes();
  21252. }
  21253. };
  21254. /**
  21255. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  21256. * because only the supportnodes for the smoothCurves have to settle.
  21257. *
  21258. * @private
  21259. */
  21260. Network.prototype._freezeDefinedNodes = function() {
  21261. var nodes = this.nodes;
  21262. for (var id in nodes) {
  21263. if (nodes.hasOwnProperty(id)) {
  21264. if (nodes[id].x != null && nodes[id].y != null) {
  21265. nodes[id].fixedData.x = nodes[id].xFixed;
  21266. nodes[id].fixedData.y = nodes[id].yFixed;
  21267. nodes[id].xFixed = true;
  21268. nodes[id].yFixed = true;
  21269. }
  21270. }
  21271. }
  21272. };
  21273. /**
  21274. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  21275. *
  21276. * @private
  21277. */
  21278. Network.prototype._restoreFrozenNodes = function() {
  21279. var nodes = this.nodes;
  21280. for (var id in nodes) {
  21281. if (nodes.hasOwnProperty(id)) {
  21282. if (nodes[id].fixedData.x != null) {
  21283. nodes[id].xFixed = nodes[id].fixedData.x;
  21284. nodes[id].yFixed = nodes[id].fixedData.y;
  21285. }
  21286. }
  21287. }
  21288. };
  21289. /**
  21290. * Check if any of the nodes is still moving
  21291. * @param {number} vmin the minimum velocity considered as 'moving'
  21292. * @return {boolean} true if moving, false if non of the nodes is moving
  21293. * @private
  21294. */
  21295. Network.prototype._isMoving = function(vmin) {
  21296. var nodes = this.nodes;
  21297. for (var id in nodes) {
  21298. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  21299. return true;
  21300. }
  21301. }
  21302. return false;
  21303. };
  21304. /**
  21305. * /**
  21306. * Perform one discrete step for all nodes
  21307. *
  21308. * @private
  21309. */
  21310. Network.prototype._discreteStepNodes = function() {
  21311. var interval = this.physicsDiscreteStepsize;
  21312. var nodes = this.nodes;
  21313. var nodeId;
  21314. var nodesPresent = false;
  21315. if (this.constants.maxVelocity > 0) {
  21316. for (nodeId in nodes) {
  21317. if (nodes.hasOwnProperty(nodeId)) {
  21318. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  21319. nodesPresent = true;
  21320. }
  21321. }
  21322. }
  21323. else {
  21324. for (nodeId in nodes) {
  21325. if (nodes.hasOwnProperty(nodeId)) {
  21326. nodes[nodeId].discreteStep(interval);
  21327. nodesPresent = true;
  21328. }
  21329. }
  21330. }
  21331. if (nodesPresent == true) {
  21332. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  21333. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  21334. return true;
  21335. }
  21336. else {
  21337. return this._isMoving(vminCorrected);
  21338. }
  21339. }
  21340. return false;
  21341. };
  21342. /**
  21343. * A single simulation step (or "tick") in the physics simulation
  21344. *
  21345. * @private
  21346. */
  21347. Network.prototype._physicsTick = function() {
  21348. if (!this.freezeSimulation) {
  21349. if (this.moving == true) {
  21350. var mainMovingStatus = false;
  21351. var supportMovingStatus = false;
  21352. this._doInAllActiveSectors("_initializeForceCalculation");
  21353. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  21354. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  21355. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  21356. }
  21357. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  21358. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  21359. // determine if the network has stabilzied
  21360. this.moving = mainMovingStatus || supportMovingStatus;
  21361. this.stabilizationIterations++;
  21362. }
  21363. }
  21364. };
  21365. /**
  21366. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  21367. * It reschedules itself at the beginning of the function
  21368. *
  21369. * @private
  21370. */
  21371. Network.prototype._animationStep = function() {
  21372. // reset the timer so a new scheduled animation step can be set
  21373. this.timer = undefined;
  21374. // handle the keyboad movement
  21375. this._handleNavigation();
  21376. // this schedules a new animation step
  21377. this.start();
  21378. // start the physics simulation
  21379. var calculationTime = Date.now();
  21380. var maxSteps = 1;
  21381. this._physicsTick();
  21382. var timeRequired = Date.now() - calculationTime;
  21383. while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  21384. this._physicsTick();
  21385. timeRequired = Date.now() - calculationTime;
  21386. maxSteps++;
  21387. }
  21388. // start the rendering process
  21389. var renderTime = Date.now();
  21390. this._redraw();
  21391. this.renderTime = Date.now() - renderTime;
  21392. };
  21393. if (typeof window !== 'undefined') {
  21394. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  21395. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  21396. }
  21397. /**
  21398. * Schedule a animation step with the refreshrate interval.
  21399. */
  21400. Network.prototype.start = function() {
  21401. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  21402. if (this.startedStabilization == false) {
  21403. this.emit("startStabilization");
  21404. this.startedStabilization = true;
  21405. }
  21406. if (!this.timer) {
  21407. var ua = navigator.userAgent.toLowerCase();
  21408. var requiresTimeout = false;
  21409. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  21410. requiresTimeout = true;
  21411. }
  21412. else if (ua.indexOf('safari') != -1) { // safari
  21413. if (ua.indexOf('chrome') <= -1) {
  21414. requiresTimeout = true;
  21415. }
  21416. }
  21417. if (requiresTimeout == true) {
  21418. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  21419. }
  21420. else{
  21421. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  21422. }
  21423. }
  21424. }
  21425. else {
  21426. this._redraw();
  21427. if (this.stabilizationIterations > 0) {
  21428. // trigger the "stabilized" event.
  21429. // The event is triggered on the next tick, to prevent the case that
  21430. // it is fired while initializing the Network, in which case you would not
  21431. // be able to catch it
  21432. var me = this;
  21433. var params = {
  21434. iterations: me.stabilizationIterations
  21435. };
  21436. me.stabilizationIterations = 0;
  21437. me.startedStabilization = false;
  21438. setTimeout(function () {
  21439. me.emit("stabilized", params);
  21440. }, 0);
  21441. }
  21442. }
  21443. };
  21444. /**
  21445. * Move the network according to the keyboard presses.
  21446. *
  21447. * @private
  21448. */
  21449. Network.prototype._handleNavigation = function() {
  21450. if (this.xIncrement != 0 || this.yIncrement != 0) {
  21451. var translation = this._getTranslation();
  21452. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  21453. }
  21454. if (this.zoomIncrement != 0) {
  21455. var center = {
  21456. x: this.frame.canvas.clientWidth / 2,
  21457. y: this.frame.canvas.clientHeight / 2
  21458. };
  21459. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  21460. }
  21461. };
  21462. /**
  21463. * Freeze the _animationStep
  21464. */
  21465. Network.prototype.toggleFreeze = function() {
  21466. if (this.freezeSimulation == false) {
  21467. this.freezeSimulation = true;
  21468. }
  21469. else {
  21470. this.freezeSimulation = false;
  21471. this.start();
  21472. }
  21473. };
  21474. /**
  21475. * This function cleans the support nodes if they are not needed and adds them when they are.
  21476. *
  21477. * @param {boolean} [disableStart]
  21478. * @private
  21479. */
  21480. Network.prototype._configureSmoothCurves = function(disableStart) {
  21481. if (disableStart === undefined) {
  21482. disableStart = true;
  21483. }
  21484. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  21485. this._createBezierNodes();
  21486. // cleanup unused support nodes
  21487. for (var nodeId in this.sectors['support']['nodes']) {
  21488. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  21489. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  21490. delete this.sectors['support']['nodes'][nodeId];
  21491. }
  21492. }
  21493. }
  21494. }
  21495. else {
  21496. // delete the support nodes
  21497. this.sectors['support']['nodes'] = {};
  21498. for (var edgeId in this.edges) {
  21499. if (this.edges.hasOwnProperty(edgeId)) {
  21500. this.edges[edgeId].via = null;
  21501. }
  21502. }
  21503. }
  21504. this._updateCalculationNodes();
  21505. if (!disableStart) {
  21506. this.moving = true;
  21507. this.start();
  21508. }
  21509. };
  21510. /**
  21511. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  21512. * are used for the force calculation.
  21513. *
  21514. * @private
  21515. */
  21516. Network.prototype._createBezierNodes = function() {
  21517. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  21518. for (var edgeId in this.edges) {
  21519. if (this.edges.hasOwnProperty(edgeId)) {
  21520. var edge = this.edges[edgeId];
  21521. if (edge.via == null) {
  21522. var nodeId = "edgeId:".concat(edge.id);
  21523. this.sectors['support']['nodes'][nodeId] = new Node(
  21524. {id:nodeId,
  21525. mass:1,
  21526. shape:'circle',
  21527. image:"",
  21528. internalMultiplier:1
  21529. },{},{},this.constants);
  21530. edge.via = this.sectors['support']['nodes'][nodeId];
  21531. edge.via.parentEdgeId = edge.id;
  21532. edge.positionBezierNode();
  21533. }
  21534. }
  21535. }
  21536. }
  21537. };
  21538. /**
  21539. * load the functions that load the mixins into the prototype.
  21540. *
  21541. * @private
  21542. */
  21543. Network.prototype._initializeMixinLoaders = function () {
  21544. for (var mixin in MixinLoader) {
  21545. if (MixinLoader.hasOwnProperty(mixin)) {
  21546. Network.prototype[mixin] = MixinLoader[mixin];
  21547. }
  21548. }
  21549. };
  21550. /**
  21551. * Load the XY positions of the nodes into the dataset.
  21552. */
  21553. Network.prototype.storePosition = function() {
  21554. console.log("storePosition is depricated: use .storePositions() from now on.")
  21555. this.storePositions();
  21556. };
  21557. /**
  21558. * Load the XY positions of the nodes into the dataset.
  21559. */
  21560. Network.prototype.storePositions = function() {
  21561. var dataArray = [];
  21562. for (var nodeId in this.nodes) {
  21563. if (this.nodes.hasOwnProperty(nodeId)) {
  21564. var node = this.nodes[nodeId];
  21565. var allowedToMoveX = !this.nodes.xFixed;
  21566. var allowedToMoveY = !this.nodes.yFixed;
  21567. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  21568. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  21569. }
  21570. }
  21571. }
  21572. this.nodesData.update(dataArray);
  21573. };
  21574. /**
  21575. * Return the positions of the nodes.
  21576. */
  21577. Network.prototype.getPositions = function(ids) {
  21578. var dataArray = {};
  21579. if (ids !== undefined) {
  21580. if (Array.isArray(ids) == true) {
  21581. for (var i = 0; i < ids.length; i++) {
  21582. if (this.nodes[ids[i]] !== undefined) {
  21583. var node = this.nodes[ids[i]];
  21584. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  21585. }
  21586. }
  21587. }
  21588. else {
  21589. if (this.nodes[ids] !== undefined) {
  21590. var node = this.nodes[ids];
  21591. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  21592. }
  21593. }
  21594. }
  21595. else {
  21596. for (var nodeId in this.nodes) {
  21597. if (this.nodes.hasOwnProperty(nodeId)) {
  21598. var node = this.nodes[nodeId];
  21599. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  21600. }
  21601. }
  21602. }
  21603. return dataArray;
  21604. };
  21605. /**
  21606. * Center a node in view.
  21607. *
  21608. * @param {Number} nodeId
  21609. * @param {Number} [options]
  21610. */
  21611. Network.prototype.focusOnNode = function (nodeId, options) {
  21612. if (this.nodes.hasOwnProperty(nodeId)) {
  21613. if (options === undefined) {
  21614. options = {};
  21615. }
  21616. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  21617. options.position = nodePosition;
  21618. options.lockedOnNode = nodeId;
  21619. this.moveTo(options)
  21620. }
  21621. else {
  21622. console.log("This nodeId cannot be found.");
  21623. }
  21624. };
  21625. /**
  21626. *
  21627. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  21628. * | options.scale = Number // scale to move to
  21629. * | options.position = {x:Number, y:Number} // position to move to
  21630. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  21631. */
  21632. Network.prototype.moveTo = function (options) {
  21633. if (options === undefined) {
  21634. options = {};
  21635. return;
  21636. }
  21637. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  21638. if (options.offset.x === undefined) {options.offset.x = 0; }
  21639. if (options.offset.y === undefined) {options.offset.y = 0; }
  21640. if (options.scale === undefined) {options.scale = this._getScale(); }
  21641. if (options.position === undefined) {options.position = this._getTranslation();}
  21642. if (options.animation === undefined) {options.animation = {duration:0}; }
  21643. if (options.animation === false ) {options.animation = {duration:0}; }
  21644. if (options.animation === true ) {options.animation = {}; }
  21645. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  21646. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  21647. this.animateView(options);
  21648. };
  21649. /**
  21650. *
  21651. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  21652. * | options.time = Number // animation time in milliseconds
  21653. * | options.scale = Number // scale to animate to
  21654. * | options.position = {x:Number, y:Number} // position to animate to
  21655. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  21656. * // easeInCubic, easeOutCubic, easeInOutCubic,
  21657. * // easeInQuart, easeOutQuart, easeInOutQuart,
  21658. * // easeInQuint, easeOutQuint, easeInOutQuint
  21659. */
  21660. Network.prototype.animateView = function (options) {
  21661. if (options === undefined) {
  21662. options = {};
  21663. return;
  21664. }
  21665. // release if something focussed on the node
  21666. this.releaseNode();
  21667. if (options.locked == true) {
  21668. this.lockedOnNodeId = options.lockedOnNode;
  21669. this.lockedOnNodeOffset = options.offset;
  21670. }
  21671. // forcefully complete the old animation if it was still running
  21672. if (this.easingTime != 0) {
  21673. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  21674. }
  21675. this.sourceScale = this._getScale();
  21676. this.sourceTranslation = this._getTranslation();
  21677. this.targetScale = options.scale;
  21678. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  21679. // but at least then we'll have the target transition
  21680. this._setScale(this.targetScale);
  21681. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  21682. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  21683. x: viewCenter.x - options.position.x,
  21684. y: viewCenter.y - options.position.y
  21685. };
  21686. this.targetTranslation = {
  21687. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  21688. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  21689. };
  21690. // if the time is set to 0, don't do an animation
  21691. if (options.animation.duration == 0) {
  21692. if (this.lockedOnNodeId != null) {
  21693. this._classicRedraw = this._redraw;
  21694. this._redraw = this._lockedRedraw;
  21695. }
  21696. else {
  21697. this._setScale(this.targetScale);
  21698. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  21699. this._redraw();
  21700. }
  21701. }
  21702. else {
  21703. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  21704. this.animationEasingFunction = options.animation.easingFunction;
  21705. this._classicRedraw = this._redraw;
  21706. this._redraw = this._transitionRedraw;
  21707. this._redraw();
  21708. this.moving = true;
  21709. this.start();
  21710. }
  21711. };
  21712. Network.prototype._lockedRedraw = function () {
  21713. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  21714. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  21715. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  21716. x: viewCenter.x - nodePosition.x,
  21717. y: viewCenter.y - nodePosition.y
  21718. };
  21719. var sourceTranslation = this._getTranslation();
  21720. var targetTranslation = {
  21721. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  21722. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  21723. };
  21724. this._setTranslation(targetTranslation.x,targetTranslation.y);
  21725. this._classicRedraw();
  21726. }
  21727. Network.prototype.releaseNode = function () {
  21728. if (this.lockedOnNodeId != null) {
  21729. this._redraw = this._classicRedraw;
  21730. this.lockedOnNodeId = null;
  21731. this.lockedOnNodeOffset = null;
  21732. }
  21733. }
  21734. /**
  21735. *
  21736. * @param easingTime
  21737. * @private
  21738. */
  21739. Network.prototype._transitionRedraw = function (easingTime) {
  21740. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  21741. this.easingTime += this.animationSpeed;
  21742. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  21743. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  21744. this._setTranslation(
  21745. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  21746. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  21747. );
  21748. this._classicRedraw();
  21749. this.moving = true;
  21750. // cleanup
  21751. if (this.easingTime >= 1.0) {
  21752. this.easingTime = 0;
  21753. if (this.lockedOnNodeId != null) {
  21754. this._redraw = this._lockedRedraw;
  21755. }
  21756. else {
  21757. this._redraw = this._classicRedraw;
  21758. }
  21759. this.emit("animationFinished");
  21760. }
  21761. };
  21762. Network.prototype._classicRedraw = function () {
  21763. // placeholder function to be overloaded by animations;
  21764. };
  21765. /**
  21766. * Returns true when the Network is active.
  21767. * @returns {boolean}
  21768. */
  21769. Network.prototype.isActive = function () {
  21770. return !this.activator || this.activator.active;
  21771. };
  21772. /**
  21773. * Sets the scale
  21774. * @returns {Number}
  21775. */
  21776. Network.prototype.setScale = function () {
  21777. return this._setScale();
  21778. };
  21779. /**
  21780. * Returns the scale
  21781. * @returns {Number}
  21782. */
  21783. Network.prototype.getScale = function () {
  21784. return this._getScale();
  21785. };
  21786. /**
  21787. * Returns the scale
  21788. * @returns {Number}
  21789. */
  21790. Network.prototype.getCenterCoordinates = function () {
  21791. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  21792. };
  21793. module.exports = Network;
  21794. /***/ },
  21795. /* 52 */
  21796. /***/ function(module, exports, __webpack_require__) {
  21797. /**
  21798. * Parse a text source containing data in DOT language into a JSON object.
  21799. * The object contains two lists: one with nodes and one with edges.
  21800. *
  21801. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  21802. *
  21803. * @param {String} data Text containing a graph in DOT-notation
  21804. * @return {Object} graph An object containing two parameters:
  21805. * {Object[]} nodes
  21806. * {Object[]} edges
  21807. */
  21808. function parseDOT (data) {
  21809. dot = data;
  21810. return parseGraph();
  21811. }
  21812. // token types enumeration
  21813. var TOKENTYPE = {
  21814. NULL : 0,
  21815. DELIMITER : 1,
  21816. IDENTIFIER: 2,
  21817. UNKNOWN : 3
  21818. };
  21819. // map with all delimiters
  21820. var DELIMITERS = {
  21821. '{': true,
  21822. '}': true,
  21823. '[': true,
  21824. ']': true,
  21825. ';': true,
  21826. '=': true,
  21827. ',': true,
  21828. '->': true,
  21829. '--': true
  21830. };
  21831. var dot = ''; // current dot file
  21832. var index = 0; // current index in dot file
  21833. var c = ''; // current token character in expr
  21834. var token = ''; // current token
  21835. var tokenType = TOKENTYPE.NULL; // type of the token
  21836. /**
  21837. * Get the first character from the dot file.
  21838. * The character is stored into the char c. If the end of the dot file is
  21839. * reached, the function puts an empty string in c.
  21840. */
  21841. function first() {
  21842. index = 0;
  21843. c = dot.charAt(0);
  21844. }
  21845. /**
  21846. * Get the next character from the dot file.
  21847. * The character is stored into the char c. If the end of the dot file is
  21848. * reached, the function puts an empty string in c.
  21849. */
  21850. function next() {
  21851. index++;
  21852. c = dot.charAt(index);
  21853. }
  21854. /**
  21855. * Preview the next character from the dot file.
  21856. * @return {String} cNext
  21857. */
  21858. function nextPreview() {
  21859. return dot.charAt(index + 1);
  21860. }
  21861. /**
  21862. * Test whether given character is alphabetic or numeric
  21863. * @param {String} c
  21864. * @return {Boolean} isAlphaNumeric
  21865. */
  21866. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  21867. function isAlphaNumeric(c) {
  21868. return regexAlphaNumeric.test(c);
  21869. }
  21870. /**
  21871. * Merge all properties of object b into object b
  21872. * @param {Object} a
  21873. * @param {Object} b
  21874. * @return {Object} a
  21875. */
  21876. function merge (a, b) {
  21877. if (!a) {
  21878. a = {};
  21879. }
  21880. if (b) {
  21881. for (var name in b) {
  21882. if (b.hasOwnProperty(name)) {
  21883. a[name] = b[name];
  21884. }
  21885. }
  21886. }
  21887. return a;
  21888. }
  21889. /**
  21890. * Set a value in an object, where the provided parameter name can be a
  21891. * path with nested parameters. For example:
  21892. *
  21893. * var obj = {a: 2};
  21894. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  21895. *
  21896. * @param {Object} obj
  21897. * @param {String} path A parameter name or dot-separated parameter path,
  21898. * like "color.highlight.border".
  21899. * @param {*} value
  21900. */
  21901. function setValue(obj, path, value) {
  21902. var keys = path.split('.');
  21903. var o = obj;
  21904. while (keys.length) {
  21905. var key = keys.shift();
  21906. if (keys.length) {
  21907. // this isn't the end point
  21908. if (!o[key]) {
  21909. o[key] = {};
  21910. }
  21911. o = o[key];
  21912. }
  21913. else {
  21914. // this is the end point
  21915. o[key] = value;
  21916. }
  21917. }
  21918. }
  21919. /**
  21920. * Add a node to a graph object. If there is already a node with
  21921. * the same id, their attributes will be merged.
  21922. * @param {Object} graph
  21923. * @param {Object} node
  21924. */
  21925. function addNode(graph, node) {
  21926. var i, len;
  21927. var current = null;
  21928. // find root graph (in case of subgraph)
  21929. var graphs = [graph]; // list with all graphs from current graph to root graph
  21930. var root = graph;
  21931. while (root.parent) {
  21932. graphs.push(root.parent);
  21933. root = root.parent;
  21934. }
  21935. // find existing node (at root level) by its id
  21936. if (root.nodes) {
  21937. for (i = 0, len = root.nodes.length; i < len; i++) {
  21938. if (node.id === root.nodes[i].id) {
  21939. current = root.nodes[i];
  21940. break;
  21941. }
  21942. }
  21943. }
  21944. if (!current) {
  21945. // this is a new node
  21946. current = {
  21947. id: node.id
  21948. };
  21949. if (graph.node) {
  21950. // clone default attributes
  21951. current.attr = merge(current.attr, graph.node);
  21952. }
  21953. }
  21954. // add node to this (sub)graph and all its parent graphs
  21955. for (i = graphs.length - 1; i >= 0; i--) {
  21956. var g = graphs[i];
  21957. if (!g.nodes) {
  21958. g.nodes = [];
  21959. }
  21960. if (g.nodes.indexOf(current) == -1) {
  21961. g.nodes.push(current);
  21962. }
  21963. }
  21964. // merge attributes
  21965. if (node.attr) {
  21966. current.attr = merge(current.attr, node.attr);
  21967. }
  21968. }
  21969. /**
  21970. * Add an edge to a graph object
  21971. * @param {Object} graph
  21972. * @param {Object} edge
  21973. */
  21974. function addEdge(graph, edge) {
  21975. if (!graph.edges) {
  21976. graph.edges = [];
  21977. }
  21978. graph.edges.push(edge);
  21979. if (graph.edge) {
  21980. var attr = merge({}, graph.edge); // clone default attributes
  21981. edge.attr = merge(attr, edge.attr); // merge attributes
  21982. }
  21983. }
  21984. /**
  21985. * Create an edge to a graph object
  21986. * @param {Object} graph
  21987. * @param {String | Number | Object} from
  21988. * @param {String | Number | Object} to
  21989. * @param {String} type
  21990. * @param {Object | null} attr
  21991. * @return {Object} edge
  21992. */
  21993. function createEdge(graph, from, to, type, attr) {
  21994. var edge = {
  21995. from: from,
  21996. to: to,
  21997. type: type
  21998. };
  21999. if (graph.edge) {
  22000. edge.attr = merge({}, graph.edge); // clone default attributes
  22001. }
  22002. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  22003. return edge;
  22004. }
  22005. /**
  22006. * Get next token in the current dot file.
  22007. * The token and token type are available as token and tokenType
  22008. */
  22009. function getToken() {
  22010. tokenType = TOKENTYPE.NULL;
  22011. token = '';
  22012. // skip over whitespaces
  22013. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  22014. next();
  22015. }
  22016. do {
  22017. var isComment = false;
  22018. // skip comment
  22019. if (c == '#') {
  22020. // find the previous non-space character
  22021. var i = index - 1;
  22022. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  22023. i--;
  22024. }
  22025. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  22026. // the # is at the start of a line, this is indeed a line comment
  22027. while (c != '' && c != '\n') {
  22028. next();
  22029. }
  22030. isComment = true;
  22031. }
  22032. }
  22033. if (c == '/' && nextPreview() == '/') {
  22034. // skip line comment
  22035. while (c != '' && c != '\n') {
  22036. next();
  22037. }
  22038. isComment = true;
  22039. }
  22040. if (c == '/' && nextPreview() == '*') {
  22041. // skip block comment
  22042. while (c != '') {
  22043. if (c == '*' && nextPreview() == '/') {
  22044. // end of block comment found. skip these last two characters
  22045. next();
  22046. next();
  22047. break;
  22048. }
  22049. else {
  22050. next();
  22051. }
  22052. }
  22053. isComment = true;
  22054. }
  22055. // skip over whitespaces
  22056. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  22057. next();
  22058. }
  22059. }
  22060. while (isComment);
  22061. // check for end of dot file
  22062. if (c == '') {
  22063. // token is still empty
  22064. tokenType = TOKENTYPE.DELIMITER;
  22065. return;
  22066. }
  22067. // check for delimiters consisting of 2 characters
  22068. var c2 = c + nextPreview();
  22069. if (DELIMITERS[c2]) {
  22070. tokenType = TOKENTYPE.DELIMITER;
  22071. token = c2;
  22072. next();
  22073. next();
  22074. return;
  22075. }
  22076. // check for delimiters consisting of 1 character
  22077. if (DELIMITERS[c]) {
  22078. tokenType = TOKENTYPE.DELIMITER;
  22079. token = c;
  22080. next();
  22081. return;
  22082. }
  22083. // check for an identifier (number or string)
  22084. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  22085. if (isAlphaNumeric(c) || c == '-') {
  22086. token += c;
  22087. next();
  22088. while (isAlphaNumeric(c)) {
  22089. token += c;
  22090. next();
  22091. }
  22092. if (token == 'false') {
  22093. token = false; // convert to boolean
  22094. }
  22095. else if (token == 'true') {
  22096. token = true; // convert to boolean
  22097. }
  22098. else if (!isNaN(Number(token))) {
  22099. token = Number(token); // convert to number
  22100. }
  22101. tokenType = TOKENTYPE.IDENTIFIER;
  22102. return;
  22103. }
  22104. // check for a string enclosed by double quotes
  22105. if (c == '"') {
  22106. next();
  22107. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  22108. token += c;
  22109. if (c == '"') { // skip the escape character
  22110. next();
  22111. }
  22112. next();
  22113. }
  22114. if (c != '"') {
  22115. throw newSyntaxError('End of string " expected');
  22116. }
  22117. next();
  22118. tokenType = TOKENTYPE.IDENTIFIER;
  22119. return;
  22120. }
  22121. // something unknown is found, wrong characters, a syntax error
  22122. tokenType = TOKENTYPE.UNKNOWN;
  22123. while (c != '') {
  22124. token += c;
  22125. next();
  22126. }
  22127. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  22128. }
  22129. /**
  22130. * Parse a graph.
  22131. * @returns {Object} graph
  22132. */
  22133. function parseGraph() {
  22134. var graph = {};
  22135. first();
  22136. getToken();
  22137. // optional strict keyword
  22138. if (token == 'strict') {
  22139. graph.strict = true;
  22140. getToken();
  22141. }
  22142. // graph or digraph keyword
  22143. if (token == 'graph' || token == 'digraph') {
  22144. graph.type = token;
  22145. getToken();
  22146. }
  22147. // optional graph id
  22148. if (tokenType == TOKENTYPE.IDENTIFIER) {
  22149. graph.id = token;
  22150. getToken();
  22151. }
  22152. // open angle bracket
  22153. if (token != '{') {
  22154. throw newSyntaxError('Angle bracket { expected');
  22155. }
  22156. getToken();
  22157. // statements
  22158. parseStatements(graph);
  22159. // close angle bracket
  22160. if (token != '}') {
  22161. throw newSyntaxError('Angle bracket } expected');
  22162. }
  22163. getToken();
  22164. // end of file
  22165. if (token !== '') {
  22166. throw newSyntaxError('End of file expected');
  22167. }
  22168. getToken();
  22169. // remove temporary default properties
  22170. delete graph.node;
  22171. delete graph.edge;
  22172. delete graph.graph;
  22173. return graph;
  22174. }
  22175. /**
  22176. * Parse a list with statements.
  22177. * @param {Object} graph
  22178. */
  22179. function parseStatements (graph) {
  22180. while (token !== '' && token != '}') {
  22181. parseStatement(graph);
  22182. if (token == ';') {
  22183. getToken();
  22184. }
  22185. }
  22186. }
  22187. /**
  22188. * Parse a single statement. Can be a an attribute statement, node
  22189. * statement, a series of node statements and edge statements, or a
  22190. * parameter.
  22191. * @param {Object} graph
  22192. */
  22193. function parseStatement(graph) {
  22194. // parse subgraph
  22195. var subgraph = parseSubgraph(graph);
  22196. if (subgraph) {
  22197. // edge statements
  22198. parseEdge(graph, subgraph);
  22199. return;
  22200. }
  22201. // parse an attribute statement
  22202. var attr = parseAttributeStatement(graph);
  22203. if (attr) {
  22204. return;
  22205. }
  22206. // parse node
  22207. if (tokenType != TOKENTYPE.IDENTIFIER) {
  22208. throw newSyntaxError('Identifier expected');
  22209. }
  22210. var id = token; // id can be a string or a number
  22211. getToken();
  22212. if (token == '=') {
  22213. // id statement
  22214. getToken();
  22215. if (tokenType != TOKENTYPE.IDENTIFIER) {
  22216. throw newSyntaxError('Identifier expected');
  22217. }
  22218. graph[id] = token;
  22219. getToken();
  22220. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  22221. }
  22222. else {
  22223. parseNodeStatement(graph, id);
  22224. }
  22225. }
  22226. /**
  22227. * Parse a subgraph
  22228. * @param {Object} graph parent graph object
  22229. * @return {Object | null} subgraph
  22230. */
  22231. function parseSubgraph (graph) {
  22232. var subgraph = null;
  22233. // optional subgraph keyword
  22234. if (token == 'subgraph') {
  22235. subgraph = {};
  22236. subgraph.type = 'subgraph';
  22237. getToken();
  22238. // optional graph id
  22239. if (tokenType == TOKENTYPE.IDENTIFIER) {
  22240. subgraph.id = token;
  22241. getToken();
  22242. }
  22243. }
  22244. // open angle bracket
  22245. if (token == '{') {
  22246. getToken();
  22247. if (!subgraph) {
  22248. subgraph = {};
  22249. }
  22250. subgraph.parent = graph;
  22251. subgraph.node = graph.node;
  22252. subgraph.edge = graph.edge;
  22253. subgraph.graph = graph.graph;
  22254. // statements
  22255. parseStatements(subgraph);
  22256. // close angle bracket
  22257. if (token != '}') {
  22258. throw newSyntaxError('Angle bracket } expected');
  22259. }
  22260. getToken();
  22261. // remove temporary default properties
  22262. delete subgraph.node;
  22263. delete subgraph.edge;
  22264. delete subgraph.graph;
  22265. delete subgraph.parent;
  22266. // register at the parent graph
  22267. if (!graph.subgraphs) {
  22268. graph.subgraphs = [];
  22269. }
  22270. graph.subgraphs.push(subgraph);
  22271. }
  22272. return subgraph;
  22273. }
  22274. /**
  22275. * parse an attribute statement like "node [shape=circle fontSize=16]".
  22276. * Available keywords are 'node', 'edge', 'graph'.
  22277. * The previous list with default attributes will be replaced
  22278. * @param {Object} graph
  22279. * @returns {String | null} keyword Returns the name of the parsed attribute
  22280. * (node, edge, graph), or null if nothing
  22281. * is parsed.
  22282. */
  22283. function parseAttributeStatement (graph) {
  22284. // attribute statements
  22285. if (token == 'node') {
  22286. getToken();
  22287. // node attributes
  22288. graph.node = parseAttributeList();
  22289. return 'node';
  22290. }
  22291. else if (token == 'edge') {
  22292. getToken();
  22293. // edge attributes
  22294. graph.edge = parseAttributeList();
  22295. return 'edge';
  22296. }
  22297. else if (token == 'graph') {
  22298. getToken();
  22299. // graph attributes
  22300. graph.graph = parseAttributeList();
  22301. return 'graph';
  22302. }
  22303. return null;
  22304. }
  22305. /**
  22306. * parse a node statement
  22307. * @param {Object} graph
  22308. * @param {String | Number} id
  22309. */
  22310. function parseNodeStatement(graph, id) {
  22311. // node statement
  22312. var node = {
  22313. id: id
  22314. };
  22315. var attr = parseAttributeList();
  22316. if (attr) {
  22317. node.attr = attr;
  22318. }
  22319. addNode(graph, node);
  22320. // edge statements
  22321. parseEdge(graph, id);
  22322. }
  22323. /**
  22324. * Parse an edge or a series of edges
  22325. * @param {Object} graph
  22326. * @param {String | Number} from Id of the from node
  22327. */
  22328. function parseEdge(graph, from) {
  22329. while (token == '->' || token == '--') {
  22330. var to;
  22331. var type = token;
  22332. getToken();
  22333. var subgraph = parseSubgraph(graph);
  22334. if (subgraph) {
  22335. to = subgraph;
  22336. }
  22337. else {
  22338. if (tokenType != TOKENTYPE.IDENTIFIER) {
  22339. throw newSyntaxError('Identifier or subgraph expected');
  22340. }
  22341. to = token;
  22342. addNode(graph, {
  22343. id: to
  22344. });
  22345. getToken();
  22346. }
  22347. // parse edge attributes
  22348. var attr = parseAttributeList();
  22349. // create edge
  22350. var edge = createEdge(graph, from, to, type, attr);
  22351. addEdge(graph, edge);
  22352. from = to;
  22353. }
  22354. }
  22355. /**
  22356. * Parse a set with attributes,
  22357. * for example [label="1.000", shape=solid]
  22358. * @return {Object | null} attr
  22359. */
  22360. function parseAttributeList() {
  22361. var attr = null;
  22362. while (token == '[') {
  22363. getToken();
  22364. attr = {};
  22365. while (token !== '' && token != ']') {
  22366. if (tokenType != TOKENTYPE.IDENTIFIER) {
  22367. throw newSyntaxError('Attribute name expected');
  22368. }
  22369. var name = token;
  22370. getToken();
  22371. if (token != '=') {
  22372. throw newSyntaxError('Equal sign = expected');
  22373. }
  22374. getToken();
  22375. if (tokenType != TOKENTYPE.IDENTIFIER) {
  22376. throw newSyntaxError('Attribute value expected');
  22377. }
  22378. var value = token;
  22379. setValue(attr, name, value); // name can be a path
  22380. getToken();
  22381. if (token ==',') {
  22382. getToken();
  22383. }
  22384. }
  22385. if (token != ']') {
  22386. throw newSyntaxError('Bracket ] expected');
  22387. }
  22388. getToken();
  22389. }
  22390. return attr;
  22391. }
  22392. /**
  22393. * Create a syntax error with extra information on current token and index.
  22394. * @param {String} message
  22395. * @returns {SyntaxError} err
  22396. */
  22397. function newSyntaxError(message) {
  22398. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  22399. }
  22400. /**
  22401. * Chop off text after a maximum length
  22402. * @param {String} text
  22403. * @param {Number} maxLength
  22404. * @returns {String}
  22405. */
  22406. function chop (text, maxLength) {
  22407. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  22408. }
  22409. /**
  22410. * Execute a function fn for each pair of elements in two arrays
  22411. * @param {Array | *} array1
  22412. * @param {Array | *} array2
  22413. * @param {function} fn
  22414. */
  22415. function forEach2(array1, array2, fn) {
  22416. if (Array.isArray(array1)) {
  22417. array1.forEach(function (elem1) {
  22418. if (Array.isArray(array2)) {
  22419. array2.forEach(function (elem2) {
  22420. fn(elem1, elem2);
  22421. });
  22422. }
  22423. else {
  22424. fn(elem1, array2);
  22425. }
  22426. });
  22427. }
  22428. else {
  22429. if (Array.isArray(array2)) {
  22430. array2.forEach(function (elem2) {
  22431. fn(array1, elem2);
  22432. });
  22433. }
  22434. else {
  22435. fn(array1, array2);
  22436. }
  22437. }
  22438. }
  22439. /**
  22440. * Convert a string containing a graph in DOT language into a map containing
  22441. * with nodes and edges in the format of graph.
  22442. * @param {String} data Text containing a graph in DOT-notation
  22443. * @return {Object} graphData
  22444. */
  22445. function DOTToGraph (data) {
  22446. // parse the DOT file
  22447. var dotData = parseDOT(data);
  22448. var graphData = {
  22449. nodes: [],
  22450. edges: [],
  22451. options: {}
  22452. };
  22453. // copy the nodes
  22454. if (dotData.nodes) {
  22455. dotData.nodes.forEach(function (dotNode) {
  22456. var graphNode = {
  22457. id: dotNode.id,
  22458. label: String(dotNode.label || dotNode.id)
  22459. };
  22460. merge(graphNode, dotNode.attr);
  22461. if (graphNode.image) {
  22462. graphNode.shape = 'image';
  22463. }
  22464. graphData.nodes.push(graphNode);
  22465. });
  22466. }
  22467. // copy the edges
  22468. if (dotData.edges) {
  22469. /**
  22470. * Convert an edge in DOT format to an edge with VisGraph format
  22471. * @param {Object} dotEdge
  22472. * @returns {Object} graphEdge
  22473. */
  22474. var convertEdge = function (dotEdge) {
  22475. var graphEdge = {
  22476. from: dotEdge.from,
  22477. to: dotEdge.to
  22478. };
  22479. merge(graphEdge, dotEdge.attr);
  22480. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  22481. return graphEdge;
  22482. }
  22483. dotData.edges.forEach(function (dotEdge) {
  22484. var from, to;
  22485. if (dotEdge.from instanceof Object) {
  22486. from = dotEdge.from.nodes;
  22487. }
  22488. else {
  22489. from = {
  22490. id: dotEdge.from
  22491. }
  22492. }
  22493. if (dotEdge.to instanceof Object) {
  22494. to = dotEdge.to.nodes;
  22495. }
  22496. else {
  22497. to = {
  22498. id: dotEdge.to
  22499. }
  22500. }
  22501. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  22502. dotEdge.from.edges.forEach(function (subEdge) {
  22503. var graphEdge = convertEdge(subEdge);
  22504. graphData.edges.push(graphEdge);
  22505. });
  22506. }
  22507. forEach2(from, to, function (from, to) {
  22508. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  22509. var graphEdge = convertEdge(subEdge);
  22510. graphData.edges.push(graphEdge);
  22511. });
  22512. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  22513. dotEdge.to.edges.forEach(function (subEdge) {
  22514. var graphEdge = convertEdge(subEdge);
  22515. graphData.edges.push(graphEdge);
  22516. });
  22517. }
  22518. });
  22519. }
  22520. // copy the options
  22521. if (dotData.attr) {
  22522. graphData.options = dotData.attr;
  22523. }
  22524. return graphData;
  22525. }
  22526. // exports
  22527. exports.parseDOT = parseDOT;
  22528. exports.DOTToGraph = DOTToGraph;
  22529. /***/ },
  22530. /* 53 */
  22531. /***/ function(module, exports, __webpack_require__) {
  22532. function parseGephi(gephiJSON, options) {
  22533. var edges = [];
  22534. var nodes = [];
  22535. this.options = {
  22536. edges: {
  22537. inheritColor: true
  22538. },
  22539. nodes: {
  22540. allowedToMove: false,
  22541. parseColor: false
  22542. }
  22543. };
  22544. if (options !== undefined) {
  22545. this.options.nodes['allowedToMove'] = options.allowedToMove | false;
  22546. this.options.nodes['parseColor'] = options.parseColor | false;
  22547. this.options.edges['inheritColor'] = options.inheritColor | true;
  22548. }
  22549. var gEdges = gephiJSON.edges;
  22550. var gNodes = gephiJSON.nodes;
  22551. for (var i = 0; i < gEdges.length; i++) {
  22552. var edge = {};
  22553. var gEdge = gEdges[i];
  22554. edge['id'] = gEdge.id;
  22555. edge['from'] = gEdge.source;
  22556. edge['to'] = gEdge.target;
  22557. edge['attributes'] = gEdge.attributes;
  22558. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  22559. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  22560. edge['color'] = gEdge.color;
  22561. edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
  22562. edges.push(edge);
  22563. }
  22564. for (var i = 0; i < gNodes.length; i++) {
  22565. var node = {};
  22566. var gNode = gNodes[i];
  22567. node['id'] = gNode.id;
  22568. node['attributes'] = gNode.attributes;
  22569. node['x'] = gNode.x;
  22570. node['y'] = gNode.y;
  22571. node['label'] = gNode.label;
  22572. if (this.options.nodes.parseColor == true) {
  22573. node['color'] = gNode.color;
  22574. }
  22575. else {
  22576. node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
  22577. }
  22578. node['radius'] = gNode.size;
  22579. node['allowedToMoveX'] = this.options.nodes.allowedToMove;
  22580. node['allowedToMoveY'] = this.options.nodes.allowedToMove;
  22581. nodes.push(node);
  22582. }
  22583. return {nodes:nodes, edges:edges};
  22584. }
  22585. exports.parseGephi = parseGephi;
  22586. /***/ },
  22587. /* 54 */
  22588. /***/ function(module, exports, __webpack_require__) {
  22589. var util = __webpack_require__(1);
  22590. /**
  22591. * @class Groups
  22592. * This class can store groups and properties specific for groups.
  22593. */
  22594. function Groups() {
  22595. this.clear();
  22596. this.defaultIndex = 0;
  22597. }
  22598. /**
  22599. * default constants for group colors
  22600. */
  22601. Groups.DEFAULT = [
  22602. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  22603. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  22604. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  22605. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green
  22606. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  22607. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  22608. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange
  22609. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  22610. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  22611. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  22612. ];
  22613. /**
  22614. * Clear all groups
  22615. */
  22616. Groups.prototype.clear = function () {
  22617. this.groups = {};
  22618. this.groups.length = function()
  22619. {
  22620. var i = 0;
  22621. for ( var p in this ) {
  22622. if (this.hasOwnProperty(p)) {
  22623. i++;
  22624. }
  22625. }
  22626. return i;
  22627. }
  22628. };
  22629. /**
  22630. * get group properties of a groupname. If groupname is not found, a new group
  22631. * is added.
  22632. * @param {*} groupname Can be a number, string, Date, etc.
  22633. * @return {Object} group The created group, containing all group properties
  22634. */
  22635. Groups.prototype.get = function (groupname) {
  22636. var group = this.groups[groupname];
  22637. if (group == undefined) {
  22638. // create new group
  22639. var index = this.defaultIndex % Groups.DEFAULT.length;
  22640. this.defaultIndex++;
  22641. group = {};
  22642. group.color = Groups.DEFAULT[index];
  22643. this.groups[groupname] = group;
  22644. }
  22645. return group;
  22646. };
  22647. /**
  22648. * Add a custom group style
  22649. * @param {String} groupname
  22650. * @param {Object} style An object containing borderColor,
  22651. * backgroundColor, etc.
  22652. * @return {Object} group The created group object
  22653. */
  22654. Groups.prototype.add = function (groupname, style) {
  22655. this.groups[groupname] = style;
  22656. if (style.color) {
  22657. style.color = util.parseColor(style.color);
  22658. }
  22659. return style;
  22660. };
  22661. module.exports = Groups;
  22662. /***/ },
  22663. /* 55 */
  22664. /***/ function(module, exports, __webpack_require__) {
  22665. /**
  22666. * @class Images
  22667. * This class loads images and keeps them stored.
  22668. */
  22669. function Images() {
  22670. this.images = {};
  22671. this.callback = undefined;
  22672. }
  22673. /**
  22674. * Set an onload callback function. This will be called each time an image
  22675. * is loaded
  22676. * @param {function} callback
  22677. */
  22678. Images.prototype.setOnloadCallback = function(callback) {
  22679. this.callback = callback;
  22680. };
  22681. /**
  22682. *
  22683. * @param {string} url Url of the image
  22684. * @param {string} url Url of an image to use if the url image is not found
  22685. * @return {Image} img The image object
  22686. */
  22687. Images.prototype.load = function(url, brokenUrl) {
  22688. var img = this.images[url];
  22689. if (img == undefined) {
  22690. // create the image
  22691. var images = this;
  22692. img = new Image();
  22693. this.images[url] = img;
  22694. img.onload = function() {
  22695. if (images.callback) {
  22696. images.callback(this);
  22697. }
  22698. };
  22699. img.onerror = function () {
  22700. this.src = brokenUrl;
  22701. if (images.callback) {
  22702. images.callback(this);
  22703. }
  22704. };
  22705. img.src = url;
  22706. }
  22707. return img;
  22708. };
  22709. module.exports = Images;
  22710. /***/ },
  22711. /* 56 */
  22712. /***/ function(module, exports, __webpack_require__) {
  22713. var util = __webpack_require__(1);
  22714. /**
  22715. * @class Node
  22716. * A node. A node can be connected to other nodes via one or multiple edges.
  22717. * @param {object} properties An object containing properties for the node. All
  22718. * properties are optional, except for the id.
  22719. * {number} id Id of the node. Required
  22720. * {string} label Text label for the node
  22721. * {number} x Horizontal position of the node
  22722. * {number} y Vertical position of the node
  22723. * {string} shape Node shape, available:
  22724. * "database", "circle", "ellipse",
  22725. * "box", "image", "text", "dot",
  22726. * "star", "triangle", "triangleDown",
  22727. * "square"
  22728. * {string} image An image url
  22729. * {string} title An title text, can be HTML
  22730. * {anytype} group A group name or number
  22731. * @param {Network.Images} imagelist A list with images. Only needed
  22732. * when the node has an image
  22733. * @param {Network.Groups} grouplist A list with groups. Needed for
  22734. * retrieving group properties
  22735. * @param {Object} constants An object with default values for
  22736. * example for the color
  22737. *
  22738. */
  22739. function Node(properties, imagelist, grouplist, networkConstants) {
  22740. var constants = util.selectiveBridgeObject(['nodes'],networkConstants);
  22741. this.options = constants.nodes;
  22742. this.selected = false;
  22743. this.hover = false;
  22744. this.edges = []; // all edges connected to this node
  22745. this.dynamicEdges = [];
  22746. this.reroutedEdges = {};
  22747. this.fontDrawThreshold = 3;
  22748. // set defaults for the properties
  22749. this.id = undefined;
  22750. this.x = null;
  22751. this.y = null;
  22752. this.allowedToMoveX = false;
  22753. this.allowedToMoveY = false;
  22754. this.xFixed = false;
  22755. this.yFixed = false;
  22756. this.horizontalAlignLeft = true; // these are for the navigation controls
  22757. this.verticalAlignTop = true; // these are for the navigation controls
  22758. this.baseRadiusValue = networkConstants.nodes.radius;
  22759. this.radiusFixed = false;
  22760. this.level = -1;
  22761. this.preassignedLevel = false;
  22762. this.hierarchyEnumerated = false;
  22763. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  22764. this.imagelist = imagelist;
  22765. this.grouplist = grouplist;
  22766. // physics properties
  22767. this.fx = 0.0; // external force x
  22768. this.fy = 0.0; // external force y
  22769. this.vx = 0.0; // velocity x
  22770. this.vy = 0.0; // velocity y
  22771. this.damping = networkConstants.physics.damping; // written every time gravity is calculated
  22772. this.fixedData = {x:null,y:null};
  22773. this.setProperties(properties, constants);
  22774. // creating the variables for clustering
  22775. this.resetCluster();
  22776. this.dynamicEdgesLength = 0;
  22777. this.clusterSession = 0;
  22778. this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width;
  22779. this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height;
  22780. this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius;
  22781. this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements;
  22782. this.growthIndicator = 0;
  22783. // variables to tell the node about the network.
  22784. this.networkScaleInv = 1;
  22785. this.networkScale = 1;
  22786. this.canvasTopLeft = {"x": -300, "y": -300};
  22787. this.canvasBottomRight = {"x": 300, "y": 300};
  22788. this.parentEdgeId = null;
  22789. }
  22790. /**
  22791. * (re)setting the clustering variables and objects
  22792. */
  22793. Node.prototype.resetCluster = function() {
  22794. // clustering variables
  22795. this.formationScale = undefined; // this is used to determine when to open the cluster
  22796. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  22797. this.containedNodes = {};
  22798. this.containedEdges = {};
  22799. this.clusterSessions = [];
  22800. };
  22801. /**
  22802. * Attach a edge to the node
  22803. * @param {Edge} edge
  22804. */
  22805. Node.prototype.attachEdge = function(edge) {
  22806. if (this.edges.indexOf(edge) == -1) {
  22807. this.edges.push(edge);
  22808. }
  22809. if (this.dynamicEdges.indexOf(edge) == -1) {
  22810. this.dynamicEdges.push(edge);
  22811. }
  22812. this.dynamicEdgesLength = this.dynamicEdges.length;
  22813. };
  22814. /**
  22815. * Detach a edge from the node
  22816. * @param {Edge} edge
  22817. */
  22818. Node.prototype.detachEdge = function(edge) {
  22819. var index = this.edges.indexOf(edge);
  22820. if (index != -1) {
  22821. this.edges.splice(index, 1);
  22822. }
  22823. index = this.dynamicEdges.indexOf(edge);
  22824. if (index != -1) {
  22825. this.dynamicEdges.splice(index, 1);
  22826. }
  22827. this.dynamicEdgesLength = this.dynamicEdges.length;
  22828. };
  22829. /**
  22830. * Set or overwrite properties for the node
  22831. * @param {Object} properties an object with properties
  22832. * @param {Object} constants and object with default, global properties
  22833. */
  22834. Node.prototype.setProperties = function(properties, constants) {
  22835. if (!properties) {
  22836. return;
  22837. }
  22838. var fields = ['borderWidth','borderWidthSelected','shape','image','brokenImage','radius','fontColor',
  22839. 'fontSize','fontFace','fontFill','group','mass'
  22840. ];
  22841. util.selectiveDeepExtend(fields, this.options, properties);
  22842. // basic properties
  22843. if (properties.id !== undefined) {this.id = properties.id;}
  22844. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  22845. if (properties.title !== undefined) {this.title = properties.title;}
  22846. if (properties.x !== undefined) {this.x = properties.x;}
  22847. if (properties.y !== undefined) {this.y = properties.y;}
  22848. if (properties.value !== undefined) {this.value = properties.value;}
  22849. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  22850. // navigation controls properties
  22851. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  22852. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  22853. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  22854. if (this.id === undefined) {
  22855. throw "Node must have an id";
  22856. }
  22857. // copy group properties
  22858. if (typeof this.options.group === 'number' || (typeof this.options.group === 'string' && this.options.group != '')) {
  22859. var groupObj = this.grouplist.get(this.options.group);
  22860. for (var prop in groupObj) {
  22861. if (groupObj.hasOwnProperty(prop)) {
  22862. this.options[prop] = groupObj[prop];
  22863. }
  22864. }
  22865. }
  22866. // individual shape properties
  22867. if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;}
  22868. if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);}
  22869. if (this.options.image!== undefined && this.options.image!= "") {
  22870. if (this.imagelist) {
  22871. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage);
  22872. }
  22873. else {
  22874. throw "No imagelist provided";
  22875. }
  22876. }
  22877. if (properties.allowedToMoveX !== undefined) {
  22878. this.xFixed = !properties.allowedToMoveX;
  22879. this.allowedToMoveX = properties.allowedToMoveX;
  22880. }
  22881. else if (properties.x !== undefined && this.allowedToMoveX == false) {
  22882. this.xFixed = true;
  22883. }
  22884. if (properties.allowedToMoveY !== undefined) {
  22885. this.yFixed = !properties.allowedToMoveY;
  22886. this.allowedToMoveY = properties.allowedToMoveY;
  22887. }
  22888. else if (properties.y !== undefined && this.allowedToMoveY == false) {
  22889. this.yFixed = true;
  22890. }
  22891. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  22892. if (this.options.shape == 'image') {
  22893. this.options.radiusMin = constants.nodes.widthMin;
  22894. this.options.radiusMax = constants.nodes.widthMax;
  22895. }
  22896. // choose draw method depending on the shape
  22897. switch (this.options.shape) {
  22898. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  22899. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  22900. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  22901. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  22902. // TODO: add diamond shape
  22903. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  22904. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  22905. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  22906. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  22907. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  22908. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  22909. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  22910. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  22911. }
  22912. // reset the size of the node, this can be changed
  22913. this._reset();
  22914. };
  22915. /**
  22916. * select this node
  22917. */
  22918. Node.prototype.select = function() {
  22919. this.selected = true;
  22920. this._reset();
  22921. };
  22922. /**
  22923. * unselect this node
  22924. */
  22925. Node.prototype.unselect = function() {
  22926. this.selected = false;
  22927. this._reset();
  22928. };
  22929. /**
  22930. * Reset the calculated size of the node, forces it to recalculate its size
  22931. */
  22932. Node.prototype.clearSizeCache = function() {
  22933. this._reset();
  22934. };
  22935. /**
  22936. * Reset the calculated size of the node, forces it to recalculate its size
  22937. * @private
  22938. */
  22939. Node.prototype._reset = function() {
  22940. this.width = undefined;
  22941. this.height = undefined;
  22942. };
  22943. /**
  22944. * get the title of this node.
  22945. * @return {string} title The title of the node, or undefined when no title
  22946. * has been set.
  22947. */
  22948. Node.prototype.getTitle = function() {
  22949. return typeof this.title === "function" ? this.title() : this.title;
  22950. };
  22951. /**
  22952. * Calculate the distance to the border of the Node
  22953. * @param {CanvasRenderingContext2D} ctx
  22954. * @param {Number} angle Angle in radians
  22955. * @returns {number} distance Distance to the border in pixels
  22956. */
  22957. Node.prototype.distanceToBorder = function (ctx, angle) {
  22958. var borderWidth = 1;
  22959. if (!this.width) {
  22960. this.resize(ctx);
  22961. }
  22962. switch (this.options.shape) {
  22963. case 'circle':
  22964. case 'dot':
  22965. return this.options.radius+ borderWidth;
  22966. case 'ellipse':
  22967. var a = this.width / 2;
  22968. var b = this.height / 2;
  22969. var w = (Math.sin(angle) * a);
  22970. var h = (Math.cos(angle) * b);
  22971. return a * b / Math.sqrt(w * w + h * h);
  22972. // TODO: implement distanceToBorder for database
  22973. // TODO: implement distanceToBorder for triangle
  22974. // TODO: implement distanceToBorder for triangleDown
  22975. case 'box':
  22976. case 'image':
  22977. case 'text':
  22978. default:
  22979. if (this.width) {
  22980. return Math.min(
  22981. Math.abs(this.width / 2 / Math.cos(angle)),
  22982. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  22983. // TODO: reckon with border radius too in case of box
  22984. }
  22985. else {
  22986. return 0;
  22987. }
  22988. }
  22989. // TODO: implement calculation of distance to border for all shapes
  22990. };
  22991. /**
  22992. * Set forces acting on the node
  22993. * @param {number} fx Force in horizontal direction
  22994. * @param {number} fy Force in vertical direction
  22995. */
  22996. Node.prototype._setForce = function(fx, fy) {
  22997. this.fx = fx;
  22998. this.fy = fy;
  22999. };
  23000. /**
  23001. * Add forces acting on the node
  23002. * @param {number} fx Force in horizontal direction
  23003. * @param {number} fy Force in vertical direction
  23004. * @private
  23005. */
  23006. Node.prototype._addForce = function(fx, fy) {
  23007. this.fx += fx;
  23008. this.fy += fy;
  23009. };
  23010. /**
  23011. * Perform one discrete step for the node
  23012. * @param {number} interval Time interval in seconds
  23013. */
  23014. Node.prototype.discreteStep = function(interval) {
  23015. if (!this.xFixed) {
  23016. var dx = this.damping * this.vx; // damping force
  23017. var ax = (this.fx - dx) / this.options.mass; // acceleration
  23018. this.vx += ax * interval; // velocity
  23019. this.x += this.vx * interval; // position
  23020. }
  23021. else {
  23022. this.fx = 0;
  23023. this.vx = 0;
  23024. }
  23025. if (!this.yFixed) {
  23026. var dy = this.damping * this.vy; // damping force
  23027. var ay = (this.fy - dy) / this.options.mass; // acceleration
  23028. this.vy += ay * interval; // velocity
  23029. this.y += this.vy * interval; // position
  23030. }
  23031. else {
  23032. this.fy = 0;
  23033. this.vy = 0;
  23034. }
  23035. };
  23036. /**
  23037. * Perform one discrete step for the node
  23038. * @param {number} interval Time interval in seconds
  23039. * @param {number} maxVelocity The speed limit imposed on the velocity
  23040. */
  23041. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  23042. if (!this.xFixed) {
  23043. var dx = this.damping * this.vx; // damping force
  23044. var ax = (this.fx - dx) / this.options.mass; // acceleration
  23045. this.vx += ax * interval; // velocity
  23046. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  23047. this.x += this.vx * interval; // position
  23048. }
  23049. else {
  23050. this.fx = 0;
  23051. this.vx = 0;
  23052. }
  23053. if (!this.yFixed) {
  23054. var dy = this.damping * this.vy; // damping force
  23055. var ay = (this.fy - dy) / this.options.mass; // acceleration
  23056. this.vy += ay * interval; // velocity
  23057. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  23058. this.y += this.vy * interval; // position
  23059. }
  23060. else {
  23061. this.fy = 0;
  23062. this.vy = 0;
  23063. }
  23064. };
  23065. /**
  23066. * Check if this node has a fixed x and y position
  23067. * @return {boolean} true if fixed, false if not
  23068. */
  23069. Node.prototype.isFixed = function() {
  23070. return (this.xFixed && this.yFixed);
  23071. };
  23072. /**
  23073. * Check if this node is moving
  23074. * @param {number} vmin the minimum velocity considered as "moving"
  23075. * @return {boolean} true if moving, false if it has no velocity
  23076. */
  23077. Node.prototype.isMoving = function(vmin) {
  23078. var velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2));
  23079. // this.velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2))
  23080. return (velocity > vmin);
  23081. };
  23082. /**
  23083. * check if this node is selecte
  23084. * @return {boolean} selected True if node is selected, else false
  23085. */
  23086. Node.prototype.isSelected = function() {
  23087. return this.selected;
  23088. };
  23089. /**
  23090. * Retrieve the value of the node. Can be undefined
  23091. * @return {Number} value
  23092. */
  23093. Node.prototype.getValue = function() {
  23094. return this.value;
  23095. };
  23096. /**
  23097. * Calculate the distance from the nodes location to the given location (x,y)
  23098. * @param {Number} x
  23099. * @param {Number} y
  23100. * @return {Number} value
  23101. */
  23102. Node.prototype.getDistance = function(x, y) {
  23103. var dx = this.x - x,
  23104. dy = this.y - y;
  23105. return Math.sqrt(dx * dx + dy * dy);
  23106. };
  23107. /**
  23108. * Adjust the value range of the node. The node will adjust it's radius
  23109. * based on its value.
  23110. * @param {Number} min
  23111. * @param {Number} max
  23112. */
  23113. Node.prototype.setValueRange = function(min, max) {
  23114. if (!this.radiusFixed && this.value !== undefined) {
  23115. if (max == min) {
  23116. this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2;
  23117. }
  23118. else {
  23119. var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min);
  23120. this.options.radius= (this.value - min) * scale + this.options.radiusMin;
  23121. }
  23122. }
  23123. this.baseRadiusValue = this.options.radius;
  23124. };
  23125. /**
  23126. * Draw this node in the given canvas
  23127. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23128. * @param {CanvasRenderingContext2D} ctx
  23129. */
  23130. Node.prototype.draw = function(ctx) {
  23131. throw "Draw method not initialized for node";
  23132. };
  23133. /**
  23134. * Recalculate the size of this node in the given canvas
  23135. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23136. * @param {CanvasRenderingContext2D} ctx
  23137. */
  23138. Node.prototype.resize = function(ctx) {
  23139. throw "Resize method not initialized for node";
  23140. };
  23141. /**
  23142. * Check if this object is overlapping with the provided object
  23143. * @param {Object} obj an object with parameters left, top, right, bottom
  23144. * @return {boolean} True if location is located on node
  23145. */
  23146. Node.prototype.isOverlappingWith = function(obj) {
  23147. return (this.left < obj.right &&
  23148. this.left + this.width > obj.left &&
  23149. this.top < obj.bottom &&
  23150. this.top + this.height > obj.top);
  23151. };
  23152. Node.prototype._resizeImage = function (ctx) {
  23153. // TODO: pre calculate the image size
  23154. if (!this.width || !this.height) { // undefined or 0
  23155. var width, height;
  23156. if (this.value) {
  23157. this.options.radius= this.baseRadiusValue;
  23158. var scale = this.imageObj.height / this.imageObj.width;
  23159. if (scale !== undefined) {
  23160. width = this.options.radius|| this.imageObj.width;
  23161. height = this.options.radius* scale || this.imageObj.height;
  23162. }
  23163. else {
  23164. width = 0;
  23165. height = 0;
  23166. }
  23167. }
  23168. else {
  23169. width = this.imageObj.width;
  23170. height = this.imageObj.height;
  23171. }
  23172. this.width = width;
  23173. this.height = height;
  23174. this.growthIndicator = 0;
  23175. if (this.width > 0 && this.height > 0) {
  23176. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23177. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23178. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23179. this.growthIndicator = this.width - width;
  23180. }
  23181. }
  23182. };
  23183. Node.prototype._drawImage = function (ctx) {
  23184. this._resizeImage(ctx);
  23185. this.left = this.x - this.width / 2;
  23186. this.top = this.y - this.height / 2;
  23187. var yLabel;
  23188. if (this.imageObj.width != 0 ) {
  23189. // draw the shade
  23190. if (this.clusterSize > 1) {
  23191. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  23192. lineWidth *= this.networkScaleInv;
  23193. lineWidth = Math.min(0.2 * this.width,lineWidth);
  23194. ctx.globalAlpha = 0.5;
  23195. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  23196. }
  23197. // draw the image
  23198. ctx.globalAlpha = 1.0;
  23199. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  23200. yLabel = this.y + this.height / 2;
  23201. }
  23202. else {
  23203. // image still loading... just draw the label for now
  23204. yLabel = this.y;
  23205. }
  23206. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  23207. };
  23208. Node.prototype._resizeBox = function (ctx) {
  23209. if (!this.width) {
  23210. var margin = 5;
  23211. var textSize = this.getTextSize(ctx);
  23212. this.width = textSize.width + 2 * margin;
  23213. this.height = textSize.height + 2 * margin;
  23214. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  23215. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  23216. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  23217. // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  23218. }
  23219. };
  23220. Node.prototype._drawBox = function (ctx) {
  23221. this._resizeBox(ctx);
  23222. this.left = this.x - this.width / 2;
  23223. this.top = this.y - this.height / 2;
  23224. var clusterLineWidth = 2.5;
  23225. var borderWidth = this.options.borderWidth;
  23226. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23227. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23228. // draw the outer border
  23229. if (this.clusterSize > 1) {
  23230. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23231. ctx.lineWidth *= this.networkScaleInv;
  23232. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23233. 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);
  23234. ctx.stroke();
  23235. }
  23236. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23237. ctx.lineWidth *= this.networkScaleInv;
  23238. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23239. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.options.color.background;
  23240. ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius);
  23241. ctx.fill();
  23242. ctx.stroke();
  23243. this._label(ctx, this.label, this.x, this.y);
  23244. };
  23245. Node.prototype._resizeDatabase = function (ctx) {
  23246. if (!this.width) {
  23247. var margin = 5;
  23248. var textSize = this.getTextSize(ctx);
  23249. var size = textSize.width + 2 * margin;
  23250. this.width = size;
  23251. this.height = size;
  23252. // scaling used for clustering
  23253. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23254. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23255. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23256. this.growthIndicator = this.width - size;
  23257. }
  23258. };
  23259. Node.prototype._drawDatabase = function (ctx) {
  23260. this._resizeDatabase(ctx);
  23261. this.left = this.x - this.width / 2;
  23262. this.top = this.y - this.height / 2;
  23263. var clusterLineWidth = 2.5;
  23264. var borderWidth = this.options.borderWidth;
  23265. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23266. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23267. // draw the outer border
  23268. if (this.clusterSize > 1) {
  23269. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23270. ctx.lineWidth *= this.networkScaleInv;
  23271. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23272. 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);
  23273. ctx.stroke();
  23274. }
  23275. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23276. ctx.lineWidth *= this.networkScaleInv;
  23277. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23278. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23279. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  23280. ctx.fill();
  23281. ctx.stroke();
  23282. this._label(ctx, this.label, this.x, this.y);
  23283. };
  23284. Node.prototype._resizeCircle = function (ctx) {
  23285. if (!this.width) {
  23286. var margin = 5;
  23287. var textSize = this.getTextSize(ctx);
  23288. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  23289. this.options.radius = diameter / 2;
  23290. this.width = diameter;
  23291. this.height = diameter;
  23292. // scaling used for clustering
  23293. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  23294. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  23295. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  23296. this.growthIndicator = this.options.radius- 0.5*diameter;
  23297. }
  23298. };
  23299. Node.prototype._drawCircle = function (ctx) {
  23300. this._resizeCircle(ctx);
  23301. this.left = this.x - this.width / 2;
  23302. this.top = this.y - this.height / 2;
  23303. var clusterLineWidth = 2.5;
  23304. var borderWidth = this.options.borderWidth;
  23305. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23306. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23307. // draw the outer border
  23308. if (this.clusterSize > 1) {
  23309. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23310. ctx.lineWidth *= this.networkScaleInv;
  23311. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23312. ctx.circle(this.x, this.y, this.options.radius+2*ctx.lineWidth);
  23313. ctx.stroke();
  23314. }
  23315. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23316. ctx.lineWidth *= this.networkScaleInv;
  23317. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23318. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23319. ctx.circle(this.x, this.y, this.options.radius);
  23320. ctx.fill();
  23321. ctx.stroke();
  23322. this._label(ctx, this.label, this.x, this.y);
  23323. };
  23324. Node.prototype._resizeEllipse = function (ctx) {
  23325. if (!this.width) {
  23326. var textSize = this.getTextSize(ctx);
  23327. this.width = textSize.width * 1.5;
  23328. this.height = textSize.height * 2;
  23329. if (this.width < this.height) {
  23330. this.width = this.height;
  23331. }
  23332. var defaultSize = this.width;
  23333. // scaling used for clustering
  23334. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23335. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23336. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23337. this.growthIndicator = this.width - defaultSize;
  23338. }
  23339. };
  23340. Node.prototype._drawEllipse = function (ctx) {
  23341. this._resizeEllipse(ctx);
  23342. this.left = this.x - this.width / 2;
  23343. this.top = this.y - this.height / 2;
  23344. var clusterLineWidth = 2.5;
  23345. var borderWidth = this.options.borderWidth;
  23346. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23347. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23348. // draw the outer border
  23349. if (this.clusterSize > 1) {
  23350. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23351. ctx.lineWidth *= this.networkScaleInv;
  23352. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23353. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  23354. ctx.stroke();
  23355. }
  23356. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23357. ctx.lineWidth *= this.networkScaleInv;
  23358. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23359. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23360. ctx.ellipse(this.left, this.top, this.width, this.height);
  23361. ctx.fill();
  23362. ctx.stroke();
  23363. this._label(ctx, this.label, this.x, this.y);
  23364. };
  23365. Node.prototype._drawDot = function (ctx) {
  23366. this._drawShape(ctx, 'circle');
  23367. };
  23368. Node.prototype._drawTriangle = function (ctx) {
  23369. this._drawShape(ctx, 'triangle');
  23370. };
  23371. Node.prototype._drawTriangleDown = function (ctx) {
  23372. this._drawShape(ctx, 'triangleDown');
  23373. };
  23374. Node.prototype._drawSquare = function (ctx) {
  23375. this._drawShape(ctx, 'square');
  23376. };
  23377. Node.prototype._drawStar = function (ctx) {
  23378. this._drawShape(ctx, 'star');
  23379. };
  23380. Node.prototype._resizeShape = function (ctx) {
  23381. if (!this.width) {
  23382. this.options.radius= this.baseRadiusValue;
  23383. var size = 2 * this.options.radius;
  23384. this.width = size;
  23385. this.height = size;
  23386. // scaling used for clustering
  23387. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23388. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23389. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  23390. this.growthIndicator = this.width - size;
  23391. }
  23392. };
  23393. Node.prototype._drawShape = function (ctx, shape) {
  23394. this._resizeShape(ctx);
  23395. this.left = this.x - this.width / 2;
  23396. this.top = this.y - this.height / 2;
  23397. var clusterLineWidth = 2.5;
  23398. var borderWidth = this.options.borderWidth;
  23399. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  23400. var radiusMultiplier = 2;
  23401. // choose draw method depending on the shape
  23402. switch (shape) {
  23403. case 'dot': radiusMultiplier = 2; break;
  23404. case 'square': radiusMultiplier = 2; break;
  23405. case 'triangle': radiusMultiplier = 3; break;
  23406. case 'triangleDown': radiusMultiplier = 3; break;
  23407. case 'star': radiusMultiplier = 4; break;
  23408. }
  23409. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  23410. // draw the outer border
  23411. if (this.clusterSize > 1) {
  23412. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23413. ctx.lineWidth *= this.networkScaleInv;
  23414. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23415. ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth);
  23416. ctx.stroke();
  23417. }
  23418. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  23419. ctx.lineWidth *= this.networkScaleInv;
  23420. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  23421. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  23422. ctx[shape](this.x, this.y, this.options.radius);
  23423. ctx.fill();
  23424. ctx.stroke();
  23425. if (this.label) {
  23426. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true);
  23427. }
  23428. };
  23429. Node.prototype._resizeText = function (ctx) {
  23430. if (!this.width) {
  23431. var margin = 5;
  23432. var textSize = this.getTextSize(ctx);
  23433. this.width = textSize.width + 2 * margin;
  23434. this.height = textSize.height + 2 * margin;
  23435. // scaling used for clustering
  23436. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  23437. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  23438. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  23439. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  23440. }
  23441. };
  23442. Node.prototype._drawText = function (ctx) {
  23443. this._resizeText(ctx);
  23444. this.left = this.x - this.width / 2;
  23445. this.top = this.y - this.height / 2;
  23446. this._label(ctx, this.label, this.x, this.y);
  23447. };
  23448. Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) {
  23449. if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) {
  23450. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  23451. var lines = text.split('\n');
  23452. var lineCount = lines.length;
  23453. var fontSize = (Number(this.options.fontSize) + 4); // TODO: why is this +4 ?
  23454. var yLine = y + (1 - lineCount) / 2 * fontSize;
  23455. if (labelUnderNode == true) {
  23456. yLine = y + (1 - lineCount) / (2 * fontSize);
  23457. }
  23458. // font fill from edges now for nodes!
  23459. var width = ctx.measureText(lines[0]).width;
  23460. for (var i = 1; i < lineCount; i++) {
  23461. var lineWidth = ctx.measureText(lines[i]).width;
  23462. width = lineWidth > width ? lineWidth : width;
  23463. }
  23464. var height = this.options.fontSize * lineCount;
  23465. var left = x - width / 2;
  23466. var top = y - height / 2;
  23467. if (baseline == "top") {
  23468. top += 0.5 * fontSize;
  23469. }
  23470. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  23471. // create the fontfill background
  23472. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  23473. ctx.fillStyle = this.options.fontFill;
  23474. ctx.fillRect(left, top, width, height);
  23475. }
  23476. // draw text
  23477. ctx.fillStyle = this.options.fontColor || "black";
  23478. ctx.textAlign = align || "center";
  23479. ctx.textBaseline = baseline || "middle";
  23480. for (var i = 0; i < lineCount; i++) {
  23481. ctx.fillText(lines[i], x, yLine);
  23482. yLine += fontSize;
  23483. }
  23484. }
  23485. };
  23486. Node.prototype.getTextSize = function(ctx) {
  23487. if (this.label !== undefined) {
  23488. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  23489. var lines = this.label.split('\n'),
  23490. height = (Number(this.options.fontSize) + 4) * lines.length,
  23491. width = 0;
  23492. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  23493. width = Math.max(width, ctx.measureText(lines[i]).width);
  23494. }
  23495. return {"width": width, "height": height};
  23496. }
  23497. else {
  23498. return {"width": 0, "height": 0};
  23499. }
  23500. };
  23501. /**
  23502. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  23503. * there is a safety margin of 0.3 * width;
  23504. *
  23505. * @returns {boolean}
  23506. */
  23507. Node.prototype.inArea = function() {
  23508. if (this.width !== undefined) {
  23509. return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x &&
  23510. this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x &&
  23511. this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y &&
  23512. this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y);
  23513. }
  23514. else {
  23515. return true;
  23516. }
  23517. };
  23518. /**
  23519. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  23520. * @returns {boolean}
  23521. */
  23522. Node.prototype.inView = function() {
  23523. return (this.x >= this.canvasTopLeft.x &&
  23524. this.x < this.canvasBottomRight.x &&
  23525. this.y >= this.canvasTopLeft.y &&
  23526. this.y < this.canvasBottomRight.y);
  23527. };
  23528. /**
  23529. * This allows the zoom level of the network to influence the rendering
  23530. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  23531. *
  23532. * @param scale
  23533. * @param canvasTopLeft
  23534. * @param canvasBottomRight
  23535. */
  23536. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  23537. this.networkScaleInv = 1.0/scale;
  23538. this.networkScale = scale;
  23539. this.canvasTopLeft = canvasTopLeft;
  23540. this.canvasBottomRight = canvasBottomRight;
  23541. };
  23542. /**
  23543. * This allows the zoom level of the network to influence the rendering
  23544. *
  23545. * @param scale
  23546. */
  23547. Node.prototype.setScale = function(scale) {
  23548. this.networkScaleInv = 1.0/scale;
  23549. this.networkScale = scale;
  23550. };
  23551. /**
  23552. * set the velocity at 0. Is called when this node is contained in another during clustering
  23553. */
  23554. Node.prototype.clearVelocity = function() {
  23555. this.vx = 0;
  23556. this.vy = 0;
  23557. };
  23558. /**
  23559. * Basic preservation of (kinectic) energy
  23560. *
  23561. * @param massBeforeClustering
  23562. */
  23563. Node.prototype.updateVelocity = function(massBeforeClustering) {
  23564. var energyBefore = this.vx * this.vx * massBeforeClustering;
  23565. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  23566. this.vx = Math.sqrt(energyBefore/this.options.mass);
  23567. energyBefore = this.vy * this.vy * massBeforeClustering;
  23568. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  23569. this.vy = Math.sqrt(energyBefore/this.options.mass);
  23570. };
  23571. module.exports = Node;
  23572. /***/ },
  23573. /* 57 */
  23574. /***/ function(module, exports, __webpack_require__) {
  23575. var util = __webpack_require__(1);
  23576. var Node = __webpack_require__(56);
  23577. /**
  23578. * @class Edge
  23579. *
  23580. * A edge connects two nodes
  23581. * @param {Object} properties Object with properties. Must contain
  23582. * At least properties from and to.
  23583. * Available properties: from (number),
  23584. * to (number), label (string, color (string),
  23585. * width (number), style (string),
  23586. * length (number), title (string)
  23587. * @param {Network} network A Network object, used to find and edge to
  23588. * nodes.
  23589. * @param {Object} constants An object with default values for
  23590. * example for the color
  23591. */
  23592. function Edge (properties, network, networkConstants) {
  23593. if (!network) {
  23594. throw "No network provided";
  23595. }
  23596. var fields = ['edges','physics'];
  23597. var constants = util.selectiveBridgeObject(fields,networkConstants);
  23598. this.options = constants.edges;
  23599. this.physics = constants.physics;
  23600. this.options['smoothCurves'] = networkConstants['smoothCurves'];
  23601. this.network = network;
  23602. // initialize variables
  23603. this.id = undefined;
  23604. this.fromId = undefined;
  23605. this.toId = undefined;
  23606. this.title = undefined;
  23607. this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
  23608. this.value = undefined;
  23609. this.selected = false;
  23610. this.hover = false;
  23611. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  23612. this.dirtyLabel = true;
  23613. this.from = null; // a node
  23614. this.to = null; // a node
  23615. this.via = null; // a temp node
  23616. this.fromBackup = null; // used to clean up after reconnect
  23617. this.toBackup = null;; // used to clean up after reconnect
  23618. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  23619. // by storing the original information we can revert to the original connection when the cluser is opened.
  23620. this.originalFromId = [];
  23621. this.originalToId = [];
  23622. this.connected = false;
  23623. this.widthFixed = false;
  23624. this.lengthFixed = false;
  23625. this.setProperties(properties);
  23626. this.controlNodesEnabled = false;
  23627. this.controlNodes = {from:null, to:null, positions:{}};
  23628. this.connectedNode = null;
  23629. }
  23630. /**
  23631. * Set or overwrite properties for the edge
  23632. * @param {Object} properties an object with properties
  23633. * @param {Object} constants and object with default, global properties
  23634. */
  23635. Edge.prototype.setProperties = function(properties) {
  23636. if (!properties) {
  23637. return;
  23638. }
  23639. var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
  23640. 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor'
  23641. ];
  23642. util.selectiveDeepExtend(fields, this.options, properties);
  23643. if (properties.from !== undefined) {this.fromId = properties.from;}
  23644. if (properties.to !== undefined) {this.toId = properties.to;}
  23645. if (properties.id !== undefined) {this.id = properties.id;}
  23646. if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
  23647. if (properties.title !== undefined) {this.title = properties.title;}
  23648. if (properties.value !== undefined) {this.value = properties.value;}
  23649. if (properties.length !== undefined) {this.physics.springLength = properties.length;}
  23650. if (properties.color !== undefined) {
  23651. this.options.inheritColor = false;
  23652. if (util.isString(properties.color)) {
  23653. this.options.color.color = properties.color;
  23654. this.options.color.highlight = properties.color;
  23655. }
  23656. else {
  23657. if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
  23658. if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
  23659. if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
  23660. }
  23661. }
  23662. // A node is connected when it has a from and to node.
  23663. this.connect();
  23664. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  23665. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  23666. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  23667. // set draw method based on style
  23668. switch (this.options.style) {
  23669. case 'line': this.draw = this._drawLine; break;
  23670. case 'arrow': this.draw = this._drawArrow; break;
  23671. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  23672. case 'dash-line': this.draw = this._drawDashLine; break;
  23673. default: this.draw = this._drawLine; break;
  23674. }
  23675. };
  23676. /**
  23677. * Connect an edge to its nodes
  23678. */
  23679. Edge.prototype.connect = function () {
  23680. this.disconnect();
  23681. this.from = this.network.nodes[this.fromId] || null;
  23682. this.to = this.network.nodes[this.toId] || null;
  23683. this.connected = (this.from && this.to);
  23684. if (this.connected) {
  23685. this.from.attachEdge(this);
  23686. this.to.attachEdge(this);
  23687. }
  23688. else {
  23689. if (this.from) {
  23690. this.from.detachEdge(this);
  23691. }
  23692. if (this.to) {
  23693. this.to.detachEdge(this);
  23694. }
  23695. }
  23696. };
  23697. /**
  23698. * Disconnect an edge from its nodes
  23699. */
  23700. Edge.prototype.disconnect = function () {
  23701. if (this.from) {
  23702. this.from.detachEdge(this);
  23703. this.from = null;
  23704. }
  23705. if (this.to) {
  23706. this.to.detachEdge(this);
  23707. this.to = null;
  23708. }
  23709. this.connected = false;
  23710. };
  23711. /**
  23712. * get the title of this edge.
  23713. * @return {string} title The title of the edge, or undefined when no title
  23714. * has been set.
  23715. */
  23716. Edge.prototype.getTitle = function() {
  23717. return typeof this.title === "function" ? this.title() : this.title;
  23718. };
  23719. /**
  23720. * Retrieve the value of the edge. Can be undefined
  23721. * @return {Number} value
  23722. */
  23723. Edge.prototype.getValue = function() {
  23724. return this.value;
  23725. };
  23726. /**
  23727. * Adjust the value range of the edge. The edge will adjust it's width
  23728. * based on its value.
  23729. * @param {Number} min
  23730. * @param {Number} max
  23731. */
  23732. Edge.prototype.setValueRange = function(min, max) {
  23733. if (!this.widthFixed && this.value !== undefined) {
  23734. var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
  23735. this.options.width= (this.value - min) * scale + this.options.widthMin;
  23736. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  23737. }
  23738. };
  23739. /**
  23740. * Redraw a edge
  23741. * Draw this edge in the given canvas
  23742. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23743. * @param {CanvasRenderingContext2D} ctx
  23744. */
  23745. Edge.prototype.draw = function(ctx) {
  23746. throw "Method draw not initialized in edge";
  23747. };
  23748. /**
  23749. * Check if this object is overlapping with the provided object
  23750. * @param {Object} obj an object with parameters left, top
  23751. * @return {boolean} True if location is located on the edge
  23752. */
  23753. Edge.prototype.isOverlappingWith = function(obj) {
  23754. if (this.connected) {
  23755. var distMax = 10;
  23756. var xFrom = this.from.x;
  23757. var yFrom = this.from.y;
  23758. var xTo = this.to.x;
  23759. var yTo = this.to.y;
  23760. var xObj = obj.left;
  23761. var yObj = obj.top;
  23762. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  23763. return (dist < distMax);
  23764. }
  23765. else {
  23766. return false
  23767. }
  23768. };
  23769. Edge.prototype._getColor = function() {
  23770. var colorObj = this.options.color;
  23771. if (this.options.inheritColor == "to") {
  23772. colorObj = {
  23773. highlight: this.to.options.color.highlight.border,
  23774. hover: this.to.options.color.hover.border,
  23775. color: this.to.options.color.border
  23776. };
  23777. }
  23778. else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
  23779. colorObj = {
  23780. highlight: this.from.options.color.highlight.border,
  23781. hover: this.from.options.color.hover.border,
  23782. color: this.from.options.color.border
  23783. };
  23784. }
  23785. if (this.selected == true) {return colorObj.highlight;}
  23786. else if (this.hover == true) {return colorObj.hover;}
  23787. else {return colorObj.color;}
  23788. };
  23789. /**
  23790. * Redraw a edge as a line
  23791. * Draw this edge in the given canvas
  23792. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23793. * @param {CanvasRenderingContext2D} ctx
  23794. * @private
  23795. */
  23796. Edge.prototype._drawLine = function(ctx) {
  23797. // set style
  23798. ctx.strokeStyle = this._getColor();
  23799. ctx.lineWidth = this._getLineWidth();
  23800. if (this.from != this.to) {
  23801. // draw line
  23802. var via = this._line(ctx);
  23803. // draw label
  23804. var point;
  23805. if (this.label) {
  23806. if (this.options.smoothCurves.enabled == true && via != null) {
  23807. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  23808. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  23809. point = {x:midpointX, y:midpointY};
  23810. }
  23811. else {
  23812. point = this._pointOnLine(0.5);
  23813. }
  23814. this._label(ctx, this.label, point.x, point.y);
  23815. }
  23816. }
  23817. else {
  23818. var x, y;
  23819. var radius = this.physics.springLength / 4;
  23820. var node = this.from;
  23821. if (!node.width) {
  23822. node.resize(ctx);
  23823. }
  23824. if (node.width > node.height) {
  23825. x = node.x + node.width / 2;
  23826. y = node.y - radius;
  23827. }
  23828. else {
  23829. x = node.x + radius;
  23830. y = node.y - node.height / 2;
  23831. }
  23832. this._circle(ctx, x, y, radius);
  23833. point = this._pointOnCircle(x, y, radius, 0.5);
  23834. this._label(ctx, this.label, point.x, point.y);
  23835. }
  23836. };
  23837. /**
  23838. * Get the line width of the edge. Depends on width and whether one of the
  23839. * connected nodes is selected.
  23840. * @return {Number} width
  23841. * @private
  23842. */
  23843. Edge.prototype._getLineWidth = function() {
  23844. if (this.selected == true) {
  23845. return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
  23846. }
  23847. else {
  23848. if (this.hover == true) {
  23849. return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
  23850. }
  23851. else {
  23852. return Math.max(this.options.width, 0.3*this.networkScaleInv);
  23853. }
  23854. }
  23855. };
  23856. Edge.prototype._getViaCoordinates = function () {
  23857. var xVia = null;
  23858. var yVia = null;
  23859. var factor = this.options.smoothCurves.roundness;
  23860. var type = this.options.smoothCurves.type;
  23861. var dx = Math.abs(this.from.x - this.to.x);
  23862. var dy = Math.abs(this.from.y - this.to.y);
  23863. if (type == 'discrete' || type == 'diagonalCross') {
  23864. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  23865. if (this.from.y > this.to.y) {
  23866. if (this.from.x < this.to.x) {
  23867. xVia = this.from.x + factor * dy;
  23868. yVia = this.from.y - factor * dy;
  23869. }
  23870. else if (this.from.x > this.to.x) {
  23871. xVia = this.from.x - factor * dy;
  23872. yVia = this.from.y - factor * dy;
  23873. }
  23874. }
  23875. else if (this.from.y < this.to.y) {
  23876. if (this.from.x < this.to.x) {
  23877. xVia = this.from.x + factor * dy;
  23878. yVia = this.from.y + factor * dy;
  23879. }
  23880. else if (this.from.x > this.to.x) {
  23881. xVia = this.from.x - factor * dy;
  23882. yVia = this.from.y + factor * dy;
  23883. }
  23884. }
  23885. if (type == "discrete") {
  23886. xVia = dx < factor * dy ? this.from.x : xVia;
  23887. }
  23888. }
  23889. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  23890. if (this.from.y > this.to.y) {
  23891. if (this.from.x < this.to.x) {
  23892. xVia = this.from.x + factor * dx;
  23893. yVia = this.from.y - factor * dx;
  23894. }
  23895. else if (this.from.x > this.to.x) {
  23896. xVia = this.from.x - factor * dx;
  23897. yVia = this.from.y - factor * dx;
  23898. }
  23899. }
  23900. else if (this.from.y < this.to.y) {
  23901. if (this.from.x < this.to.x) {
  23902. xVia = this.from.x + factor * dx;
  23903. yVia = this.from.y + factor * dx;
  23904. }
  23905. else if (this.from.x > this.to.x) {
  23906. xVia = this.from.x - factor * dx;
  23907. yVia = this.from.y + factor * dx;
  23908. }
  23909. }
  23910. if (type == "discrete") {
  23911. yVia = dy < factor * dx ? this.from.y : yVia;
  23912. }
  23913. }
  23914. }
  23915. else if (type == "straightCross") {
  23916. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
  23917. xVia = this.from.x;
  23918. if (this.from.y < this.to.y) {
  23919. yVia = this.to.y - (1-factor) * dy;
  23920. }
  23921. else {
  23922. yVia = this.to.y + (1-factor) * dy;
  23923. }
  23924. }
  23925. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
  23926. if (this.from.x < this.to.x) {
  23927. xVia = this.to.x - (1-factor) * dx;
  23928. }
  23929. else {
  23930. xVia = this.to.x + (1-factor) * dx;
  23931. }
  23932. yVia = this.from.y;
  23933. }
  23934. }
  23935. else if (type == 'horizontal') {
  23936. if (this.from.x < this.to.x) {
  23937. xVia = this.to.x - (1-factor) * dx;
  23938. }
  23939. else {
  23940. xVia = this.to.x + (1-factor) * dx;
  23941. }
  23942. yVia = this.from.y;
  23943. }
  23944. else if (type == 'vertical') {
  23945. xVia = this.from.x;
  23946. if (this.from.y < this.to.y) {
  23947. yVia = this.to.y - (1-factor) * dy;
  23948. }
  23949. else {
  23950. yVia = this.to.y + (1-factor) * dy;
  23951. }
  23952. }
  23953. else { // continuous
  23954. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  23955. if (this.from.y > this.to.y) {
  23956. if (this.from.x < this.to.x) {
  23957. // console.log(1)
  23958. xVia = this.from.x + factor * dy;
  23959. yVia = this.from.y - factor * dy;
  23960. xVia = this.to.x < xVia ? this.to.x : xVia;
  23961. }
  23962. else if (this.from.x > this.to.x) {
  23963. // console.log(2)
  23964. xVia = this.from.x - factor * dy;
  23965. yVia = this.from.y - factor * dy;
  23966. xVia = this.to.x > xVia ? this.to.x :xVia;
  23967. }
  23968. }
  23969. else if (this.from.y < this.to.y) {
  23970. if (this.from.x < this.to.x) {
  23971. // console.log(3)
  23972. xVia = this.from.x + factor * dy;
  23973. yVia = this.from.y + factor * dy;
  23974. xVia = this.to.x < xVia ? this.to.x : xVia;
  23975. }
  23976. else if (this.from.x > this.to.x) {
  23977. // console.log(4, this.from.x, this.to.x)
  23978. xVia = this.from.x - factor * dy;
  23979. yVia = this.from.y + factor * dy;
  23980. xVia = this.to.x > xVia ? this.to.x : xVia;
  23981. }
  23982. }
  23983. }
  23984. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  23985. if (this.from.y > this.to.y) {
  23986. if (this.from.x < this.to.x) {
  23987. // console.log(5)
  23988. xVia = this.from.x + factor * dx;
  23989. yVia = this.from.y - factor * dx;
  23990. yVia = this.to.y > yVia ? this.to.y : yVia;
  23991. }
  23992. else if (this.from.x > this.to.x) {
  23993. // console.log(6)
  23994. xVia = this.from.x - factor * dx;
  23995. yVia = this.from.y - factor * dx;
  23996. yVia = this.to.y > yVia ? this.to.y : yVia;
  23997. }
  23998. }
  23999. else if (this.from.y < this.to.y) {
  24000. if (this.from.x < this.to.x) {
  24001. // console.log(7)
  24002. xVia = this.from.x + factor * dx;
  24003. yVia = this.from.y + factor * dx;
  24004. yVia = this.to.y < yVia ? this.to.y : yVia;
  24005. }
  24006. else if (this.from.x > this.to.x) {
  24007. // console.log(8)
  24008. xVia = this.from.x - factor * dx;
  24009. yVia = this.from.y + factor * dx;
  24010. yVia = this.to.y < yVia ? this.to.y : yVia;
  24011. }
  24012. }
  24013. }
  24014. }
  24015. return {x:xVia, y:yVia};
  24016. };
  24017. /**
  24018. * Draw a line between two nodes
  24019. * @param {CanvasRenderingContext2D} ctx
  24020. * @private
  24021. */
  24022. Edge.prototype._line = function (ctx) {
  24023. // draw a straight line
  24024. ctx.beginPath();
  24025. ctx.moveTo(this.from.x, this.from.y);
  24026. if (this.options.smoothCurves.enabled == true) {
  24027. if (this.options.smoothCurves.dynamic == false) {
  24028. var via = this._getViaCoordinates();
  24029. if (via.x == null) {
  24030. ctx.lineTo(this.to.x, this.to.y);
  24031. ctx.stroke();
  24032. return null;
  24033. }
  24034. else {
  24035. // this.via.x = via.x;
  24036. // this.via.y = via.y;
  24037. ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
  24038. ctx.stroke();
  24039. return via;
  24040. }
  24041. }
  24042. else {
  24043. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  24044. ctx.stroke();
  24045. return this.via;
  24046. }
  24047. }
  24048. else {
  24049. ctx.lineTo(this.to.x, this.to.y);
  24050. ctx.stroke();
  24051. return null;
  24052. }
  24053. };
  24054. /**
  24055. * Draw a line from a node to itself, a circle
  24056. * @param {CanvasRenderingContext2D} ctx
  24057. * @param {Number} x
  24058. * @param {Number} y
  24059. * @param {Number} radius
  24060. * @private
  24061. */
  24062. Edge.prototype._circle = function (ctx, x, y, radius) {
  24063. // draw a circle
  24064. ctx.beginPath();
  24065. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  24066. ctx.stroke();
  24067. };
  24068. /**
  24069. * Draw label with white background and with the middle at (x, y)
  24070. * @param {CanvasRenderingContext2D} ctx
  24071. * @param {String} text
  24072. * @param {Number} x
  24073. * @param {Number} y
  24074. * @private
  24075. */
  24076. Edge.prototype._label = function (ctx, text, x, y) {
  24077. if (text) {
  24078. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  24079. this.options.fontSize + "px " + this.options.fontFace;
  24080. var yLine;
  24081. if (this.dirtyLabel == true) {
  24082. var lines = String(text).split('\n');
  24083. var lineCount = lines.length;
  24084. var fontSize = (Number(this.options.fontSize) + 4);
  24085. yLine = y + (1 - lineCount) / 2 * fontSize;
  24086. var width = ctx.measureText(lines[0]).width;
  24087. for (var i = 1; i < lineCount; i++) {
  24088. var lineWidth = ctx.measureText(lines[i]).width;
  24089. width = lineWidth > width ? lineWidth : width;
  24090. }
  24091. var height = this.options.fontSize * lineCount;
  24092. var left = x - width / 2;
  24093. var top = y - height / 2;
  24094. // cache
  24095. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  24096. }
  24097. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  24098. ctx.fillStyle = this.options.fontFill;
  24099. ctx.fillRect(this.labelDimensions.left,
  24100. this.labelDimensions.top,
  24101. this.labelDimensions.width,
  24102. this.labelDimensions.height);
  24103. }
  24104. // draw text
  24105. ctx.fillStyle = this.options.fontColor || "black";
  24106. ctx.textAlign = "center";
  24107. ctx.textBaseline = "middle";
  24108. yLine = this.labelDimensions.yLine;
  24109. for (var i = 0; i < lineCount; i++) {
  24110. ctx.fillText(lines[i], x, yLine);
  24111. yLine += fontSize;
  24112. }
  24113. }
  24114. };
  24115. /**
  24116. * Redraw a edge as a dashed line
  24117. * Draw this edge in the given canvas
  24118. * @author David Jordan
  24119. * @date 2012-08-08
  24120. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  24121. * @param {CanvasRenderingContext2D} ctx
  24122. * @private
  24123. */
  24124. Edge.prototype._drawDashLine = function(ctx) {
  24125. // set style
  24126. ctx.strokeStyle = this._getColor();
  24127. ctx.lineWidth = this._getLineWidth();
  24128. var via = null;
  24129. // only firefox and chrome support this method, else we use the legacy one.
  24130. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  24131. // configure the dash pattern
  24132. var pattern = [0];
  24133. if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
  24134. pattern = [this.options.dash.length,this.options.dash.gap];
  24135. }
  24136. else {
  24137. pattern = [5,5];
  24138. }
  24139. // set dash settings for chrome or firefox
  24140. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  24141. ctx.setLineDash(pattern);
  24142. ctx.lineDashOffset = 0;
  24143. } else { //Firefox
  24144. ctx.mozDash = pattern;
  24145. ctx.mozDashOffset = 0;
  24146. }
  24147. // draw the line
  24148. via = this._line(ctx);
  24149. // restore the dash settings.
  24150. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  24151. ctx.setLineDash([0]);
  24152. ctx.lineDashOffset = 0;
  24153. } else { //Firefox
  24154. ctx.mozDash = [0];
  24155. ctx.mozDashOffset = 0;
  24156. }
  24157. }
  24158. else { // unsupporting smooth lines
  24159. // draw dashed line
  24160. ctx.beginPath();
  24161. ctx.lineCap = 'round';
  24162. if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  24163. {
  24164. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  24165. [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
  24166. }
  24167. 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
  24168. {
  24169. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  24170. [this.options.dash.length,this.options.dash.gap]);
  24171. }
  24172. else //If all else fails draw a line
  24173. {
  24174. ctx.moveTo(this.from.x, this.from.y);
  24175. ctx.lineTo(this.to.x, this.to.y);
  24176. }
  24177. ctx.stroke();
  24178. }
  24179. // draw label
  24180. if (this.label) {
  24181. var point;
  24182. if (this.options.smoothCurves.enabled == true && via != null) {
  24183. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  24184. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  24185. point = {x:midpointX, y:midpointY};
  24186. }
  24187. else {
  24188. point = this._pointOnLine(0.5);
  24189. }
  24190. this._label(ctx, this.label, point.x, point.y);
  24191. }
  24192. };
  24193. /**
  24194. * Get a point on a line
  24195. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  24196. * @return {Object} point
  24197. * @private
  24198. */
  24199. Edge.prototype._pointOnLine = function (percentage) {
  24200. return {
  24201. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  24202. y: (1 - percentage) * this.from.y + percentage * this.to.y
  24203. }
  24204. };
  24205. /**
  24206. * Get a point on a circle
  24207. * @param {Number} x
  24208. * @param {Number} y
  24209. * @param {Number} radius
  24210. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  24211. * @return {Object} point
  24212. * @private
  24213. */
  24214. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  24215. var angle = (percentage - 3/8) * 2 * Math.PI;
  24216. return {
  24217. x: x + radius * Math.cos(angle),
  24218. y: y - radius * Math.sin(angle)
  24219. }
  24220. };
  24221. /**
  24222. * Redraw a edge as a line with an arrow halfway the line
  24223. * Draw this edge in the given canvas
  24224. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  24225. * @param {CanvasRenderingContext2D} ctx
  24226. * @private
  24227. */
  24228. Edge.prototype._drawArrowCenter = function(ctx) {
  24229. var point;
  24230. // set style
  24231. ctx.strokeStyle = this._getColor();
  24232. ctx.fillStyle = ctx.strokeStyle;
  24233. ctx.lineWidth = this._getLineWidth();
  24234. if (this.from != this.to) {
  24235. // draw line
  24236. var via = this._line(ctx);
  24237. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  24238. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  24239. // draw an arrow halfway the line
  24240. if (this.options.smoothCurves.enabled == true && via != null) {
  24241. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  24242. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  24243. point = {x:midpointX, y:midpointY};
  24244. }
  24245. else {
  24246. point = this._pointOnLine(0.5);
  24247. }
  24248. ctx.arrow(point.x, point.y, angle, length);
  24249. ctx.fill();
  24250. ctx.stroke();
  24251. // draw label
  24252. if (this.label) {
  24253. this._label(ctx, this.label, point.x, point.y);
  24254. }
  24255. }
  24256. else {
  24257. // draw circle
  24258. var x, y;
  24259. var radius = 0.25 * Math.max(100,this.physics.springLength);
  24260. var node = this.from;
  24261. if (!node.width) {
  24262. node.resize(ctx);
  24263. }
  24264. if (node.width > node.height) {
  24265. x = node.x + node.width * 0.5;
  24266. y = node.y - radius;
  24267. }
  24268. else {
  24269. x = node.x + radius;
  24270. y = node.y - node.height * 0.5;
  24271. }
  24272. this._circle(ctx, x, y, radius);
  24273. // draw all arrows
  24274. var angle = 0.2 * Math.PI;
  24275. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  24276. point = this._pointOnCircle(x, y, radius, 0.5);
  24277. ctx.arrow(point.x, point.y, angle, length);
  24278. ctx.fill();
  24279. ctx.stroke();
  24280. // draw label
  24281. if (this.label) {
  24282. point = this._pointOnCircle(x, y, radius, 0.5);
  24283. this._label(ctx, this.label, point.x, point.y);
  24284. }
  24285. }
  24286. };
  24287. /**
  24288. * Redraw a edge as a line with an arrow
  24289. * Draw this edge in the given canvas
  24290. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  24291. * @param {CanvasRenderingContext2D} ctx
  24292. * @private
  24293. */
  24294. Edge.prototype._drawArrow = function(ctx) {
  24295. // set style
  24296. ctx.strokeStyle = this._getColor();
  24297. ctx.fillStyle = ctx.strokeStyle;
  24298. ctx.lineWidth = this._getLineWidth();
  24299. var angle, length;
  24300. //draw a line
  24301. if (this.from != this.to) {
  24302. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  24303. var dx = (this.to.x - this.from.x);
  24304. var dy = (this.to.y - this.from.y);
  24305. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  24306. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  24307. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  24308. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  24309. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  24310. var via;
  24311. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
  24312. via = this.via;
  24313. }
  24314. else if (this.options.smoothCurves.enabled == true) {
  24315. via = this._getViaCoordinates();
  24316. }
  24317. if (this.options.smoothCurves.enabled == true && via.x != null) {
  24318. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  24319. dx = (this.to.x - via.x);
  24320. dy = (this.to.y - via.y);
  24321. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  24322. }
  24323. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  24324. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  24325. var xTo,yTo;
  24326. if (this.options.smoothCurves.enabled == true && via.x != null) {
  24327. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  24328. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  24329. }
  24330. else {
  24331. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  24332. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  24333. }
  24334. ctx.beginPath();
  24335. ctx.moveTo(xFrom,yFrom);
  24336. if (this.options.smoothCurves.enabled == true && via.x != null) {
  24337. ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
  24338. }
  24339. else {
  24340. ctx.lineTo(xTo, yTo);
  24341. }
  24342. ctx.stroke();
  24343. // draw arrow at the end of the line
  24344. length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  24345. ctx.arrow(xTo, yTo, angle, length);
  24346. ctx.fill();
  24347. ctx.stroke();
  24348. // draw label
  24349. if (this.label) {
  24350. var point;
  24351. if (this.options.smoothCurves.enabled == true && via != null) {
  24352. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  24353. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  24354. point = {x:midpointX, y:midpointY};
  24355. }
  24356. else {
  24357. point = this._pointOnLine(0.5);
  24358. }
  24359. this._label(ctx, this.label, point.x, point.y);
  24360. }
  24361. }
  24362. else {
  24363. // draw circle
  24364. var node = this.from;
  24365. var x, y, arrow;
  24366. var radius = 0.25 * Math.max(100,this.physics.springLength);
  24367. if (!node.width) {
  24368. node.resize(ctx);
  24369. }
  24370. if (node.width > node.height) {
  24371. x = node.x + node.width * 0.5;
  24372. y = node.y - radius;
  24373. arrow = {
  24374. x: x,
  24375. y: node.y,
  24376. angle: 0.9 * Math.PI
  24377. };
  24378. }
  24379. else {
  24380. x = node.x + radius;
  24381. y = node.y - node.height * 0.5;
  24382. arrow = {
  24383. x: node.x,
  24384. y: y,
  24385. angle: 0.6 * Math.PI
  24386. };
  24387. }
  24388. ctx.beginPath();
  24389. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  24390. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  24391. ctx.stroke();
  24392. // draw all arrows
  24393. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  24394. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  24395. ctx.fill();
  24396. ctx.stroke();
  24397. // draw label
  24398. if (this.label) {
  24399. point = this._pointOnCircle(x, y, radius, 0.5);
  24400. this._label(ctx, this.label, point.x, point.y);
  24401. }
  24402. }
  24403. };
  24404. /**
  24405. * Calculate the distance between a point (x3,y3) and a line segment from
  24406. * (x1,y1) to (x2,y2).
  24407. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  24408. * @param {number} x1
  24409. * @param {number} y1
  24410. * @param {number} x2
  24411. * @param {number} y2
  24412. * @param {number} x3
  24413. * @param {number} y3
  24414. * @private
  24415. */
  24416. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  24417. var returnValue = 0;
  24418. if (this.from != this.to) {
  24419. if (this.options.smoothCurves.enabled == true) {
  24420. var xVia, yVia;
  24421. if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
  24422. xVia = this.via.x;
  24423. yVia = this.via.y;
  24424. }
  24425. else {
  24426. var via = this._getViaCoordinates();
  24427. xVia = via.x;
  24428. yVia = via.y;
  24429. }
  24430. var minDistance = 1e9;
  24431. var distance;
  24432. var i,t,x,y, lastX, lastY;
  24433. for (i = 0; i < 10; i++) {
  24434. t = 0.1*i;
  24435. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
  24436. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
  24437. if (i > 0) {
  24438. distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
  24439. minDistance = distance < minDistance ? distance : minDistance;
  24440. }
  24441. lastX = x; lastY = y;
  24442. }
  24443. returnValue = minDistance;
  24444. }
  24445. else {
  24446. returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
  24447. }
  24448. }
  24449. else {
  24450. var x, y, dx, dy;
  24451. var radius = 0.25 * this.physics.springLength;
  24452. var node = this.from;
  24453. if (node.width > node.height) {
  24454. x = node.x + 0.5 * node.width;
  24455. y = node.y - radius;
  24456. }
  24457. else {
  24458. x = node.x + radius;
  24459. y = node.y - 0.5 * node.height;
  24460. }
  24461. dx = x - x3;
  24462. dy = y - y3;
  24463. returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
  24464. }
  24465. if (this.labelDimensions.left < x3 &&
  24466. this.labelDimensions.left + this.labelDimensions.width > x3 &&
  24467. this.labelDimensions.top < y3 &&
  24468. this.labelDimensions.top + this.labelDimensions.height > y3) {
  24469. return 0;
  24470. }
  24471. else {
  24472. return returnValue;
  24473. }
  24474. };
  24475. Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
  24476. var px = x2-x1,
  24477. py = y2-y1,
  24478. something = px*px + py*py,
  24479. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  24480. if (u > 1) {
  24481. u = 1;
  24482. }
  24483. else if (u < 0) {
  24484. u = 0;
  24485. }
  24486. var x = x1 + u * px,
  24487. y = y1 + u * py,
  24488. dx = x - x3,
  24489. dy = y - y3;
  24490. //# Note: If the actual distance does not matter,
  24491. //# if you only want to compare what this function
  24492. //# returns to other results of this function, you
  24493. //# can just return the squared distance instead
  24494. //# (i.e. remove the sqrt) to gain a little performance
  24495. return Math.sqrt(dx*dx + dy*dy);
  24496. };
  24497. /**
  24498. * This allows the zoom level of the network to influence the rendering
  24499. *
  24500. * @param scale
  24501. */
  24502. Edge.prototype.setScale = function(scale) {
  24503. this.networkScaleInv = 1.0/scale;
  24504. };
  24505. Edge.prototype.select = function() {
  24506. this.selected = true;
  24507. };
  24508. Edge.prototype.unselect = function() {
  24509. this.selected = false;
  24510. };
  24511. Edge.prototype.positionBezierNode = function() {
  24512. if (this.via !== null && this.from !== null && this.to !== null) {
  24513. this.via.x = 0.5 * (this.from.x + this.to.x);
  24514. this.via.y = 0.5 * (this.from.y + this.to.y);
  24515. }
  24516. };
  24517. /**
  24518. * This function draws the control nodes for the manipulator.
  24519. * In order to enable this, only set the this.controlNodesEnabled to true.
  24520. * @param ctx
  24521. */
  24522. Edge.prototype._drawControlNodes = function(ctx) {
  24523. if (this.controlNodesEnabled == true) {
  24524. if (this.controlNodes.from === null && this.controlNodes.to === null) {
  24525. var nodeIdFrom = "edgeIdFrom:".concat(this.id);
  24526. var nodeIdTo = "edgeIdTo:".concat(this.id);
  24527. var constants = {
  24528. nodes:{group:'', radius:8},
  24529. physics:{damping:0},
  24530. clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
  24531. };
  24532. this.controlNodes.from = new Node(
  24533. {id:nodeIdFrom,
  24534. shape:'dot',
  24535. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  24536. },{},{},constants);
  24537. this.controlNodes.to = new Node(
  24538. {id:nodeIdTo,
  24539. shape:'dot',
  24540. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  24541. },{},{},constants);
  24542. }
  24543. if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
  24544. this.controlNodes.positions = this.getControlNodePositions(ctx);
  24545. this.controlNodes.from.x = this.controlNodes.positions.from.x;
  24546. this.controlNodes.from.y = this.controlNodes.positions.from.y;
  24547. this.controlNodes.to.x = this.controlNodes.positions.to.x;
  24548. this.controlNodes.to.y = this.controlNodes.positions.to.y;
  24549. }
  24550. this.controlNodes.from.draw(ctx);
  24551. this.controlNodes.to.draw(ctx);
  24552. }
  24553. else {
  24554. this.controlNodes = {from:null, to:null, positions:{}};
  24555. }
  24556. };
  24557. /**
  24558. * Enable control nodes.
  24559. * @private
  24560. */
  24561. Edge.prototype._enableControlNodes = function() {
  24562. this.fromBackup = this.from;
  24563. this.toBackup = this.to;
  24564. this.controlNodesEnabled = true;
  24565. };
  24566. /**
  24567. * disable control nodes and remove from dynamicEdges from old node
  24568. * @private
  24569. */
  24570. Edge.prototype._disableControlNodes = function() {
  24571. this.fromId = this.from.id;
  24572. this.toId = this.to.id;
  24573. if (this.fromId != this.fromBackup.id) { // from was changed, remove edge from old 'from' node dynamic edges
  24574. this.fromBackup.detachEdge(this);
  24575. }
  24576. else if (this.toId != this.toBackup.id) { // to was changed, remove edge from old 'to' node dynamic edges
  24577. this.toBackup.detachEdge(this);
  24578. }
  24579. this.fromBackup = null;
  24580. this.toBackup = null;
  24581. this.controlNodesEnabled = false;
  24582. };
  24583. /**
  24584. * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
  24585. * @param x
  24586. * @param y
  24587. * @returns {null}
  24588. * @private
  24589. */
  24590. Edge.prototype._getSelectedControlNode = function(x,y) {
  24591. var positions = this.controlNodes.positions;
  24592. var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
  24593. var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
  24594. if (fromDistance < 15) {
  24595. this.connectedNode = this.from;
  24596. this.from = this.controlNodes.from;
  24597. return this.controlNodes.from;
  24598. }
  24599. else if (toDistance < 15) {
  24600. this.connectedNode = this.to;
  24601. this.to = this.controlNodes.to;
  24602. return this.controlNodes.to;
  24603. }
  24604. else {
  24605. return null;
  24606. }
  24607. };
  24608. /**
  24609. * this resets the control nodes to their original position.
  24610. * @private
  24611. */
  24612. Edge.prototype._restoreControlNodes = function() {
  24613. if (this.controlNodes.from.selected == true) {
  24614. this.from = this.connectedNode;
  24615. this.connectedNode = null;
  24616. this.controlNodes.from.unselect();
  24617. }
  24618. else if (this.controlNodes.to.selected == true) {
  24619. this.to = this.connectedNode;
  24620. this.connectedNode = null;
  24621. this.controlNodes.to.unselect();
  24622. }
  24623. };
  24624. /**
  24625. * this calculates the position of the control nodes on the edges of the parent nodes.
  24626. *
  24627. * @param ctx
  24628. * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
  24629. */
  24630. Edge.prototype.getControlNodePositions = function(ctx) {
  24631. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  24632. var dx = (this.to.x - this.from.x);
  24633. var dy = (this.to.y - this.from.y);
  24634. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  24635. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  24636. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  24637. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  24638. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  24639. var via;
  24640. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
  24641. via = this.via;
  24642. }
  24643. else if (this.options.smoothCurves.enabled == true) {
  24644. via = this._getViaCoordinates();
  24645. }
  24646. if (this.options.smoothCurves.enabled == true && via.x != null) {
  24647. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  24648. dx = (this.to.x - via.x);
  24649. dy = (this.to.y - via.y);
  24650. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  24651. }
  24652. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  24653. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  24654. var xTo,yTo;
  24655. if (this.options.smoothCurves.enabled == true && via.x != null) {
  24656. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  24657. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  24658. }
  24659. else {
  24660. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  24661. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  24662. }
  24663. return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
  24664. };
  24665. module.exports = Edge;
  24666. /***/ },
  24667. /* 58 */
  24668. /***/ function(module, exports, __webpack_require__) {
  24669. /**
  24670. * Popup is a class to create a popup window with some text
  24671. * @param {Element} container The container object.
  24672. * @param {Number} [x]
  24673. * @param {Number} [y]
  24674. * @param {String} [text]
  24675. * @param {Object} [style] An object containing borderColor,
  24676. * backgroundColor, etc.
  24677. */
  24678. function Popup(container, x, y, text, style) {
  24679. if (container) {
  24680. this.container = container;
  24681. }
  24682. else {
  24683. this.container = document.body;
  24684. }
  24685. // x, y and text are optional, see if a style object was passed in their place
  24686. if (style === undefined) {
  24687. if (typeof x === "object") {
  24688. style = x;
  24689. x = undefined;
  24690. } else if (typeof text === "object") {
  24691. style = text;
  24692. text = undefined;
  24693. } else {
  24694. // for backwards compatibility, in case clients other than Network are creating Popup directly
  24695. style = {
  24696. fontColor: 'black',
  24697. fontSize: 14, // px
  24698. fontFace: 'verdana',
  24699. color: {
  24700. border: '#666',
  24701. background: '#FFFFC6'
  24702. }
  24703. }
  24704. }
  24705. }
  24706. this.x = 0;
  24707. this.y = 0;
  24708. this.padding = 5;
  24709. if (x !== undefined && y !== undefined ) {
  24710. this.setPosition(x, y);
  24711. }
  24712. if (text !== undefined) {
  24713. this.setText(text);
  24714. }
  24715. // create the frame
  24716. this.frame = document.createElement("div");
  24717. var styleAttr = this.frame.style;
  24718. styleAttr.position = "absolute";
  24719. styleAttr.visibility = "hidden";
  24720. styleAttr.border = "1px solid " + style.color.border;
  24721. styleAttr.color = style.fontColor;
  24722. styleAttr.fontSize = style.fontSize + "px";
  24723. styleAttr.fontFamily = style.fontFace;
  24724. styleAttr.padding = this.padding + "px";
  24725. styleAttr.backgroundColor = style.color.background;
  24726. styleAttr.borderRadius = "3px";
  24727. styleAttr.MozBorderRadius = "3px";
  24728. styleAttr.WebkitBorderRadius = "3px";
  24729. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  24730. styleAttr.whiteSpace = "nowrap";
  24731. this.container.appendChild(this.frame);
  24732. }
  24733. /**
  24734. * @param {number} x Horizontal position of the popup window
  24735. * @param {number} y Vertical position of the popup window
  24736. */
  24737. Popup.prototype.setPosition = function(x, y) {
  24738. this.x = parseInt(x);
  24739. this.y = parseInt(y);
  24740. };
  24741. /**
  24742. * Set the content for the popup window. This can be HTML code or text.
  24743. * @param {string | Element} content
  24744. */
  24745. Popup.prototype.setText = function(content) {
  24746. if (content instanceof Element) {
  24747. this.frame.innerHTML = '';
  24748. this.frame.appendChild(content);
  24749. }
  24750. else {
  24751. this.frame.innerHTML = content; // string containing text or HTML
  24752. }
  24753. };
  24754. /**
  24755. * Show the popup window
  24756. * @param {boolean} show Optional. Show or hide the window
  24757. */
  24758. Popup.prototype.show = function (show) {
  24759. if (show === undefined) {
  24760. show = true;
  24761. }
  24762. if (show) {
  24763. var height = this.frame.clientHeight;
  24764. var width = this.frame.clientWidth;
  24765. var maxHeight = this.frame.parentNode.clientHeight;
  24766. var maxWidth = this.frame.parentNode.clientWidth;
  24767. var top = (this.y - height);
  24768. if (top + height + this.padding > maxHeight) {
  24769. top = maxHeight - height - this.padding;
  24770. }
  24771. if (top < this.padding) {
  24772. top = this.padding;
  24773. }
  24774. var left = this.x;
  24775. if (left + width + this.padding > maxWidth) {
  24776. left = maxWidth - width - this.padding;
  24777. }
  24778. if (left < this.padding) {
  24779. left = this.padding;
  24780. }
  24781. this.frame.style.left = left + "px";
  24782. this.frame.style.top = top + "px";
  24783. this.frame.style.visibility = "visible";
  24784. }
  24785. else {
  24786. this.hide();
  24787. }
  24788. };
  24789. /**
  24790. * Hide the popup window
  24791. */
  24792. Popup.prototype.hide = function () {
  24793. this.frame.style.visibility = "hidden";
  24794. };
  24795. module.exports = Popup;
  24796. /***/ },
  24797. /* 59 */
  24798. /***/ function(module, exports, __webpack_require__) {
  24799. var PhysicsMixin = __webpack_require__(60);
  24800. var ClusterMixin = __webpack_require__(64);
  24801. var SectorsMixin = __webpack_require__(65);
  24802. var SelectionMixin = __webpack_require__(66);
  24803. var ManipulationMixin = __webpack_require__(67);
  24804. var NavigationMixin = __webpack_require__(68);
  24805. var HierarchicalLayoutMixin = __webpack_require__(69);
  24806. /**
  24807. * Load a mixin into the network object
  24808. *
  24809. * @param {Object} sourceVariable | this object has to contain functions.
  24810. * @private
  24811. */
  24812. exports._loadMixin = function (sourceVariable) {
  24813. for (var mixinFunction in sourceVariable) {
  24814. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  24815. this[mixinFunction] = sourceVariable[mixinFunction];
  24816. }
  24817. }
  24818. };
  24819. /**
  24820. * removes a mixin from the network object.
  24821. *
  24822. * @param {Object} sourceVariable | this object has to contain functions.
  24823. * @private
  24824. */
  24825. exports._clearMixin = function (sourceVariable) {
  24826. for (var mixinFunction in sourceVariable) {
  24827. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  24828. this[mixinFunction] = undefined;
  24829. }
  24830. }
  24831. };
  24832. /**
  24833. * Mixin the physics system and initialize the parameters required.
  24834. *
  24835. * @private
  24836. */
  24837. exports._loadPhysicsSystem = function () {
  24838. this._loadMixin(PhysicsMixin);
  24839. this._loadSelectedForceSolver();
  24840. if (this.constants.configurePhysics == true) {
  24841. this._loadPhysicsConfiguration();
  24842. }
  24843. };
  24844. /**
  24845. * Mixin the cluster system and initialize the parameters required.
  24846. *
  24847. * @private
  24848. */
  24849. exports._loadClusterSystem = function () {
  24850. this.clusterSession = 0;
  24851. this.hubThreshold = 5;
  24852. this._loadMixin(ClusterMixin);
  24853. };
  24854. /**
  24855. * Mixin the sector system and initialize the parameters required
  24856. *
  24857. * @private
  24858. */
  24859. exports._loadSectorSystem = function () {
  24860. this.sectors = {};
  24861. this.activeSector = ["default"];
  24862. this.sectors["active"] = {};
  24863. this.sectors["active"]["default"] = {"nodes": {},
  24864. "edges": {},
  24865. "nodeIndices": [],
  24866. "formationScale": 1.0,
  24867. "drawingNode": undefined };
  24868. this.sectors["frozen"] = {};
  24869. this.sectors["support"] = {"nodes": {},
  24870. "edges": {},
  24871. "nodeIndices": [],
  24872. "formationScale": 1.0,
  24873. "drawingNode": undefined };
  24874. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  24875. this._loadMixin(SectorsMixin);
  24876. };
  24877. /**
  24878. * Mixin the selection system and initialize the parameters required
  24879. *
  24880. * @private
  24881. */
  24882. exports._loadSelectionSystem = function () {
  24883. this.selectionObj = {nodes: {}, edges: {}};
  24884. this._loadMixin(SelectionMixin);
  24885. };
  24886. /**
  24887. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  24888. *
  24889. * @private
  24890. */
  24891. exports._loadManipulationSystem = function () {
  24892. // reset global variables -- these are used by the selection of nodes and edges.
  24893. this.blockConnectingEdgeSelection = false;
  24894. this.forceAppendSelection = false;
  24895. if (this.constants.dataManipulation.enabled == true) {
  24896. // load the manipulator HTML elements. All styling done in css.
  24897. if (this.manipulationDiv === undefined) {
  24898. this.manipulationDiv = document.createElement('div');
  24899. this.manipulationDiv.className = 'network-manipulationDiv';
  24900. if (this.editMode == true) {
  24901. this.manipulationDiv.style.display = "block";
  24902. }
  24903. else {
  24904. this.manipulationDiv.style.display = "none";
  24905. }
  24906. this.frame.appendChild(this.manipulationDiv);
  24907. }
  24908. if (this.editModeDiv === undefined) {
  24909. this.editModeDiv = document.createElement('div');
  24910. this.editModeDiv.className = 'network-manipulation-editMode';
  24911. if (this.editMode == true) {
  24912. this.editModeDiv.style.display = "none";
  24913. }
  24914. else {
  24915. this.editModeDiv.style.display = "block";
  24916. }
  24917. this.frame.appendChild(this.editModeDiv);
  24918. }
  24919. if (this.closeDiv === undefined) {
  24920. this.closeDiv = document.createElement('div');
  24921. this.closeDiv.className = 'network-manipulation-closeDiv';
  24922. this.closeDiv.style.display = this.manipulationDiv.style.display;
  24923. this.frame.appendChild(this.closeDiv);
  24924. }
  24925. // load the manipulation functions
  24926. this._loadMixin(ManipulationMixin);
  24927. // create the manipulator toolbar
  24928. this._createManipulatorBar();
  24929. }
  24930. else {
  24931. if (this.manipulationDiv !== undefined) {
  24932. // removes all the bindings and overloads
  24933. this._createManipulatorBar();
  24934. // remove the manipulation divs
  24935. this.frame.removeChild(this.manipulationDiv);
  24936. this.frame.removeChild(this.editModeDiv);
  24937. this.frame.removeChild(this.closeDiv);
  24938. this.manipulationDiv = undefined;
  24939. this.editModeDiv = undefined;
  24940. this.closeDiv = undefined;
  24941. // remove the mixin functions
  24942. this._clearMixin(ManipulationMixin);
  24943. }
  24944. }
  24945. };
  24946. /**
  24947. * Mixin the navigation (User Interface) system and initialize the parameters required
  24948. *
  24949. * @private
  24950. */
  24951. exports._loadNavigationControls = function () {
  24952. this._loadMixin(NavigationMixin);
  24953. // the clean function removes the button divs, this is done to remove the bindings.
  24954. this._cleanNavigation();
  24955. if (this.constants.navigation.enabled == true) {
  24956. this._loadNavigationElements();
  24957. }
  24958. };
  24959. /**
  24960. * Mixin the hierarchical layout system.
  24961. *
  24962. * @private
  24963. */
  24964. exports._loadHierarchySystem = function () {
  24965. this._loadMixin(HierarchicalLayoutMixin);
  24966. };
  24967. /***/ },
  24968. /* 60 */
  24969. /***/ function(module, exports, __webpack_require__) {
  24970. var util = __webpack_require__(1);
  24971. var RepulsionMixin = __webpack_require__(61);
  24972. var HierarchialRepulsionMixin = __webpack_require__(62);
  24973. var BarnesHutMixin = __webpack_require__(63);
  24974. /**
  24975. * Toggling barnes Hut calculation on and off.
  24976. *
  24977. * @private
  24978. */
  24979. exports._toggleBarnesHut = function () {
  24980. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  24981. this._loadSelectedForceSolver();
  24982. this.moving = true;
  24983. this.start();
  24984. };
  24985. /**
  24986. * This loads the node force solver based on the barnes hut or repulsion algorithm
  24987. *
  24988. * @private
  24989. */
  24990. exports._loadSelectedForceSolver = function () {
  24991. // this overloads the this._calculateNodeForces
  24992. if (this.constants.physics.barnesHut.enabled == true) {
  24993. this._clearMixin(RepulsionMixin);
  24994. this._clearMixin(HierarchialRepulsionMixin);
  24995. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  24996. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  24997. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  24998. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  24999. this._loadMixin(BarnesHutMixin);
  25000. }
  25001. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  25002. this._clearMixin(BarnesHutMixin);
  25003. this._clearMixin(RepulsionMixin);
  25004. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  25005. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  25006. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  25007. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  25008. this._loadMixin(HierarchialRepulsionMixin);
  25009. }
  25010. else {
  25011. this._clearMixin(BarnesHutMixin);
  25012. this._clearMixin(HierarchialRepulsionMixin);
  25013. this.barnesHutTree = undefined;
  25014. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  25015. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  25016. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  25017. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  25018. this._loadMixin(RepulsionMixin);
  25019. }
  25020. };
  25021. /**
  25022. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  25023. * if there is more than one node. If it is just one node, we dont calculate anything.
  25024. *
  25025. * @private
  25026. */
  25027. exports._initializeForceCalculation = function () {
  25028. // stop calculation if there is only one node
  25029. if (this.nodeIndices.length == 1) {
  25030. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  25031. }
  25032. else {
  25033. // if there are too many nodes on screen, we cluster without repositioning
  25034. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  25035. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  25036. }
  25037. // we now start the force calculation
  25038. this._calculateForces();
  25039. }
  25040. };
  25041. /**
  25042. * Calculate the external forces acting on the nodes
  25043. * Forces are caused by: edges, repulsing forces between nodes, gravity
  25044. * @private
  25045. */
  25046. exports._calculateForces = function () {
  25047. // Gravity is required to keep separated groups from floating off
  25048. // the forces are reset to zero in this loop by using _setForce instead
  25049. // of _addForce
  25050. this._calculateGravitationalForces();
  25051. this._calculateNodeForces();
  25052. if (this.constants.physics.springConstant > 0) {
  25053. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  25054. this._calculateSpringForcesWithSupport();
  25055. }
  25056. else {
  25057. if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  25058. this._calculateHierarchicalSpringForces();
  25059. }
  25060. else {
  25061. this._calculateSpringForces();
  25062. }
  25063. }
  25064. }
  25065. };
  25066. /**
  25067. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  25068. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  25069. * This function joins the datanodes and invisible (called support) nodes into one object.
  25070. * We do this so we do not contaminate this.nodes with the support nodes.
  25071. *
  25072. * @private
  25073. */
  25074. exports._updateCalculationNodes = function () {
  25075. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  25076. this.calculationNodes = {};
  25077. this.calculationNodeIndices = [];
  25078. for (var nodeId in this.nodes) {
  25079. if (this.nodes.hasOwnProperty(nodeId)) {
  25080. this.calculationNodes[nodeId] = this.nodes[nodeId];
  25081. }
  25082. }
  25083. var supportNodes = this.sectors['support']['nodes'];
  25084. for (var supportNodeId in supportNodes) {
  25085. if (supportNodes.hasOwnProperty(supportNodeId)) {
  25086. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  25087. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  25088. }
  25089. else {
  25090. supportNodes[supportNodeId]._setForce(0, 0);
  25091. }
  25092. }
  25093. }
  25094. for (var idx in this.calculationNodes) {
  25095. if (this.calculationNodes.hasOwnProperty(idx)) {
  25096. this.calculationNodeIndices.push(idx);
  25097. }
  25098. }
  25099. }
  25100. else {
  25101. this.calculationNodes = this.nodes;
  25102. this.calculationNodeIndices = this.nodeIndices;
  25103. }
  25104. };
  25105. /**
  25106. * this function applies the central gravity effect to keep groups from floating off
  25107. *
  25108. * @private
  25109. */
  25110. exports._calculateGravitationalForces = function () {
  25111. var dx, dy, distance, node, i;
  25112. var nodes = this.calculationNodes;
  25113. var gravity = this.constants.physics.centralGravity;
  25114. var gravityForce = 0;
  25115. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  25116. node = nodes[this.calculationNodeIndices[i]];
  25117. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  25118. // gravity does not apply when we are in a pocket sector
  25119. if (this._sector() == "default" && gravity != 0) {
  25120. dx = -node.x;
  25121. dy = -node.y;
  25122. distance = Math.sqrt(dx * dx + dy * dy);
  25123. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  25124. node.fx = dx * gravityForce;
  25125. node.fy = dy * gravityForce;
  25126. }
  25127. else {
  25128. node.fx = 0;
  25129. node.fy = 0;
  25130. }
  25131. }
  25132. };
  25133. /**
  25134. * this function calculates the effects of the springs in the case of unsmooth curves.
  25135. *
  25136. * @private
  25137. */
  25138. exports._calculateSpringForces = function () {
  25139. var edgeLength, edge, edgeId;
  25140. var dx, dy, fx, fy, springForce, distance;
  25141. var edges = this.edges;
  25142. // forces caused by the edges, modelled as springs
  25143. for (edgeId in edges) {
  25144. if (edges.hasOwnProperty(edgeId)) {
  25145. edge = edges[edgeId];
  25146. if (edge.connected) {
  25147. // only calculate forces if nodes are in the same sector
  25148. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25149. edgeLength = edge.physics.springLength;
  25150. // this implies that the edges between big clusters are longer
  25151. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  25152. dx = (edge.from.x - edge.to.x);
  25153. dy = (edge.from.y - edge.to.y);
  25154. distance = Math.sqrt(dx * dx + dy * dy);
  25155. if (distance == 0) {
  25156. distance = 0.01;
  25157. }
  25158. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25159. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25160. fx = dx * springForce;
  25161. fy = dy * springForce;
  25162. edge.from.fx += fx;
  25163. edge.from.fy += fy;
  25164. edge.to.fx -= fx;
  25165. edge.to.fy -= fy;
  25166. }
  25167. }
  25168. }
  25169. }
  25170. };
  25171. /**
  25172. * This function calculates the springforces on the nodes, accounting for the support nodes.
  25173. *
  25174. * @private
  25175. */
  25176. exports._calculateSpringForcesWithSupport = function () {
  25177. var edgeLength, edge, edgeId, combinedClusterSize;
  25178. var edges = this.edges;
  25179. // forces caused by the edges, modelled as springs
  25180. for (edgeId in edges) {
  25181. if (edges.hasOwnProperty(edgeId)) {
  25182. edge = edges[edgeId];
  25183. if (edge.connected) {
  25184. // only calculate forces if nodes are in the same sector
  25185. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25186. if (edge.via != null) {
  25187. var node1 = edge.to;
  25188. var node2 = edge.via;
  25189. var node3 = edge.from;
  25190. edgeLength = edge.physics.springLength;
  25191. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  25192. // this implies that the edges between big clusters are longer
  25193. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  25194. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  25195. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  25196. }
  25197. }
  25198. }
  25199. }
  25200. }
  25201. };
  25202. /**
  25203. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  25204. *
  25205. * @param node1
  25206. * @param node2
  25207. * @param edgeLength
  25208. * @private
  25209. */
  25210. exports._calculateSpringForce = function (node1, node2, edgeLength) {
  25211. var dx, dy, fx, fy, springForce, distance;
  25212. dx = (node1.x - node2.x);
  25213. dy = (node1.y - node2.y);
  25214. distance = Math.sqrt(dx * dx + dy * dy);
  25215. if (distance == 0) {
  25216. distance = 0.01;
  25217. }
  25218. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25219. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25220. fx = dx * springForce;
  25221. fy = dy * springForce;
  25222. node1.fx += fx;
  25223. node1.fy += fy;
  25224. node2.fx -= fx;
  25225. node2.fy -= fy;
  25226. };
  25227. /**
  25228. * Load the HTML for the physics config and bind it
  25229. * @private
  25230. */
  25231. exports._loadPhysicsConfiguration = function () {
  25232. if (this.physicsConfiguration === undefined) {
  25233. this.backupConstants = {};
  25234. util.deepExtend(this.backupConstants,this.constants);
  25235. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  25236. this.physicsConfiguration = document.createElement('div');
  25237. this.physicsConfiguration.className = "PhysicsConfiguration";
  25238. this.physicsConfiguration.innerHTML = '' +
  25239. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  25240. '<tr>' +
  25241. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  25242. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  25243. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  25244. '</tr>' +
  25245. '</table>' +
  25246. '<table id="graph_BH_table" style="display:none">' +
  25247. '<tr><td><b>Barnes Hut</b></td></tr>' +
  25248. '<tr>' +
  25249. '<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>' +
  25250. '</tr>' +
  25251. '<tr>' +
  25252. '<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>' +
  25253. '</tr>' +
  25254. '<tr>' +
  25255. '<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>' +
  25256. '</tr>' +
  25257. '<tr>' +
  25258. '<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>' +
  25259. '</tr>' +
  25260. '<tr>' +
  25261. '<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>' +
  25262. '</tr>' +
  25263. '</table>' +
  25264. '<table id="graph_R_table" style="display:none">' +
  25265. '<tr><td><b>Repulsion</b></td></tr>' +
  25266. '<tr>' +
  25267. '<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>' +
  25268. '</tr>' +
  25269. '<tr>' +
  25270. '<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>' +
  25271. '</tr>' +
  25272. '<tr>' +
  25273. '<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>' +
  25274. '</tr>' +
  25275. '<tr>' +
  25276. '<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>' +
  25277. '</tr>' +
  25278. '<tr>' +
  25279. '<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>' +
  25280. '</tr>' +
  25281. '</table>' +
  25282. '<table id="graph_H_table" style="display:none">' +
  25283. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  25284. '<tr>' +
  25285. '<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>' +
  25286. '</tr>' +
  25287. '<tr>' +
  25288. '<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>' +
  25289. '</tr>' +
  25290. '<tr>' +
  25291. '<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>' +
  25292. '</tr>' +
  25293. '<tr>' +
  25294. '<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>' +
  25295. '</tr>' +
  25296. '<tr>' +
  25297. '<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>' +
  25298. '</tr>' +
  25299. '<tr>' +
  25300. '<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>' +
  25301. '</tr>' +
  25302. '<tr>' +
  25303. '<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>' +
  25304. '</tr>' +
  25305. '<tr>' +
  25306. '<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>' +
  25307. '</tr>' +
  25308. '</table>' +
  25309. '<table><tr><td><b>Options:</b></td></tr>' +
  25310. '<tr>' +
  25311. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  25312. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  25313. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  25314. '</tr>' +
  25315. '</table>'
  25316. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  25317. this.optionsDiv = document.createElement("div");
  25318. this.optionsDiv.style.fontSize = "14px";
  25319. this.optionsDiv.style.fontFamily = "verdana";
  25320. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  25321. var rangeElement;
  25322. rangeElement = document.getElementById('graph_BH_gc');
  25323. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  25324. rangeElement = document.getElementById('graph_BH_cg');
  25325. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  25326. rangeElement = document.getElementById('graph_BH_sc');
  25327. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  25328. rangeElement = document.getElementById('graph_BH_sl');
  25329. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  25330. rangeElement = document.getElementById('graph_BH_damp');
  25331. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  25332. rangeElement = document.getElementById('graph_R_nd');
  25333. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  25334. rangeElement = document.getElementById('graph_R_cg');
  25335. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  25336. rangeElement = document.getElementById('graph_R_sc');
  25337. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  25338. rangeElement = document.getElementById('graph_R_sl');
  25339. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  25340. rangeElement = document.getElementById('graph_R_damp');
  25341. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  25342. rangeElement = document.getElementById('graph_H_nd');
  25343. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  25344. rangeElement = document.getElementById('graph_H_cg');
  25345. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  25346. rangeElement = document.getElementById('graph_H_sc');
  25347. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  25348. rangeElement = document.getElementById('graph_H_sl');
  25349. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  25350. rangeElement = document.getElementById('graph_H_damp');
  25351. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  25352. rangeElement = document.getElementById('graph_H_direction');
  25353. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  25354. rangeElement = document.getElementById('graph_H_levsep');
  25355. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  25356. rangeElement = document.getElementById('graph_H_nspac');
  25357. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  25358. var radioButton1 = document.getElementById("graph_physicsMethod1");
  25359. var radioButton2 = document.getElementById("graph_physicsMethod2");
  25360. var radioButton3 = document.getElementById("graph_physicsMethod3");
  25361. radioButton2.checked = true;
  25362. if (this.constants.physics.barnesHut.enabled) {
  25363. radioButton1.checked = true;
  25364. }
  25365. if (this.constants.hierarchicalLayout.enabled) {
  25366. radioButton3.checked = true;
  25367. }
  25368. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  25369. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  25370. var graph_generateOptions = document.getElementById("graph_generateOptions");
  25371. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  25372. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  25373. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  25374. if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) {
  25375. graph_toggleSmooth.style.background = "#A4FF56";
  25376. }
  25377. else {
  25378. graph_toggleSmooth.style.background = "#FF8532";
  25379. }
  25380. switchConfigurations.apply(this);
  25381. radioButton1.onchange = switchConfigurations.bind(this);
  25382. radioButton2.onchange = switchConfigurations.bind(this);
  25383. radioButton3.onchange = switchConfigurations.bind(this);
  25384. }
  25385. };
  25386. /**
  25387. * This overwrites the this.constants.
  25388. *
  25389. * @param constantsVariableName
  25390. * @param value
  25391. * @private
  25392. */
  25393. exports._overWriteGraphConstants = function (constantsVariableName, value) {
  25394. var nameArray = constantsVariableName.split("_");
  25395. if (nameArray.length == 1) {
  25396. this.constants[nameArray[0]] = value;
  25397. }
  25398. else if (nameArray.length == 2) {
  25399. this.constants[nameArray[0]][nameArray[1]] = value;
  25400. }
  25401. else if (nameArray.length == 3) {
  25402. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  25403. }
  25404. };
  25405. /**
  25406. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  25407. */
  25408. function graphToggleSmoothCurves () {
  25409. this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled;
  25410. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  25411. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  25412. else {graph_toggleSmooth.style.background = "#FF8532";}
  25413. this._configureSmoothCurves(false);
  25414. }
  25415. /**
  25416. * this function is used to scramble the nodes
  25417. *
  25418. */
  25419. function graphRepositionNodes () {
  25420. for (var nodeId in this.calculationNodes) {
  25421. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  25422. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  25423. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  25424. }
  25425. }
  25426. if (this.constants.hierarchicalLayout.enabled == true) {
  25427. this._setupHierarchicalLayout();
  25428. showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  25429. showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity");
  25430. showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant");
  25431. showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength");
  25432. showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping");
  25433. }
  25434. else {
  25435. this.repositionNodes();
  25436. }
  25437. this.moving = true;
  25438. this.start();
  25439. }
  25440. /**
  25441. * this is used to generate an options file from the playing with physics system.
  25442. */
  25443. function graphGenerateOptions () {
  25444. var options = "No options are required, default values used.";
  25445. var optionsSpecific = [];
  25446. var radioButton1 = document.getElementById("graph_physicsMethod1");
  25447. var radioButton2 = document.getElementById("graph_physicsMethod2");
  25448. if (radioButton1.checked == true) {
  25449. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  25450. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  25451. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  25452. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  25453. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  25454. if (optionsSpecific.length != 0) {
  25455. options = "var options = {";
  25456. options += "physics: {barnesHut: {";
  25457. for (var i = 0; i < optionsSpecific.length; i++) {
  25458. options += optionsSpecific[i];
  25459. if (i < optionsSpecific.length - 1) {
  25460. options += ", "
  25461. }
  25462. }
  25463. options += '}}'
  25464. }
  25465. if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {
  25466. if (optionsSpecific.length == 0) {options = "var options = {";}
  25467. else {options += ", "}
  25468. options += "smoothCurves: " + this.constants.smoothCurves.enabled;
  25469. }
  25470. if (options != "No options are required, default values used.") {
  25471. options += '};'
  25472. }
  25473. }
  25474. else if (radioButton2.checked == true) {
  25475. options = "var options = {";
  25476. options += "physics: {barnesHut: {enabled: false}";
  25477. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  25478. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  25479. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  25480. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  25481. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  25482. if (optionsSpecific.length != 0) {
  25483. options += ", repulsion: {";
  25484. for (var i = 0; i < optionsSpecific.length; i++) {
  25485. options += optionsSpecific[i];
  25486. if (i < optionsSpecific.length - 1) {
  25487. options += ", "
  25488. }
  25489. }
  25490. options += '}}'
  25491. }
  25492. if (optionsSpecific.length == 0) {options += "}"}
  25493. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  25494. options += ", smoothCurves: " + this.constants.smoothCurves;
  25495. }
  25496. options += '};'
  25497. }
  25498. else {
  25499. options = "var options = {";
  25500. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  25501. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  25502. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  25503. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  25504. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  25505. if (optionsSpecific.length != 0) {
  25506. options += "physics: {hierarchicalRepulsion: {";
  25507. for (var i = 0; i < optionsSpecific.length; i++) {
  25508. options += optionsSpecific[i];
  25509. if (i < optionsSpecific.length - 1) {
  25510. options += ", ";
  25511. }
  25512. }
  25513. options += '}},';
  25514. }
  25515. options += 'hierarchicalLayout: {';
  25516. optionsSpecific = [];
  25517. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  25518. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  25519. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  25520. if (optionsSpecific.length != 0) {
  25521. for (var i = 0; i < optionsSpecific.length; i++) {
  25522. options += optionsSpecific[i];
  25523. if (i < optionsSpecific.length - 1) {
  25524. options += ", "
  25525. }
  25526. }
  25527. options += '}'
  25528. }
  25529. else {
  25530. options += "enabled:true}";
  25531. }
  25532. options += '};'
  25533. }
  25534. this.optionsDiv.innerHTML = options;
  25535. }
  25536. /**
  25537. * this is used to switch between barnesHut, repulsion and hierarchical.
  25538. *
  25539. */
  25540. function switchConfigurations () {
  25541. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  25542. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  25543. var tableId = "graph_" + radioButton + "_table";
  25544. var table = document.getElementById(tableId);
  25545. table.style.display = "block";
  25546. for (var i = 0; i < ids.length; i++) {
  25547. if (ids[i] != tableId) {
  25548. table = document.getElementById(ids[i]);
  25549. table.style.display = "none";
  25550. }
  25551. }
  25552. this._restoreNodes();
  25553. if (radioButton == "R") {
  25554. this.constants.hierarchicalLayout.enabled = false;
  25555. this.constants.physics.hierarchicalRepulsion.enabled = false;
  25556. this.constants.physics.barnesHut.enabled = false;
  25557. }
  25558. else if (radioButton == "H") {
  25559. if (this.constants.hierarchicalLayout.enabled == false) {
  25560. this.constants.hierarchicalLayout.enabled = true;
  25561. this.constants.physics.hierarchicalRepulsion.enabled = true;
  25562. this.constants.physics.barnesHut.enabled = false;
  25563. this.constants.smoothCurves.enabled = false;
  25564. this._setupHierarchicalLayout();
  25565. }
  25566. }
  25567. else {
  25568. this.constants.hierarchicalLayout.enabled = false;
  25569. this.constants.physics.hierarchicalRepulsion.enabled = false;
  25570. this.constants.physics.barnesHut.enabled = true;
  25571. }
  25572. this._loadSelectedForceSolver();
  25573. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  25574. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  25575. else {graph_toggleSmooth.style.background = "#FF8532";}
  25576. this.moving = true;
  25577. this.start();
  25578. }
  25579. /**
  25580. * this generates the ranges depending on the iniital values.
  25581. *
  25582. * @param id
  25583. * @param map
  25584. * @param constantsVariableName
  25585. */
  25586. function showValueOfRange (id,map,constantsVariableName) {
  25587. var valueId = id + "_value";
  25588. var rangeValue = document.getElementById(id).value;
  25589. if (Array.isArray(map)) {
  25590. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  25591. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  25592. }
  25593. else {
  25594. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  25595. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  25596. }
  25597. if (constantsVariableName == "hierarchicalLayout_direction" ||
  25598. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  25599. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  25600. this._setupHierarchicalLayout();
  25601. }
  25602. this.moving = true;
  25603. this.start();
  25604. }
  25605. /***/ },
  25606. /* 61 */
  25607. /***/ function(module, exports, __webpack_require__) {
  25608. /**
  25609. * Calculate the forces the nodes apply on each other based on a repulsion field.
  25610. * This field is linearly approximated.
  25611. *
  25612. * @private
  25613. */
  25614. exports._calculateNodeForces = function () {
  25615. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  25616. repulsingForce, node1, node2, i, j;
  25617. var nodes = this.calculationNodes;
  25618. var nodeIndices = this.calculationNodeIndices;
  25619. // approximation constants
  25620. var a_base = -2 / 3;
  25621. var b = 4 / 3;
  25622. // repulsing forces between nodes
  25623. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  25624. var minimumDistance = nodeDistance;
  25625. // we loop from i over all but the last entree in the array
  25626. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  25627. for (i = 0; i < nodeIndices.length - 1; i++) {
  25628. node1 = nodes[nodeIndices[i]];
  25629. for (j = i + 1; j < nodeIndices.length; j++) {
  25630. node2 = nodes[nodeIndices[j]];
  25631. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  25632. dx = node2.x - node1.x;
  25633. dy = node2.y - node1.y;
  25634. distance = Math.sqrt(dx * dx + dy * dy);
  25635. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  25636. var a = a_base / minimumDistance;
  25637. if (distance < 2 * minimumDistance) {
  25638. if (distance < 0.5 * minimumDistance) {
  25639. repulsingForce = 1.0;
  25640. }
  25641. else {
  25642. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  25643. }
  25644. // amplify the repulsion for clusters.
  25645. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  25646. repulsingForce = repulsingForce / distance;
  25647. fx = dx * repulsingForce;
  25648. fy = dy * repulsingForce;
  25649. node1.fx -= fx;
  25650. node1.fy -= fy;
  25651. node2.fx += fx;
  25652. node2.fy += fy;
  25653. }
  25654. }
  25655. }
  25656. };
  25657. /***/ },
  25658. /* 62 */
  25659. /***/ function(module, exports, __webpack_require__) {
  25660. /**
  25661. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  25662. * This field is linearly approximated.
  25663. *
  25664. * @private
  25665. */
  25666. exports._calculateNodeForces = function () {
  25667. var dx, dy, distance, fx, fy,
  25668. repulsingForce, node1, node2, i, j;
  25669. var nodes = this.calculationNodes;
  25670. var nodeIndices = this.calculationNodeIndices;
  25671. // repulsing forces between nodes
  25672. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  25673. // we loop from i over all but the last entree in the array
  25674. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  25675. for (i = 0; i < nodeIndices.length - 1; i++) {
  25676. node1 = nodes[nodeIndices[i]];
  25677. for (j = i + 1; j < nodeIndices.length; j++) {
  25678. node2 = nodes[nodeIndices[j]];
  25679. // nodes only affect nodes on their level
  25680. if (node1.level == node2.level) {
  25681. dx = node2.x - node1.x;
  25682. dy = node2.y - node1.y;
  25683. distance = Math.sqrt(dx * dx + dy * dy);
  25684. var steepness = 0.05;
  25685. if (distance < nodeDistance) {
  25686. repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2);
  25687. }
  25688. else {
  25689. repulsingForce = 0;
  25690. }
  25691. // normalize force with
  25692. if (distance == 0) {
  25693. distance = 0.01;
  25694. }
  25695. else {
  25696. repulsingForce = repulsingForce / distance;
  25697. }
  25698. fx = dx * repulsingForce;
  25699. fy = dy * repulsingForce;
  25700. node1.fx -= fx;
  25701. node1.fy -= fy;
  25702. node2.fx += fx;
  25703. node2.fy += fy;
  25704. }
  25705. }
  25706. }
  25707. };
  25708. /**
  25709. * this function calculates the effects of the springs in the case of unsmooth curves.
  25710. *
  25711. * @private
  25712. */
  25713. exports._calculateHierarchicalSpringForces = function () {
  25714. var edgeLength, edge, edgeId;
  25715. var dx, dy, fx, fy, springForce, distance;
  25716. var edges = this.edges;
  25717. var nodes = this.calculationNodes;
  25718. var nodeIndices = this.calculationNodeIndices;
  25719. for (var i = 0; i < nodeIndices.length; i++) {
  25720. var node1 = nodes[nodeIndices[i]];
  25721. node1.springFx = 0;
  25722. node1.springFy = 0;
  25723. }
  25724. // forces caused by the edges, modelled as springs
  25725. for (edgeId in edges) {
  25726. if (edges.hasOwnProperty(edgeId)) {
  25727. edge = edges[edgeId];
  25728. if (edge.connected) {
  25729. // only calculate forces if nodes are in the same sector
  25730. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25731. edgeLength = edge.physics.springLength;
  25732. // this implies that the edges between big clusters are longer
  25733. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  25734. dx = (edge.from.x - edge.to.x);
  25735. dy = (edge.from.y - edge.to.y);
  25736. distance = Math.sqrt(dx * dx + dy * dy);
  25737. if (distance == 0) {
  25738. distance = 0.01;
  25739. }
  25740. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25741. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25742. fx = dx * springForce;
  25743. fy = dy * springForce;
  25744. if (edge.to.level != edge.from.level) {
  25745. edge.to.springFx -= fx;
  25746. edge.to.springFy -= fy;
  25747. edge.from.springFx += fx;
  25748. edge.from.springFy += fy;
  25749. }
  25750. else {
  25751. var factor = 0.5;
  25752. edge.to.fx -= factor*fx;
  25753. edge.to.fy -= factor*fy;
  25754. edge.from.fx += factor*fx;
  25755. edge.from.fy += factor*fy;
  25756. }
  25757. }
  25758. }
  25759. }
  25760. }
  25761. // normalize spring forces
  25762. var springForce = 1;
  25763. var springFx, springFy;
  25764. for (i = 0; i < nodeIndices.length; i++) {
  25765. var node = nodes[nodeIndices[i]];
  25766. springFx = Math.min(springForce,Math.max(-springForce,node.springFx));
  25767. springFy = Math.min(springForce,Math.max(-springForce,node.springFy));
  25768. node.fx += springFx;
  25769. node.fy += springFy;
  25770. }
  25771. // retain energy balance
  25772. var totalFx = 0;
  25773. var totalFy = 0;
  25774. for (i = 0; i < nodeIndices.length; i++) {
  25775. var node = nodes[nodeIndices[i]];
  25776. totalFx += node.fx;
  25777. totalFy += node.fy;
  25778. }
  25779. var correctionFx = totalFx / nodeIndices.length;
  25780. var correctionFy = totalFy / nodeIndices.length;
  25781. for (i = 0; i < nodeIndices.length; i++) {
  25782. var node = nodes[nodeIndices[i]];
  25783. node.fx -= correctionFx;
  25784. node.fy -= correctionFy;
  25785. }
  25786. };
  25787. /***/ },
  25788. /* 63 */
  25789. /***/ function(module, exports, __webpack_require__) {
  25790. /**
  25791. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  25792. * The Barnes Hut method is used to speed up this N-body simulation.
  25793. *
  25794. * @private
  25795. */
  25796. exports._calculateNodeForces = function() {
  25797. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  25798. var node;
  25799. var nodes = this.calculationNodes;
  25800. var nodeIndices = this.calculationNodeIndices;
  25801. var nodeCount = nodeIndices.length;
  25802. this._formBarnesHutTree(nodes,nodeIndices);
  25803. var barnesHutTree = this.barnesHutTree;
  25804. // place the nodes one by one recursively
  25805. for (var i = 0; i < nodeCount; i++) {
  25806. node = nodes[nodeIndices[i]];
  25807. if (node.options.mass > 0) {
  25808. // starting with root is irrelevant, it never passes the BarnesHut condition
  25809. this._getForceContribution(barnesHutTree.root.children.NW,node);
  25810. this._getForceContribution(barnesHutTree.root.children.NE,node);
  25811. this._getForceContribution(barnesHutTree.root.children.SW,node);
  25812. this._getForceContribution(barnesHutTree.root.children.SE,node);
  25813. }
  25814. }
  25815. }
  25816. };
  25817. /**
  25818. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  25819. * If a region contains a single node, we check if it is not itself, then we apply the force.
  25820. *
  25821. * @param parentBranch
  25822. * @param node
  25823. * @private
  25824. */
  25825. exports._getForceContribution = function(parentBranch,node) {
  25826. // we get no force contribution from an empty region
  25827. if (parentBranch.childrenCount > 0) {
  25828. var dx,dy,distance;
  25829. // get the distance from the center of mass to the node.
  25830. dx = parentBranch.centerOfMass.x - node.x;
  25831. dy = parentBranch.centerOfMass.y - node.y;
  25832. distance = Math.sqrt(dx * dx + dy * dy);
  25833. // BarnesHut condition
  25834. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  25835. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  25836. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  25837. // duplicate code to reduce function calls to speed up program
  25838. if (distance == 0) {
  25839. distance = 0.1*Math.random();
  25840. dx = distance;
  25841. }
  25842. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  25843. var fx = dx * gravityForce;
  25844. var fy = dy * gravityForce;
  25845. node.fx += fx;
  25846. node.fy += fy;
  25847. }
  25848. else {
  25849. // Did not pass the condition, go into children if available
  25850. if (parentBranch.childrenCount == 4) {
  25851. this._getForceContribution(parentBranch.children.NW,node);
  25852. this._getForceContribution(parentBranch.children.NE,node);
  25853. this._getForceContribution(parentBranch.children.SW,node);
  25854. this._getForceContribution(parentBranch.children.SE,node);
  25855. }
  25856. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  25857. if (parentBranch.children.data.id != node.id) { // if it is not self
  25858. // duplicate code to reduce function calls to speed up program
  25859. if (distance == 0) {
  25860. distance = 0.5*Math.random();
  25861. dx = distance;
  25862. }
  25863. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  25864. var fx = dx * gravityForce;
  25865. var fy = dy * gravityForce;
  25866. node.fx += fx;
  25867. node.fy += fy;
  25868. }
  25869. }
  25870. }
  25871. }
  25872. };
  25873. /**
  25874. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  25875. *
  25876. * @param nodes
  25877. * @param nodeIndices
  25878. * @private
  25879. */
  25880. exports._formBarnesHutTree = function(nodes,nodeIndices) {
  25881. var node;
  25882. var nodeCount = nodeIndices.length;
  25883. var minX = Number.MAX_VALUE,
  25884. minY = Number.MAX_VALUE,
  25885. maxX =-Number.MAX_VALUE,
  25886. maxY =-Number.MAX_VALUE;
  25887. // get the range of the nodes
  25888. for (var i = 0; i < nodeCount; i++) {
  25889. var x = nodes[nodeIndices[i]].x;
  25890. var y = nodes[nodeIndices[i]].y;
  25891. if (nodes[nodeIndices[i]].options.mass > 0) {
  25892. if (x < minX) { minX = x; }
  25893. if (x > maxX) { maxX = x; }
  25894. if (y < minY) { minY = y; }
  25895. if (y > maxY) { maxY = y; }
  25896. }
  25897. }
  25898. // make the range a square
  25899. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  25900. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  25901. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  25902. var minimumTreeSize = 1e-5;
  25903. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  25904. var halfRootSize = 0.5 * rootSize;
  25905. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  25906. // construct the barnesHutTree
  25907. var barnesHutTree = {
  25908. root:{
  25909. centerOfMass: {x:0, y:0},
  25910. mass:0,
  25911. range: {
  25912. minX: centerX-halfRootSize,maxX:centerX+halfRootSize,
  25913. minY: centerY-halfRootSize,maxY:centerY+halfRootSize
  25914. },
  25915. size: rootSize,
  25916. calcSize: 1 / rootSize,
  25917. children: { data:null},
  25918. maxWidth: 0,
  25919. level: 0,
  25920. childrenCount: 4
  25921. }
  25922. };
  25923. this._splitBranch(barnesHutTree.root);
  25924. // place the nodes one by one recursively
  25925. for (i = 0; i < nodeCount; i++) {
  25926. node = nodes[nodeIndices[i]];
  25927. if (node.options.mass > 0) {
  25928. this._placeInTree(barnesHutTree.root,node);
  25929. }
  25930. }
  25931. // make global
  25932. this.barnesHutTree = barnesHutTree
  25933. };
  25934. /**
  25935. * this updates the mass of a branch. this is increased by adding a node.
  25936. *
  25937. * @param parentBranch
  25938. * @param node
  25939. * @private
  25940. */
  25941. exports._updateBranchMass = function(parentBranch, node) {
  25942. var totalMass = parentBranch.mass + node.options.mass;
  25943. var totalMassInv = 1/totalMass;
  25944. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  25945. parentBranch.centerOfMass.x *= totalMassInv;
  25946. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  25947. parentBranch.centerOfMass.y *= totalMassInv;
  25948. parentBranch.mass = totalMass;
  25949. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  25950. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  25951. };
  25952. /**
  25953. * determine in which branch the node will be placed.
  25954. *
  25955. * @param parentBranch
  25956. * @param node
  25957. * @param skipMassUpdate
  25958. * @private
  25959. */
  25960. exports._placeInTree = function(parentBranch,node,skipMassUpdate) {
  25961. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  25962. // update the mass of the branch.
  25963. this._updateBranchMass(parentBranch,node);
  25964. }
  25965. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  25966. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  25967. this._placeInRegion(parentBranch,node,"NW");
  25968. }
  25969. else { // in SW
  25970. this._placeInRegion(parentBranch,node,"SW");
  25971. }
  25972. }
  25973. else { // in NE or SE
  25974. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  25975. this._placeInRegion(parentBranch,node,"NE");
  25976. }
  25977. else { // in SE
  25978. this._placeInRegion(parentBranch,node,"SE");
  25979. }
  25980. }
  25981. };
  25982. /**
  25983. * actually place the node in a region (or branch)
  25984. *
  25985. * @param parentBranch
  25986. * @param node
  25987. * @param region
  25988. * @private
  25989. */
  25990. exports._placeInRegion = function(parentBranch,node,region) {
  25991. switch (parentBranch.children[region].childrenCount) {
  25992. case 0: // place node here
  25993. parentBranch.children[region].children.data = node;
  25994. parentBranch.children[region].childrenCount = 1;
  25995. this._updateBranchMass(parentBranch.children[region],node);
  25996. break;
  25997. case 1: // convert into children
  25998. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  25999. // we move one node a pixel and we do not put it in the tree.
  26000. if (parentBranch.children[region].children.data.x == node.x &&
  26001. parentBranch.children[region].children.data.y == node.y) {
  26002. node.x += Math.random();
  26003. node.y += Math.random();
  26004. }
  26005. else {
  26006. this._splitBranch(parentBranch.children[region]);
  26007. this._placeInTree(parentBranch.children[region],node);
  26008. }
  26009. break;
  26010. case 4: // place in branch
  26011. this._placeInTree(parentBranch.children[region],node);
  26012. break;
  26013. }
  26014. };
  26015. /**
  26016. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  26017. * after the split is complete.
  26018. *
  26019. * @param parentBranch
  26020. * @private
  26021. */
  26022. exports._splitBranch = function(parentBranch) {
  26023. // if the branch is shaded with a node, replace the node in the new subset.
  26024. var containedNode = null;
  26025. if (parentBranch.childrenCount == 1) {
  26026. containedNode = parentBranch.children.data;
  26027. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  26028. }
  26029. parentBranch.childrenCount = 4;
  26030. parentBranch.children.data = null;
  26031. this._insertRegion(parentBranch,"NW");
  26032. this._insertRegion(parentBranch,"NE");
  26033. this._insertRegion(parentBranch,"SW");
  26034. this._insertRegion(parentBranch,"SE");
  26035. if (containedNode != null) {
  26036. this._placeInTree(parentBranch,containedNode);
  26037. }
  26038. };
  26039. /**
  26040. * This function subdivides the region into four new segments.
  26041. * Specifically, this inserts a single new segment.
  26042. * It fills the children section of the parentBranch
  26043. *
  26044. * @param parentBranch
  26045. * @param region
  26046. * @param parentRange
  26047. * @private
  26048. */
  26049. exports._insertRegion = function(parentBranch, region) {
  26050. var minX,maxX,minY,maxY;
  26051. var childSize = 0.5 * parentBranch.size;
  26052. switch (region) {
  26053. case "NW":
  26054. minX = parentBranch.range.minX;
  26055. maxX = parentBranch.range.minX + childSize;
  26056. minY = parentBranch.range.minY;
  26057. maxY = parentBranch.range.minY + childSize;
  26058. break;
  26059. case "NE":
  26060. minX = parentBranch.range.minX + childSize;
  26061. maxX = parentBranch.range.maxX;
  26062. minY = parentBranch.range.minY;
  26063. maxY = parentBranch.range.minY + childSize;
  26064. break;
  26065. case "SW":
  26066. minX = parentBranch.range.minX;
  26067. maxX = parentBranch.range.minX + childSize;
  26068. minY = parentBranch.range.minY + childSize;
  26069. maxY = parentBranch.range.maxY;
  26070. break;
  26071. case "SE":
  26072. minX = parentBranch.range.minX + childSize;
  26073. maxX = parentBranch.range.maxX;
  26074. minY = parentBranch.range.minY + childSize;
  26075. maxY = parentBranch.range.maxY;
  26076. break;
  26077. }
  26078. parentBranch.children[region] = {
  26079. centerOfMass:{x:0,y:0},
  26080. mass:0,
  26081. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  26082. size: 0.5 * parentBranch.size,
  26083. calcSize: 2 * parentBranch.calcSize,
  26084. children: {data:null},
  26085. maxWidth: 0,
  26086. level: parentBranch.level+1,
  26087. childrenCount: 0
  26088. };
  26089. };
  26090. /**
  26091. * This function is for debugging purposed, it draws the tree.
  26092. *
  26093. * @param ctx
  26094. * @param color
  26095. * @private
  26096. */
  26097. exports._drawTree = function(ctx,color) {
  26098. if (this.barnesHutTree !== undefined) {
  26099. ctx.lineWidth = 1;
  26100. this._drawBranch(this.barnesHutTree.root,ctx,color);
  26101. }
  26102. };
  26103. /**
  26104. * This function is for debugging purposes. It draws the branches recursively.
  26105. *
  26106. * @param branch
  26107. * @param ctx
  26108. * @param color
  26109. * @private
  26110. */
  26111. exports._drawBranch = function(branch,ctx,color) {
  26112. if (color === undefined) {
  26113. color = "#FF0000";
  26114. }
  26115. if (branch.childrenCount == 4) {
  26116. this._drawBranch(branch.children.NW,ctx);
  26117. this._drawBranch(branch.children.NE,ctx);
  26118. this._drawBranch(branch.children.SE,ctx);
  26119. this._drawBranch(branch.children.SW,ctx);
  26120. }
  26121. ctx.strokeStyle = color;
  26122. ctx.beginPath();
  26123. ctx.moveTo(branch.range.minX,branch.range.minY);
  26124. ctx.lineTo(branch.range.maxX,branch.range.minY);
  26125. ctx.stroke();
  26126. ctx.beginPath();
  26127. ctx.moveTo(branch.range.maxX,branch.range.minY);
  26128. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  26129. ctx.stroke();
  26130. ctx.beginPath();
  26131. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  26132. ctx.lineTo(branch.range.minX,branch.range.maxY);
  26133. ctx.stroke();
  26134. ctx.beginPath();
  26135. ctx.moveTo(branch.range.minX,branch.range.maxY);
  26136. ctx.lineTo(branch.range.minX,branch.range.minY);
  26137. ctx.stroke();
  26138. /*
  26139. if (branch.mass > 0) {
  26140. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  26141. ctx.stroke();
  26142. }
  26143. */
  26144. };
  26145. /***/ },
  26146. /* 64 */
  26147. /***/ function(module, exports, __webpack_require__) {
  26148. /**
  26149. * Creation of the ClusterMixin var.
  26150. *
  26151. * This contains all the functions the Network object can use to employ clustering
  26152. */
  26153. /**
  26154. * This is only called in the constructor of the network object
  26155. *
  26156. */
  26157. exports.startWithClustering = function() {
  26158. // cluster if the data set is big
  26159. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  26160. // updates the lables after clustering
  26161. this.updateLabels();
  26162. // this is called here because if clusterin is disabled, the start and stabilize are called in
  26163. // the setData function.
  26164. if (this.stabilize) {
  26165. this._stabilize();
  26166. }
  26167. this.start();
  26168. };
  26169. /**
  26170. * This function clusters until the initialMaxNodes has been reached
  26171. *
  26172. * @param {Number} maxNumberOfNodes
  26173. * @param {Boolean} reposition
  26174. */
  26175. exports.clusterToFit = function(maxNumberOfNodes, reposition) {
  26176. var numberOfNodes = this.nodeIndices.length;
  26177. var maxLevels = 50;
  26178. var level = 0;
  26179. // we first cluster the hubs, then we pull in the outliers, repeat
  26180. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  26181. if (level % 3 == 0) {
  26182. this.forceAggregateHubs(true);
  26183. this.normalizeClusterLevels();
  26184. }
  26185. else {
  26186. this.increaseClusterLevel(); // this also includes a cluster normalization
  26187. }
  26188. numberOfNodes = this.nodeIndices.length;
  26189. level += 1;
  26190. }
  26191. // after the clustering we reposition the nodes to reduce the initial chaos
  26192. if (level > 0 && reposition == true) {
  26193. this.repositionNodes();
  26194. }
  26195. this._updateCalculationNodes();
  26196. };
  26197. /**
  26198. * This function can be called to open up a specific cluster. It is only called by
  26199. * It will unpack the cluster back one level.
  26200. *
  26201. * @param node | Node object: cluster to open.
  26202. */
  26203. exports.openCluster = function(node) {
  26204. var isMovingBeforeClustering = this.moving;
  26205. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  26206. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  26207. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  26208. this._addSector(node);
  26209. var level = 0;
  26210. // we decluster until we reach a decent number of nodes
  26211. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  26212. this.decreaseClusterLevel();
  26213. level += 1;
  26214. }
  26215. }
  26216. else {
  26217. this._expandClusterNode(node,false,true);
  26218. // update the index list, dynamic edges and labels
  26219. this._updateNodeIndexList();
  26220. this._updateDynamicEdges();
  26221. this._updateCalculationNodes();
  26222. this.updateLabels();
  26223. }
  26224. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  26225. if (this.moving != isMovingBeforeClustering) {
  26226. this.start();
  26227. }
  26228. };
  26229. /**
  26230. * This calls the updateClustes with default arguments
  26231. */
  26232. exports.updateClustersDefault = function() {
  26233. if (this.constants.clustering.enabled == true) {
  26234. this.updateClusters(0,false,false);
  26235. }
  26236. };
  26237. /**
  26238. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  26239. * be clustered with their connected node. This can be repeated as many times as needed.
  26240. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  26241. */
  26242. exports.increaseClusterLevel = function() {
  26243. this.updateClusters(-1,false,true);
  26244. };
  26245. /**
  26246. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  26247. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  26248. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  26249. */
  26250. exports.decreaseClusterLevel = function() {
  26251. this.updateClusters(1,false,true);
  26252. };
  26253. /**
  26254. * This is the main clustering function. It clusters and declusters on zoom or forced
  26255. * This function clusters on zoom, it can be called with a predefined zoom direction
  26256. * If out, check if we can form clusters, if in, check if we can open clusters.
  26257. * This function is only called from _zoom()
  26258. *
  26259. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  26260. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  26261. * @param {Boolean} force | enabled or disable forcing
  26262. * @param {Boolean} doNotStart | if true do not call start
  26263. *
  26264. */
  26265. exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) {
  26266. var isMovingBeforeClustering = this.moving;
  26267. var amountOfNodes = this.nodeIndices.length;
  26268. // on zoom out collapse the sector if the scale is at the level the sector was made
  26269. if (this.previousScale > this.scale && zoomDirection == 0) {
  26270. this._collapseSector();
  26271. }
  26272. // check if we zoom in or out
  26273. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  26274. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  26275. // outer nodes determines if it is being clustered
  26276. this._formClusters(force);
  26277. }
  26278. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  26279. if (force == true) {
  26280. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  26281. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  26282. this._openClusters(recursive,force);
  26283. }
  26284. else {
  26285. // if a cluster takes up a set percentage of the active window
  26286. this._openClustersBySize();
  26287. }
  26288. }
  26289. this._updateNodeIndexList();
  26290. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  26291. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  26292. this._aggregateHubs(force);
  26293. this._updateNodeIndexList();
  26294. }
  26295. // we now reduce chains.
  26296. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  26297. this.handleChains();
  26298. this._updateNodeIndexList();
  26299. }
  26300. this.previousScale = this.scale;
  26301. // rest of the update the index list, dynamic edges and labels
  26302. this._updateDynamicEdges();
  26303. this.updateLabels();
  26304. // if a cluster was formed, we increase the clusterSession
  26305. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  26306. this.clusterSession += 1;
  26307. // if clusters have been made, we normalize the cluster level
  26308. this.normalizeClusterLevels();
  26309. }
  26310. if (doNotStart == false || doNotStart === undefined) {
  26311. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  26312. if (this.moving != isMovingBeforeClustering) {
  26313. this.start();
  26314. }
  26315. }
  26316. this._updateCalculationNodes();
  26317. };
  26318. /**
  26319. * This function handles the chains. It is called on every updateClusters().
  26320. */
  26321. exports.handleChains = function() {
  26322. // after clustering we check how many chains there are
  26323. var chainPercentage = this._getChainFraction();
  26324. if (chainPercentage > this.constants.clustering.chainThreshold) {
  26325. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  26326. }
  26327. };
  26328. /**
  26329. * this functions starts clustering by hubs
  26330. * The minimum hub threshold is set globally
  26331. *
  26332. * @private
  26333. */
  26334. exports._aggregateHubs = function(force) {
  26335. this._getHubSize();
  26336. this._formClustersByHub(force,false);
  26337. };
  26338. /**
  26339. * This function is fired by keypress. It forces hubs to form.
  26340. *
  26341. */
  26342. exports.forceAggregateHubs = function(doNotStart) {
  26343. var isMovingBeforeClustering = this.moving;
  26344. var amountOfNodes = this.nodeIndices.length;
  26345. this._aggregateHubs(true);
  26346. // update the index list, dynamic edges and labels
  26347. this._updateNodeIndexList();
  26348. this._updateDynamicEdges();
  26349. this.updateLabels();
  26350. // if a cluster was formed, we increase the clusterSession
  26351. if (this.nodeIndices.length != amountOfNodes) {
  26352. this.clusterSession += 1;
  26353. }
  26354. if (doNotStart == false || doNotStart === undefined) {
  26355. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  26356. if (this.moving != isMovingBeforeClustering) {
  26357. this.start();
  26358. }
  26359. }
  26360. };
  26361. /**
  26362. * If a cluster takes up more than a set percentage of the screen, open the cluster
  26363. *
  26364. * @private
  26365. */
  26366. exports._openClustersBySize = function() {
  26367. for (var nodeId in this.nodes) {
  26368. if (this.nodes.hasOwnProperty(nodeId)) {
  26369. var node = this.nodes[nodeId];
  26370. if (node.inView() == true) {
  26371. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  26372. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  26373. this.openCluster(node);
  26374. }
  26375. }
  26376. }
  26377. }
  26378. };
  26379. /**
  26380. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  26381. * has to be opened based on the current zoom level.
  26382. *
  26383. * @private
  26384. */
  26385. exports._openClusters = function(recursive,force) {
  26386. for (var i = 0; i < this.nodeIndices.length; i++) {
  26387. var node = this.nodes[this.nodeIndices[i]];
  26388. this._expandClusterNode(node,recursive,force);
  26389. this._updateCalculationNodes();
  26390. }
  26391. };
  26392. /**
  26393. * This function checks if a node has to be opened. This is done by checking the zoom level.
  26394. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  26395. * This recursive behaviour is optional and can be set by the recursive argument.
  26396. *
  26397. * @param {Node} parentNode | to check for cluster and expand
  26398. * @param {Boolean} recursive | enabled or disable recursive calling
  26399. * @param {Boolean} force | enabled or disable forcing
  26400. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  26401. * @private
  26402. */
  26403. exports._expandClusterNode = function(parentNode, recursive, force, openAll) {
  26404. // first check if node is a cluster
  26405. if (parentNode.clusterSize > 1) {
  26406. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  26407. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  26408. openAll = true;
  26409. }
  26410. recursive = openAll ? true : recursive;
  26411. // if the last child has been added on a smaller scale than current scale decluster
  26412. if (parentNode.formationScale < this.scale || force == true) {
  26413. // we will check if any of the contained child nodes should be removed from the cluster
  26414. for (var containedNodeId in parentNode.containedNodes) {
  26415. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  26416. var childNode = parentNode.containedNodes[containedNodeId];
  26417. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  26418. // the largest cluster is the one that comes from outside
  26419. if (force == true) {
  26420. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  26421. || openAll) {
  26422. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  26423. }
  26424. }
  26425. else {
  26426. if (this._nodeInActiveArea(parentNode)) {
  26427. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  26428. }
  26429. }
  26430. }
  26431. }
  26432. }
  26433. }
  26434. };
  26435. /**
  26436. * ONLY CALLED FROM _expandClusterNode
  26437. *
  26438. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  26439. * the child node from the parent contained_node object and put it back into the global nodes object.
  26440. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  26441. *
  26442. * @param {Node} parentNode | the parent node
  26443. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  26444. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  26445. * With force and recursive both true, the entire cluster is unpacked
  26446. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  26447. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  26448. * @private
  26449. */
  26450. exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) {
  26451. var childNode = parentNode.containedNodes[containedNodeId];
  26452. // if child node has been added on smaller scale than current, kick out
  26453. if (childNode.formationScale < this.scale || force == true) {
  26454. // unselect all selected items
  26455. this._unselectAll();
  26456. // put the child node back in the global nodes object
  26457. this.nodes[containedNodeId] = childNode;
  26458. // release the contained edges from this childNode back into the global edges
  26459. this._releaseContainedEdges(parentNode,childNode);
  26460. // reconnect rerouted edges to the childNode
  26461. this._connectEdgeBackToChild(parentNode,childNode);
  26462. // validate all edges in dynamicEdges
  26463. this._validateEdges(parentNode);
  26464. // undo the changes from the clustering operation on the parent node
  26465. parentNode.options.mass -= childNode.options.mass;
  26466. parentNode.clusterSize -= childNode.clusterSize;
  26467. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*(parentNode.clusterSize-1));
  26468. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  26469. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  26470. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  26471. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  26472. // remove node from the list
  26473. delete parentNode.containedNodes[containedNodeId];
  26474. // check if there are other childs with this clusterSession in the parent.
  26475. var othersPresent = false;
  26476. for (var childNodeId in parentNode.containedNodes) {
  26477. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  26478. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  26479. othersPresent = true;
  26480. break;
  26481. }
  26482. }
  26483. }
  26484. // if there are no others, remove the cluster session from the list
  26485. if (othersPresent == false) {
  26486. parentNode.clusterSessions.pop();
  26487. }
  26488. this._repositionBezierNodes(childNode);
  26489. // this._repositionBezierNodes(parentNode);
  26490. // remove the clusterSession from the child node
  26491. childNode.clusterSession = 0;
  26492. // recalculate the size of the node on the next time the node is rendered
  26493. parentNode.clearSizeCache();
  26494. // restart the simulation to reorganise all nodes
  26495. this.moving = true;
  26496. }
  26497. // check if a further expansion step is possible if recursivity is enabled
  26498. if (recursive == true) {
  26499. this._expandClusterNode(childNode,recursive,force,openAll);
  26500. }
  26501. };
  26502. /**
  26503. * position the bezier nodes at the center of the edges
  26504. *
  26505. * @param node
  26506. * @private
  26507. */
  26508. exports._repositionBezierNodes = function(node) {
  26509. for (var i = 0; i < node.dynamicEdges.length; i++) {
  26510. node.dynamicEdges[i].positionBezierNode();
  26511. }
  26512. };
  26513. /**
  26514. * This function checks if any nodes at the end of their trees have edges below a threshold length
  26515. * This function is called only from updateClusters()
  26516. * forceLevelCollapse ignores the length of the edge and collapses one level
  26517. * This means that a node with only one edge will be clustered with its connected node
  26518. *
  26519. * @private
  26520. * @param {Boolean} force
  26521. */
  26522. exports._formClusters = function(force) {
  26523. if (force == false) {
  26524. this._formClustersByZoom();
  26525. }
  26526. else {
  26527. this._forceClustersByZoom();
  26528. }
  26529. };
  26530. /**
  26531. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  26532. *
  26533. * @private
  26534. */
  26535. exports._formClustersByZoom = function() {
  26536. var dx,dy,length,
  26537. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  26538. // check if any edges are shorter than minLength and start the clustering
  26539. // the clustering favours the node with the larger mass
  26540. for (var edgeId in this.edges) {
  26541. if (this.edges.hasOwnProperty(edgeId)) {
  26542. var edge = this.edges[edgeId];
  26543. if (edge.connected) {
  26544. if (edge.toId != edge.fromId) {
  26545. dx = (edge.to.x - edge.from.x);
  26546. dy = (edge.to.y - edge.from.y);
  26547. length = Math.sqrt(dx * dx + dy * dy);
  26548. if (length < minLength) {
  26549. // first check which node is larger
  26550. var parentNode = edge.from;
  26551. var childNode = edge.to;
  26552. if (edge.to.options.mass > edge.from.options.mass) {
  26553. parentNode = edge.to;
  26554. childNode = edge.from;
  26555. }
  26556. if (childNode.dynamicEdgesLength == 1) {
  26557. this._addToCluster(parentNode,childNode,false);
  26558. }
  26559. else if (parentNode.dynamicEdgesLength == 1) {
  26560. this._addToCluster(childNode,parentNode,false);
  26561. }
  26562. }
  26563. }
  26564. }
  26565. }
  26566. }
  26567. };
  26568. /**
  26569. * This function forces the network to cluster all nodes with only one connecting edge to their
  26570. * connected node.
  26571. *
  26572. * @private
  26573. */
  26574. exports._forceClustersByZoom = function() {
  26575. for (var nodeId in this.nodes) {
  26576. // another node could have absorbed this child.
  26577. if (this.nodes.hasOwnProperty(nodeId)) {
  26578. var childNode = this.nodes[nodeId];
  26579. // the edges can be swallowed by another decrease
  26580. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  26581. var edge = childNode.dynamicEdges[0];
  26582. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  26583. // group to the largest node
  26584. if (childNode.id != parentNode.id) {
  26585. if (parentNode.options.mass > childNode.options.mass) {
  26586. this._addToCluster(parentNode,childNode,true);
  26587. }
  26588. else {
  26589. this._addToCluster(childNode,parentNode,true);
  26590. }
  26591. }
  26592. }
  26593. }
  26594. }
  26595. };
  26596. /**
  26597. * To keep the nodes of roughly equal size we normalize the cluster levels.
  26598. * This function clusters a node to its smallest connected neighbour.
  26599. *
  26600. * @param node
  26601. * @private
  26602. */
  26603. exports._clusterToSmallestNeighbour = function(node) {
  26604. var smallestNeighbour = -1;
  26605. var smallestNeighbourNode = null;
  26606. for (var i = 0; i < node.dynamicEdges.length; i++) {
  26607. if (node.dynamicEdges[i] !== undefined) {
  26608. var neighbour = null;
  26609. if (node.dynamicEdges[i].fromId != node.id) {
  26610. neighbour = node.dynamicEdges[i].from;
  26611. }
  26612. else if (node.dynamicEdges[i].toId != node.id) {
  26613. neighbour = node.dynamicEdges[i].to;
  26614. }
  26615. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  26616. smallestNeighbour = neighbour.clusterSessions.length;
  26617. smallestNeighbourNode = neighbour;
  26618. }
  26619. }
  26620. }
  26621. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  26622. this._addToCluster(neighbour, node, true);
  26623. }
  26624. };
  26625. /**
  26626. * This function forms clusters from hubs, it loops over all nodes
  26627. *
  26628. * @param {Boolean} force | Disregard zoom level
  26629. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  26630. * @private
  26631. */
  26632. exports._formClustersByHub = function(force, onlyEqual) {
  26633. // we loop over all nodes in the list
  26634. for (var nodeId in this.nodes) {
  26635. // we check if it is still available since it can be used by the clustering in this loop
  26636. if (this.nodes.hasOwnProperty(nodeId)) {
  26637. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  26638. }
  26639. }
  26640. };
  26641. /**
  26642. * This function forms a cluster from a specific preselected hub node
  26643. *
  26644. * @param {Node} hubNode | the node we will cluster as a hub
  26645. * @param {Boolean} force | Disregard zoom level
  26646. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  26647. * @param {Number} [absorptionSizeOffset] |
  26648. * @private
  26649. */
  26650. exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  26651. if (absorptionSizeOffset === undefined) {
  26652. absorptionSizeOffset = 0;
  26653. }
  26654. // we decide if the node is a hub
  26655. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  26656. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  26657. // initialize variables
  26658. var dx,dy,length;
  26659. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  26660. var allowCluster = false;
  26661. // we create a list of edges because the dynamicEdges change over the course of this loop
  26662. var edgesIdarray = [];
  26663. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  26664. for (var j = 0; j < amountOfInitialEdges; j++) {
  26665. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  26666. }
  26667. // if the hub clustering is not forces, we check if one of the edges connected
  26668. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  26669. if (force == false) {
  26670. allowCluster = false;
  26671. for (j = 0; j < amountOfInitialEdges; j++) {
  26672. var edge = this.edges[edgesIdarray[j]];
  26673. if (edge !== undefined) {
  26674. if (edge.connected) {
  26675. if (edge.toId != edge.fromId) {
  26676. dx = (edge.to.x - edge.from.x);
  26677. dy = (edge.to.y - edge.from.y);
  26678. length = Math.sqrt(dx * dx + dy * dy);
  26679. if (length < minLength) {
  26680. allowCluster = true;
  26681. break;
  26682. }
  26683. }
  26684. }
  26685. }
  26686. }
  26687. }
  26688. // start the clustering if allowed
  26689. if ((!force && allowCluster) || force) {
  26690. // we loop over all edges INITIALLY connected to this hub
  26691. for (j = 0; j < amountOfInitialEdges; j++) {
  26692. edge = this.edges[edgesIdarray[j]];
  26693. // the edge can be clustered by this function in a previous loop
  26694. if (edge !== undefined) {
  26695. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  26696. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  26697. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  26698. (childNode.id != hubNode.id)) {
  26699. this._addToCluster(hubNode,childNode,force);
  26700. }
  26701. }
  26702. }
  26703. }
  26704. }
  26705. };
  26706. /**
  26707. * This function adds the child node to the parent node, creating a cluster if it is not already.
  26708. *
  26709. * @param {Node} parentNode | this is the node that will house the child node
  26710. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  26711. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  26712. * @private
  26713. */
  26714. exports._addToCluster = function(parentNode, childNode, force) {
  26715. // join child node in the parent node
  26716. parentNode.containedNodes[childNode.id] = childNode;
  26717. // manage all the edges connected to the child and parent nodes
  26718. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  26719. var edge = childNode.dynamicEdges[i];
  26720. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  26721. this._addToContainedEdges(parentNode,childNode,edge);
  26722. }
  26723. else {
  26724. this._connectEdgeToCluster(parentNode,childNode,edge);
  26725. }
  26726. }
  26727. // a contained node has no dynamic edges.
  26728. childNode.dynamicEdges = [];
  26729. // remove circular edges from clusters
  26730. this._containCircularEdgesFromNode(parentNode,childNode);
  26731. // remove the childNode from the global nodes object
  26732. delete this.nodes[childNode.id];
  26733. // update the properties of the child and parent
  26734. var massBefore = parentNode.options.mass;
  26735. childNode.clusterSession = this.clusterSession;
  26736. parentNode.options.mass += childNode.options.mass;
  26737. parentNode.clusterSize += childNode.clusterSize;
  26738. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  26739. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  26740. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  26741. parentNode.clusterSessions.push(this.clusterSession);
  26742. }
  26743. // forced clusters only open from screen size and double tap
  26744. if (force == true) {
  26745. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  26746. parentNode.formationScale = 0;
  26747. }
  26748. else {
  26749. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  26750. }
  26751. // recalculate the size of the node on the next time the node is rendered
  26752. parentNode.clearSizeCache();
  26753. // set the pop-out scale for the childnode
  26754. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  26755. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  26756. childNode.clearVelocity();
  26757. // the mass has altered, preservation of energy dictates the velocity to be updated
  26758. parentNode.updateVelocity(massBefore);
  26759. // restart the simulation to reorganise all nodes
  26760. this.moving = true;
  26761. };
  26762. /**
  26763. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  26764. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  26765. * It has to be called if a level is collapsed. It is called by _formClusters().
  26766. * @private
  26767. */
  26768. exports._updateDynamicEdges = function() {
  26769. for (var i = 0; i < this.nodeIndices.length; i++) {
  26770. var node = this.nodes[this.nodeIndices[i]];
  26771. node.dynamicEdgesLength = node.dynamicEdges.length;
  26772. // this corrects for multiple edges pointing at the same other node
  26773. var correction = 0;
  26774. if (node.dynamicEdgesLength > 1) {
  26775. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  26776. var edgeToId = node.dynamicEdges[j].toId;
  26777. var edgeFromId = node.dynamicEdges[j].fromId;
  26778. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  26779. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  26780. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  26781. correction += 1;
  26782. }
  26783. }
  26784. }
  26785. }
  26786. node.dynamicEdgesLength -= correction;
  26787. }
  26788. };
  26789. /**
  26790. * This adds an edge from the childNode to the contained edges of the parent node
  26791. *
  26792. * @param parentNode | Node object
  26793. * @param childNode | Node object
  26794. * @param edge | Edge object
  26795. * @private
  26796. */
  26797. exports._addToContainedEdges = function(parentNode, childNode, edge) {
  26798. // create an array object if it does not yet exist for this childNode
  26799. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  26800. parentNode.containedEdges[childNode.id] = []
  26801. }
  26802. // add this edge to the list
  26803. parentNode.containedEdges[childNode.id].push(edge);
  26804. // remove the edge from the global edges object
  26805. delete this.edges[edge.id];
  26806. // remove the edge from the parent object
  26807. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26808. if (parentNode.dynamicEdges[i].id == edge.id) {
  26809. parentNode.dynamicEdges.splice(i,1);
  26810. break;
  26811. }
  26812. }
  26813. };
  26814. /**
  26815. * This function connects an edge that was connected to a child node to the parent node.
  26816. * It keeps track of which nodes it has been connected to with the originalId array.
  26817. *
  26818. * @param {Node} parentNode | Node object
  26819. * @param {Node} childNode | Node object
  26820. * @param {Edge} edge | Edge object
  26821. * @private
  26822. */
  26823. exports._connectEdgeToCluster = function(parentNode, childNode, edge) {
  26824. // handle circular edges
  26825. if (edge.toId == edge.fromId) {
  26826. this._addToContainedEdges(parentNode, childNode, edge);
  26827. }
  26828. else {
  26829. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  26830. edge.originalToId.push(childNode.id);
  26831. edge.to = parentNode;
  26832. edge.toId = parentNode.id;
  26833. }
  26834. else { // edge connected to other node with the "from" side
  26835. edge.originalFromId.push(childNode.id);
  26836. edge.from = parentNode;
  26837. edge.fromId = parentNode.id;
  26838. }
  26839. this._addToReroutedEdges(parentNode,childNode,edge);
  26840. }
  26841. };
  26842. /**
  26843. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  26844. * these edges inside of the cluster.
  26845. *
  26846. * @param parentNode
  26847. * @param childNode
  26848. * @private
  26849. */
  26850. exports._containCircularEdgesFromNode = function(parentNode, childNode) {
  26851. // manage all the edges connected to the child and parent nodes
  26852. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26853. var edge = parentNode.dynamicEdges[i];
  26854. // handle circular edges
  26855. if (edge.toId == edge.fromId) {
  26856. this._addToContainedEdges(parentNode, childNode, edge);
  26857. }
  26858. }
  26859. };
  26860. /**
  26861. * This adds an edge from the childNode to the rerouted edges of the parent node
  26862. *
  26863. * @param parentNode | Node object
  26864. * @param childNode | Node object
  26865. * @param edge | Edge object
  26866. * @private
  26867. */
  26868. exports._addToReroutedEdges = function(parentNode, childNode, edge) {
  26869. // create an array object if it does not yet exist for this childNode
  26870. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  26871. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  26872. parentNode.reroutedEdges[childNode.id] = [];
  26873. }
  26874. parentNode.reroutedEdges[childNode.id].push(edge);
  26875. // this edge becomes part of the dynamicEdges of the cluster node
  26876. parentNode.dynamicEdges.push(edge);
  26877. };
  26878. /**
  26879. * This function connects an edge that was connected to a cluster node back to the child node.
  26880. *
  26881. * @param parentNode | Node object
  26882. * @param childNode | Node object
  26883. * @private
  26884. */
  26885. exports._connectEdgeBackToChild = function(parentNode, childNode) {
  26886. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  26887. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  26888. var edge = parentNode.reroutedEdges[childNode.id][i];
  26889. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  26890. edge.originalFromId.pop();
  26891. edge.fromId = childNode.id;
  26892. edge.from = childNode;
  26893. }
  26894. else {
  26895. edge.originalToId.pop();
  26896. edge.toId = childNode.id;
  26897. edge.to = childNode;
  26898. }
  26899. // append this edge to the list of edges connecting to the childnode
  26900. childNode.dynamicEdges.push(edge);
  26901. // remove the edge from the parent object
  26902. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  26903. if (parentNode.dynamicEdges[j].id == edge.id) {
  26904. parentNode.dynamicEdges.splice(j,1);
  26905. break;
  26906. }
  26907. }
  26908. }
  26909. // remove the entry from the rerouted edges
  26910. delete parentNode.reroutedEdges[childNode.id];
  26911. }
  26912. };
  26913. /**
  26914. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  26915. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  26916. * parentNode
  26917. *
  26918. * @param parentNode | Node object
  26919. * @private
  26920. */
  26921. exports._validateEdges = function(parentNode) {
  26922. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26923. var edge = parentNode.dynamicEdges[i];
  26924. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  26925. parentNode.dynamicEdges.splice(i,1);
  26926. }
  26927. }
  26928. };
  26929. /**
  26930. * This function released the contained edges back into the global domain and puts them back into the
  26931. * dynamic edges of both parent and child.
  26932. *
  26933. * @param {Node} parentNode |
  26934. * @param {Node} childNode |
  26935. * @private
  26936. */
  26937. exports._releaseContainedEdges = function(parentNode, childNode) {
  26938. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  26939. var edge = parentNode.containedEdges[childNode.id][i];
  26940. // put the edge back in the global edges object
  26941. this.edges[edge.id] = edge;
  26942. // put the edge back in the dynamic edges of the child and parent
  26943. childNode.dynamicEdges.push(edge);
  26944. parentNode.dynamicEdges.push(edge);
  26945. }
  26946. // remove the entry from the contained edges
  26947. delete parentNode.containedEdges[childNode.id];
  26948. };
  26949. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  26950. /**
  26951. * This updates the node labels for all nodes (for debugging purposes)
  26952. */
  26953. exports.updateLabels = function() {
  26954. var nodeId;
  26955. // update node labels
  26956. for (nodeId in this.nodes) {
  26957. if (this.nodes.hasOwnProperty(nodeId)) {
  26958. var node = this.nodes[nodeId];
  26959. if (node.clusterSize > 1) {
  26960. node.label = "[".concat(String(node.clusterSize),"]");
  26961. }
  26962. }
  26963. }
  26964. // update node labels
  26965. for (nodeId in this.nodes) {
  26966. if (this.nodes.hasOwnProperty(nodeId)) {
  26967. node = this.nodes[nodeId];
  26968. if (node.clusterSize == 1) {
  26969. if (node.originalLabel !== undefined) {
  26970. node.label = node.originalLabel;
  26971. }
  26972. else {
  26973. node.label = String(node.id);
  26974. }
  26975. }
  26976. }
  26977. }
  26978. // /* Debug Override */
  26979. // for (nodeId in this.nodes) {
  26980. // if (this.nodes.hasOwnProperty(nodeId)) {
  26981. // node = this.nodes[nodeId];
  26982. // node.label = String(node.level);
  26983. // }
  26984. // }
  26985. };
  26986. /**
  26987. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  26988. * if the rest of the nodes are already a few cluster levels in.
  26989. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  26990. * clustered enough to the clusterToSmallestNeighbours function.
  26991. */
  26992. exports.normalizeClusterLevels = function() {
  26993. var maxLevel = 0;
  26994. var minLevel = 1e9;
  26995. var clusterLevel = 0;
  26996. var nodeId;
  26997. // we loop over all nodes in the list
  26998. for (nodeId in this.nodes) {
  26999. if (this.nodes.hasOwnProperty(nodeId)) {
  27000. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  27001. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  27002. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  27003. }
  27004. }
  27005. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  27006. var amountOfNodes = this.nodeIndices.length;
  27007. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  27008. // we loop over all nodes in the list
  27009. for (nodeId in this.nodes) {
  27010. if (this.nodes.hasOwnProperty(nodeId)) {
  27011. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  27012. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  27013. }
  27014. }
  27015. }
  27016. this._updateNodeIndexList();
  27017. this._updateDynamicEdges();
  27018. // if a cluster was formed, we increase the clusterSession
  27019. if (this.nodeIndices.length != amountOfNodes) {
  27020. this.clusterSession += 1;
  27021. }
  27022. }
  27023. };
  27024. /**
  27025. * This function determines if the cluster we want to decluster is in the active area
  27026. * this means around the zoom center
  27027. *
  27028. * @param {Node} node
  27029. * @returns {boolean}
  27030. * @private
  27031. */
  27032. exports._nodeInActiveArea = function(node) {
  27033. return (
  27034. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  27035. &&
  27036. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  27037. )
  27038. };
  27039. /**
  27040. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  27041. * It puts large clusters away from the center and randomizes the order.
  27042. *
  27043. */
  27044. exports.repositionNodes = function() {
  27045. for (var i = 0; i < this.nodeIndices.length; i++) {
  27046. var node = this.nodes[this.nodeIndices[i]];
  27047. if ((node.xFixed == false || node.yFixed == false)) {
  27048. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass);
  27049. var angle = 2 * Math.PI * Math.random();
  27050. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  27051. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  27052. this._repositionBezierNodes(node);
  27053. }
  27054. }
  27055. };
  27056. /**
  27057. * We determine how many connections denote an important hub.
  27058. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  27059. *
  27060. * @private
  27061. */
  27062. exports._getHubSize = function() {
  27063. var average = 0;
  27064. var averageSquared = 0;
  27065. var hubCounter = 0;
  27066. var largestHub = 0;
  27067. for (var i = 0; i < this.nodeIndices.length; i++) {
  27068. var node = this.nodes[this.nodeIndices[i]];
  27069. if (node.dynamicEdgesLength > largestHub) {
  27070. largestHub = node.dynamicEdgesLength;
  27071. }
  27072. average += node.dynamicEdgesLength;
  27073. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  27074. hubCounter += 1;
  27075. }
  27076. average = average / hubCounter;
  27077. averageSquared = averageSquared / hubCounter;
  27078. var variance = averageSquared - Math.pow(average,2);
  27079. var standardDeviation = Math.sqrt(variance);
  27080. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  27081. // always have at least one to cluster
  27082. if (this.hubThreshold > largestHub) {
  27083. this.hubThreshold = largestHub;
  27084. }
  27085. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  27086. // console.log("hubThreshold:",this.hubThreshold);
  27087. };
  27088. /**
  27089. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  27090. * with this amount we can cluster specifically on these chains.
  27091. *
  27092. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  27093. * @private
  27094. */
  27095. exports._reduceAmountOfChains = function(fraction) {
  27096. this.hubThreshold = 2;
  27097. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  27098. for (var nodeId in this.nodes) {
  27099. if (this.nodes.hasOwnProperty(nodeId)) {
  27100. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  27101. if (reduceAmount > 0) {
  27102. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  27103. reduceAmount -= 1;
  27104. }
  27105. }
  27106. }
  27107. }
  27108. };
  27109. /**
  27110. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  27111. * with this amount we can cluster specifically on these chains.
  27112. *
  27113. * @private
  27114. */
  27115. exports._getChainFraction = function() {
  27116. var chains = 0;
  27117. var total = 0;
  27118. for (var nodeId in this.nodes) {
  27119. if (this.nodes.hasOwnProperty(nodeId)) {
  27120. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  27121. chains += 1;
  27122. }
  27123. total += 1;
  27124. }
  27125. }
  27126. return chains/total;
  27127. };
  27128. /***/ },
  27129. /* 65 */
  27130. /***/ function(module, exports, __webpack_require__) {
  27131. var util = __webpack_require__(1);
  27132. var Node = __webpack_require__(56);
  27133. /**
  27134. * Creation of the SectorMixin var.
  27135. *
  27136. * This contains all the functions the Network object can use to employ the sector system.
  27137. * The sector system is always used by Network, though the benefits only apply to the use of clustering.
  27138. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  27139. */
  27140. /**
  27141. * This function is only called by the setData function of the Network object.
  27142. * This loads the global references into the active sector. This initializes the sector.
  27143. *
  27144. * @private
  27145. */
  27146. exports._putDataInSector = function() {
  27147. this.sectors["active"][this._sector()].nodes = this.nodes;
  27148. this.sectors["active"][this._sector()].edges = this.edges;
  27149. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  27150. };
  27151. /**
  27152. * /**
  27153. * This function sets the global references to nodes, edges and nodeIndices back to
  27154. * those of the supplied (active) sector. If a type is defined, do the specific type
  27155. *
  27156. * @param {String} sectorId
  27157. * @param {String} [sectorType] | "active" or "frozen"
  27158. * @private
  27159. */
  27160. exports._switchToSector = function(sectorId, sectorType) {
  27161. if (sectorType === undefined || sectorType == "active") {
  27162. this._switchToActiveSector(sectorId);
  27163. }
  27164. else {
  27165. this._switchToFrozenSector(sectorId);
  27166. }
  27167. };
  27168. /**
  27169. * This function sets the global references to nodes, edges and nodeIndices back to
  27170. * those of the supplied active sector.
  27171. *
  27172. * @param sectorId
  27173. * @private
  27174. */
  27175. exports._switchToActiveSector = function(sectorId) {
  27176. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  27177. this.nodes = this.sectors["active"][sectorId]["nodes"];
  27178. this.edges = this.sectors["active"][sectorId]["edges"];
  27179. };
  27180. /**
  27181. * This function sets the global references to nodes, edges and nodeIndices back to
  27182. * those of the supplied active sector.
  27183. *
  27184. * @private
  27185. */
  27186. exports._switchToSupportSector = function() {
  27187. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  27188. this.nodes = this.sectors["support"]["nodes"];
  27189. this.edges = this.sectors["support"]["edges"];
  27190. };
  27191. /**
  27192. * This function sets the global references to nodes, edges and nodeIndices back to
  27193. * those of the supplied frozen sector.
  27194. *
  27195. * @param sectorId
  27196. * @private
  27197. */
  27198. exports._switchToFrozenSector = function(sectorId) {
  27199. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  27200. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  27201. this.edges = this.sectors["frozen"][sectorId]["edges"];
  27202. };
  27203. /**
  27204. * This function sets the global references to nodes, edges and nodeIndices back to
  27205. * those of the currently active sector.
  27206. *
  27207. * @private
  27208. */
  27209. exports._loadLatestSector = function() {
  27210. this._switchToSector(this._sector());
  27211. };
  27212. /**
  27213. * This function returns the currently active sector Id
  27214. *
  27215. * @returns {String}
  27216. * @private
  27217. */
  27218. exports._sector = function() {
  27219. return this.activeSector[this.activeSector.length-1];
  27220. };
  27221. /**
  27222. * This function returns the previously active sector Id
  27223. *
  27224. * @returns {String}
  27225. * @private
  27226. */
  27227. exports._previousSector = function() {
  27228. if (this.activeSector.length > 1) {
  27229. return this.activeSector[this.activeSector.length-2];
  27230. }
  27231. else {
  27232. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  27233. }
  27234. };
  27235. /**
  27236. * We add the active sector at the end of the this.activeSector array
  27237. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  27238. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  27239. *
  27240. * @param newId
  27241. * @private
  27242. */
  27243. exports._setActiveSector = function(newId) {
  27244. this.activeSector.push(newId);
  27245. };
  27246. /**
  27247. * We remove the currently active sector id from the active sector stack. This happens when
  27248. * we reactivate the previously active sector
  27249. *
  27250. * @private
  27251. */
  27252. exports._forgetLastSector = function() {
  27253. this.activeSector.pop();
  27254. };
  27255. /**
  27256. * This function creates a new active sector with the supplied newId. This newId
  27257. * is the expanding node id.
  27258. *
  27259. * @param {String} newId | Id of the new active sector
  27260. * @private
  27261. */
  27262. exports._createNewSector = function(newId) {
  27263. // create the new sector
  27264. this.sectors["active"][newId] = {"nodes":{},
  27265. "edges":{},
  27266. "nodeIndices":[],
  27267. "formationScale": this.scale,
  27268. "drawingNode": undefined};
  27269. // create the new sector render node. This gives visual feedback that you are in a new sector.
  27270. this.sectors["active"][newId]['drawingNode'] = new Node(
  27271. {id:newId,
  27272. color: {
  27273. background: "#eaefef",
  27274. border: "495c5e"
  27275. }
  27276. },{},{},this.constants);
  27277. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  27278. };
  27279. /**
  27280. * This function removes the currently active sector. This is called when we create a new
  27281. * active sector.
  27282. *
  27283. * @param {String} sectorId | Id of the active sector that will be removed
  27284. * @private
  27285. */
  27286. exports._deleteActiveSector = function(sectorId) {
  27287. delete this.sectors["active"][sectorId];
  27288. };
  27289. /**
  27290. * This function removes the currently active sector. This is called when we reactivate
  27291. * the previously active sector.
  27292. *
  27293. * @param {String} sectorId | Id of the active sector that will be removed
  27294. * @private
  27295. */
  27296. exports._deleteFrozenSector = function(sectorId) {
  27297. delete this.sectors["frozen"][sectorId];
  27298. };
  27299. /**
  27300. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  27301. * We copy the references, then delete the active entree.
  27302. *
  27303. * @param sectorId
  27304. * @private
  27305. */
  27306. exports._freezeSector = function(sectorId) {
  27307. // we move the set references from the active to the frozen stack.
  27308. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  27309. // we have moved the sector data into the frozen set, we now remove it from the active set
  27310. this._deleteActiveSector(sectorId);
  27311. };
  27312. /**
  27313. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  27314. * object to the "active" object.
  27315. *
  27316. * @param sectorId
  27317. * @private
  27318. */
  27319. exports._activateSector = function(sectorId) {
  27320. // we move the set references from the frozen to the active stack.
  27321. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  27322. // we have moved the sector data into the active set, we now remove it from the frozen stack
  27323. this._deleteFrozenSector(sectorId);
  27324. };
  27325. /**
  27326. * This function merges the data from the currently active sector with a frozen sector. This is used
  27327. * in the process of reverting back to the previously active sector.
  27328. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  27329. * upon the creation of a new active sector.
  27330. *
  27331. * @param sectorId
  27332. * @private
  27333. */
  27334. exports._mergeThisWithFrozen = function(sectorId) {
  27335. // copy all nodes
  27336. for (var nodeId in this.nodes) {
  27337. if (this.nodes.hasOwnProperty(nodeId)) {
  27338. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  27339. }
  27340. }
  27341. // copy all edges (if not fully clustered, else there are no edges)
  27342. for (var edgeId in this.edges) {
  27343. if (this.edges.hasOwnProperty(edgeId)) {
  27344. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  27345. }
  27346. }
  27347. // merge the nodeIndices
  27348. for (var i = 0; i < this.nodeIndices.length; i++) {
  27349. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  27350. }
  27351. };
  27352. /**
  27353. * This clusters the sector to one cluster. It was a single cluster before this process started so
  27354. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  27355. *
  27356. * @private
  27357. */
  27358. exports._collapseThisToSingleCluster = function() {
  27359. this.clusterToFit(1,false);
  27360. };
  27361. /**
  27362. * We create a new active sector from the node that we want to open.
  27363. *
  27364. * @param node
  27365. * @private
  27366. */
  27367. exports._addSector = function(node) {
  27368. // this is the currently active sector
  27369. var sector = this._sector();
  27370. // // this should allow me to select nodes from a frozen set.
  27371. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  27372. // console.log("the node is part of the active sector");
  27373. // }
  27374. // else {
  27375. // console.log("I dont know what the fuck happened!!");
  27376. // }
  27377. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  27378. delete this.nodes[node.id];
  27379. var unqiueIdentifier = util.randomUUID();
  27380. // we fully freeze the currently active sector
  27381. this._freezeSector(sector);
  27382. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  27383. this._createNewSector(unqiueIdentifier);
  27384. // we add the active sector to the sectors array to be able to revert these steps later on
  27385. this._setActiveSector(unqiueIdentifier);
  27386. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  27387. this._switchToSector(this._sector());
  27388. // finally we add the node we removed from our previous active sector to the new active sector
  27389. this.nodes[node.id] = node;
  27390. };
  27391. /**
  27392. * We close the sector that is currently open and revert back to the one before.
  27393. * If the active sector is the "default" sector, nothing happens.
  27394. *
  27395. * @private
  27396. */
  27397. exports._collapseSector = function() {
  27398. // the currently active sector
  27399. var sector = this._sector();
  27400. // we cannot collapse the default sector
  27401. if (sector != "default") {
  27402. if ((this.nodeIndices.length == 1) ||
  27403. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  27404. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  27405. var previousSector = this._previousSector();
  27406. // we collapse the sector back to a single cluster
  27407. this._collapseThisToSingleCluster();
  27408. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  27409. // This previous sector is the one we will reactivate
  27410. this._mergeThisWithFrozen(previousSector);
  27411. // the previously active (frozen) sector now has all the data from the currently active sector.
  27412. // we can now delete the active sector.
  27413. this._deleteActiveSector(sector);
  27414. // we activate the previously active (and currently frozen) sector.
  27415. this._activateSector(previousSector);
  27416. // we load the references from the newly active sector into the global references
  27417. this._switchToSector(previousSector);
  27418. // we forget the previously active sector because we reverted to the one before
  27419. this._forgetLastSector();
  27420. // finally, we update the node index list.
  27421. this._updateNodeIndexList();
  27422. // we refresh the list with calulation nodes and calculation node indices.
  27423. this._updateCalculationNodes();
  27424. }
  27425. }
  27426. };
  27427. /**
  27428. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  27429. *
  27430. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27431. * | we dont pass the function itself because then the "this" is the window object
  27432. * | instead of the Network object
  27433. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27434. * @private
  27435. */
  27436. exports._doInAllActiveSectors = function(runFunction,argument) {
  27437. var returnValues = [];
  27438. if (argument === undefined) {
  27439. for (var sector in this.sectors["active"]) {
  27440. if (this.sectors["active"].hasOwnProperty(sector)) {
  27441. // switch the global references to those of this sector
  27442. this._switchToActiveSector(sector);
  27443. returnValues.push( this[runFunction]() );
  27444. }
  27445. }
  27446. }
  27447. else {
  27448. for (var sector in this.sectors["active"]) {
  27449. if (this.sectors["active"].hasOwnProperty(sector)) {
  27450. // switch the global references to those of this sector
  27451. this._switchToActiveSector(sector);
  27452. var args = Array.prototype.splice.call(arguments, 1);
  27453. if (args.length > 1) {
  27454. returnValues.push( this[runFunction](args[0],args[1]) );
  27455. }
  27456. else {
  27457. returnValues.push( this[runFunction](argument) );
  27458. }
  27459. }
  27460. }
  27461. }
  27462. // we revert the global references back to our active sector
  27463. this._loadLatestSector();
  27464. return returnValues;
  27465. };
  27466. /**
  27467. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  27468. *
  27469. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27470. * | we dont pass the function itself because then the "this" is the window object
  27471. * | instead of the Network object
  27472. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27473. * @private
  27474. */
  27475. exports._doInSupportSector = function(runFunction,argument) {
  27476. var returnValues = false;
  27477. if (argument === undefined) {
  27478. this._switchToSupportSector();
  27479. returnValues = this[runFunction]();
  27480. }
  27481. else {
  27482. this._switchToSupportSector();
  27483. var args = Array.prototype.splice.call(arguments, 1);
  27484. if (args.length > 1) {
  27485. returnValues = this[runFunction](args[0],args[1]);
  27486. }
  27487. else {
  27488. returnValues = this[runFunction](argument);
  27489. }
  27490. }
  27491. // we revert the global references back to our active sector
  27492. this._loadLatestSector();
  27493. return returnValues;
  27494. };
  27495. /**
  27496. * This runs a function in all frozen sectors. This is used in the _redraw().
  27497. *
  27498. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27499. * | we don't pass the function itself because then the "this" is the window object
  27500. * | instead of the Network object
  27501. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27502. * @private
  27503. */
  27504. exports._doInAllFrozenSectors = function(runFunction,argument) {
  27505. if (argument === undefined) {
  27506. for (var sector in this.sectors["frozen"]) {
  27507. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  27508. // switch the global references to those of this sector
  27509. this._switchToFrozenSector(sector);
  27510. this[runFunction]();
  27511. }
  27512. }
  27513. }
  27514. else {
  27515. for (var sector in this.sectors["frozen"]) {
  27516. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  27517. // switch the global references to those of this sector
  27518. this._switchToFrozenSector(sector);
  27519. var args = Array.prototype.splice.call(arguments, 1);
  27520. if (args.length > 1) {
  27521. this[runFunction](args[0],args[1]);
  27522. }
  27523. else {
  27524. this[runFunction](argument);
  27525. }
  27526. }
  27527. }
  27528. }
  27529. this._loadLatestSector();
  27530. };
  27531. /**
  27532. * This runs a function in all sectors. This is used in the _redraw().
  27533. *
  27534. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  27535. * | we don't pass the function itself because then the "this" is the window object
  27536. * | instead of the Network object
  27537. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  27538. * @private
  27539. */
  27540. exports._doInAllSectors = function(runFunction,argument) {
  27541. var args = Array.prototype.splice.call(arguments, 1);
  27542. if (argument === undefined) {
  27543. this._doInAllActiveSectors(runFunction);
  27544. this._doInAllFrozenSectors(runFunction);
  27545. }
  27546. else {
  27547. if (args.length > 1) {
  27548. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  27549. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  27550. }
  27551. else {
  27552. this._doInAllActiveSectors(runFunction,argument);
  27553. this._doInAllFrozenSectors(runFunction,argument);
  27554. }
  27555. }
  27556. };
  27557. /**
  27558. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  27559. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  27560. *
  27561. * @private
  27562. */
  27563. exports._clearNodeIndexList = function() {
  27564. var sector = this._sector();
  27565. this.sectors["active"][sector]["nodeIndices"] = [];
  27566. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  27567. };
  27568. /**
  27569. * Draw the encompassing sector node
  27570. *
  27571. * @param ctx
  27572. * @param sectorType
  27573. * @private
  27574. */
  27575. exports._drawSectorNodes = function(ctx,sectorType) {
  27576. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  27577. for (var sector in this.sectors[sectorType]) {
  27578. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  27579. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  27580. this._switchToSector(sector,sectorType);
  27581. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  27582. for (var nodeId in this.nodes) {
  27583. if (this.nodes.hasOwnProperty(nodeId)) {
  27584. node = this.nodes[nodeId];
  27585. node.resize(ctx);
  27586. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  27587. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  27588. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  27589. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  27590. }
  27591. }
  27592. node = this.sectors[sectorType][sector]["drawingNode"];
  27593. node.x = 0.5 * (maxX + minX);
  27594. node.y = 0.5 * (maxY + minY);
  27595. node.width = 2 * (node.x - minX);
  27596. node.height = 2 * (node.y - minY);
  27597. node.options.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  27598. node.setScale(this.scale);
  27599. node._drawCircle(ctx);
  27600. }
  27601. }
  27602. }
  27603. };
  27604. exports._drawAllSectorNodes = function(ctx) {
  27605. this._drawSectorNodes(ctx,"frozen");
  27606. this._drawSectorNodes(ctx,"active");
  27607. this._loadLatestSector();
  27608. };
  27609. /***/ },
  27610. /* 66 */
  27611. /***/ function(module, exports, __webpack_require__) {
  27612. var Node = __webpack_require__(56);
  27613. /**
  27614. * This function can be called from the _doInAllSectors function
  27615. *
  27616. * @param object
  27617. * @param overlappingNodes
  27618. * @private
  27619. */
  27620. exports._getNodesOverlappingWith = function(object, overlappingNodes) {
  27621. var nodes = this.nodes;
  27622. for (var nodeId in nodes) {
  27623. if (nodes.hasOwnProperty(nodeId)) {
  27624. if (nodes[nodeId].isOverlappingWith(object)) {
  27625. overlappingNodes.push(nodeId);
  27626. }
  27627. }
  27628. }
  27629. };
  27630. /**
  27631. * retrieve all nodes overlapping with given object
  27632. * @param {Object} object An object with parameters left, top, right, bottom
  27633. * @return {Number[]} An array with id's of the overlapping nodes
  27634. * @private
  27635. */
  27636. exports._getAllNodesOverlappingWith = function (object) {
  27637. var overlappingNodes = [];
  27638. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  27639. return overlappingNodes;
  27640. };
  27641. /**
  27642. * Return a position object in canvasspace from a single point in screenspace
  27643. *
  27644. * @param pointer
  27645. * @returns {{left: number, top: number, right: number, bottom: number}}
  27646. * @private
  27647. */
  27648. exports._pointerToPositionObject = function(pointer) {
  27649. var x = this._XconvertDOMtoCanvas(pointer.x);
  27650. var y = this._YconvertDOMtoCanvas(pointer.y);
  27651. return {
  27652. left: x,
  27653. top: y,
  27654. right: x,
  27655. bottom: y
  27656. };
  27657. };
  27658. /**
  27659. * Get the top node at the a specific point (like a click)
  27660. *
  27661. * @param {{x: Number, y: Number}} pointer
  27662. * @return {Node | null} node
  27663. * @private
  27664. */
  27665. exports._getNodeAt = function (pointer) {
  27666. // we first check if this is an navigation controls element
  27667. var positionObject = this._pointerToPositionObject(pointer);
  27668. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  27669. // if there are overlapping nodes, select the last one, this is the
  27670. // one which is drawn on top of the others
  27671. if (overlappingNodes.length > 0) {
  27672. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  27673. }
  27674. else {
  27675. return null;
  27676. }
  27677. };
  27678. /**
  27679. * retrieve all edges overlapping with given object, selector is around center
  27680. * @param {Object} object An object with parameters left, top, right, bottom
  27681. * @return {Number[]} An array with id's of the overlapping nodes
  27682. * @private
  27683. */
  27684. exports._getEdgesOverlappingWith = function (object, overlappingEdges) {
  27685. var edges = this.edges;
  27686. for (var edgeId in edges) {
  27687. if (edges.hasOwnProperty(edgeId)) {
  27688. if (edges[edgeId].isOverlappingWith(object)) {
  27689. overlappingEdges.push(edgeId);
  27690. }
  27691. }
  27692. }
  27693. };
  27694. /**
  27695. * retrieve all nodes overlapping with given object
  27696. * @param {Object} object An object with parameters left, top, right, bottom
  27697. * @return {Number[]} An array with id's of the overlapping nodes
  27698. * @private
  27699. */
  27700. exports._getAllEdgesOverlappingWith = function (object) {
  27701. var overlappingEdges = [];
  27702. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  27703. return overlappingEdges;
  27704. };
  27705. /**
  27706. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  27707. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  27708. *
  27709. * @param pointer
  27710. * @returns {null}
  27711. * @private
  27712. */
  27713. exports._getEdgeAt = function(pointer) {
  27714. var positionObject = this._pointerToPositionObject(pointer);
  27715. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  27716. if (overlappingEdges.length > 0) {
  27717. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  27718. }
  27719. else {
  27720. return null;
  27721. }
  27722. };
  27723. /**
  27724. * Add object to the selection array.
  27725. *
  27726. * @param obj
  27727. * @private
  27728. */
  27729. exports._addToSelection = function(obj) {
  27730. if (obj instanceof Node) {
  27731. this.selectionObj.nodes[obj.id] = obj;
  27732. }
  27733. else {
  27734. this.selectionObj.edges[obj.id] = obj;
  27735. }
  27736. };
  27737. /**
  27738. * Add object to the selection array.
  27739. *
  27740. * @param obj
  27741. * @private
  27742. */
  27743. exports._addToHover = function(obj) {
  27744. if (obj instanceof Node) {
  27745. this.hoverObj.nodes[obj.id] = obj;
  27746. }
  27747. else {
  27748. this.hoverObj.edges[obj.id] = obj;
  27749. }
  27750. };
  27751. /**
  27752. * Remove a single option from selection.
  27753. *
  27754. * @param {Object} obj
  27755. * @private
  27756. */
  27757. exports._removeFromSelection = function(obj) {
  27758. if (obj instanceof Node) {
  27759. delete this.selectionObj.nodes[obj.id];
  27760. }
  27761. else {
  27762. delete this.selectionObj.edges[obj.id];
  27763. }
  27764. };
  27765. /**
  27766. * Unselect all. The selectionObj is useful for this.
  27767. *
  27768. * @param {Boolean} [doNotTrigger] | ignore trigger
  27769. * @private
  27770. */
  27771. exports._unselectAll = function(doNotTrigger) {
  27772. if (doNotTrigger === undefined) {
  27773. doNotTrigger = false;
  27774. }
  27775. for(var nodeId in this.selectionObj.nodes) {
  27776. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27777. this.selectionObj.nodes[nodeId].unselect();
  27778. }
  27779. }
  27780. for(var edgeId in this.selectionObj.edges) {
  27781. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27782. this.selectionObj.edges[edgeId].unselect();
  27783. }
  27784. }
  27785. this.selectionObj = {nodes:{},edges:{}};
  27786. if (doNotTrigger == false) {
  27787. this.emit('select', this.getSelection());
  27788. }
  27789. };
  27790. /**
  27791. * Unselect all clusters. The selectionObj is useful for this.
  27792. *
  27793. * @param {Boolean} [doNotTrigger] | ignore trigger
  27794. * @private
  27795. */
  27796. exports._unselectClusters = function(doNotTrigger) {
  27797. if (doNotTrigger === undefined) {
  27798. doNotTrigger = false;
  27799. }
  27800. for (var nodeId in this.selectionObj.nodes) {
  27801. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27802. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  27803. this.selectionObj.nodes[nodeId].unselect();
  27804. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  27805. }
  27806. }
  27807. }
  27808. if (doNotTrigger == false) {
  27809. this.emit('select', this.getSelection());
  27810. }
  27811. };
  27812. /**
  27813. * return the number of selected nodes
  27814. *
  27815. * @returns {number}
  27816. * @private
  27817. */
  27818. exports._getSelectedNodeCount = function() {
  27819. var count = 0;
  27820. for (var nodeId in this.selectionObj.nodes) {
  27821. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27822. count += 1;
  27823. }
  27824. }
  27825. return count;
  27826. };
  27827. /**
  27828. * return the selected node
  27829. *
  27830. * @returns {number}
  27831. * @private
  27832. */
  27833. exports._getSelectedNode = function() {
  27834. for (var nodeId in this.selectionObj.nodes) {
  27835. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27836. return this.selectionObj.nodes[nodeId];
  27837. }
  27838. }
  27839. return null;
  27840. };
  27841. /**
  27842. * return the selected edge
  27843. *
  27844. * @returns {number}
  27845. * @private
  27846. */
  27847. exports._getSelectedEdge = function() {
  27848. for (var edgeId in this.selectionObj.edges) {
  27849. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27850. return this.selectionObj.edges[edgeId];
  27851. }
  27852. }
  27853. return null;
  27854. };
  27855. /**
  27856. * return the number of selected edges
  27857. *
  27858. * @returns {number}
  27859. * @private
  27860. */
  27861. exports._getSelectedEdgeCount = function() {
  27862. var count = 0;
  27863. for (var edgeId in this.selectionObj.edges) {
  27864. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27865. count += 1;
  27866. }
  27867. }
  27868. return count;
  27869. };
  27870. /**
  27871. * return the number of selected objects.
  27872. *
  27873. * @returns {number}
  27874. * @private
  27875. */
  27876. exports._getSelectedObjectCount = function() {
  27877. var count = 0;
  27878. for(var nodeId in this.selectionObj.nodes) {
  27879. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27880. count += 1;
  27881. }
  27882. }
  27883. for(var edgeId in this.selectionObj.edges) {
  27884. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27885. count += 1;
  27886. }
  27887. }
  27888. return count;
  27889. };
  27890. /**
  27891. * Check if anything is selected
  27892. *
  27893. * @returns {boolean}
  27894. * @private
  27895. */
  27896. exports._selectionIsEmpty = function() {
  27897. for(var nodeId in this.selectionObj.nodes) {
  27898. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27899. return false;
  27900. }
  27901. }
  27902. for(var edgeId in this.selectionObj.edges) {
  27903. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27904. return false;
  27905. }
  27906. }
  27907. return true;
  27908. };
  27909. /**
  27910. * check if one of the selected nodes is a cluster.
  27911. *
  27912. * @returns {boolean}
  27913. * @private
  27914. */
  27915. exports._clusterInSelection = function() {
  27916. for(var nodeId in this.selectionObj.nodes) {
  27917. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27918. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  27919. return true;
  27920. }
  27921. }
  27922. }
  27923. return false;
  27924. };
  27925. /**
  27926. * select the edges connected to the node that is being selected
  27927. *
  27928. * @param {Node} node
  27929. * @private
  27930. */
  27931. exports._selectConnectedEdges = function(node) {
  27932. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27933. var edge = node.dynamicEdges[i];
  27934. edge.select();
  27935. this._addToSelection(edge);
  27936. }
  27937. };
  27938. /**
  27939. * select the edges connected to the node that is being selected
  27940. *
  27941. * @param {Node} node
  27942. * @private
  27943. */
  27944. exports._hoverConnectedEdges = function(node) {
  27945. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27946. var edge = node.dynamicEdges[i];
  27947. edge.hover = true;
  27948. this._addToHover(edge);
  27949. }
  27950. };
  27951. /**
  27952. * unselect the edges connected to the node that is being selected
  27953. *
  27954. * @param {Node} node
  27955. * @private
  27956. */
  27957. exports._unselectConnectedEdges = function(node) {
  27958. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27959. var edge = node.dynamicEdges[i];
  27960. edge.unselect();
  27961. this._removeFromSelection(edge);
  27962. }
  27963. };
  27964. /**
  27965. * This is called when someone clicks on a node. either select or deselect it.
  27966. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27967. *
  27968. * @param {Node || Edge} object
  27969. * @param {Boolean} append
  27970. * @param {Boolean} [doNotTrigger] | ignore trigger
  27971. * @private
  27972. */
  27973. exports._selectObject = function(object, append, doNotTrigger, highlightEdges, overrideSelectable) {
  27974. if (doNotTrigger === undefined) {
  27975. doNotTrigger = false;
  27976. }
  27977. if (highlightEdges === undefined) {
  27978. highlightEdges = true;
  27979. }
  27980. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  27981. this._unselectAll(true);
  27982. }
  27983. // selectable allows the object to be selected. Override can be used if needed to bypass this.
  27984. if (object.selected == false && (this.constants.selectable == true || overrideSelectable)) {
  27985. object.select();
  27986. this._addToSelection(object);
  27987. if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) {
  27988. this._selectConnectedEdges(object);
  27989. }
  27990. }
  27991. // do not select the object if selectable is false, only add it to selection to allow drag to work
  27992. else if (object.selected == false) {
  27993. this._addToSelection(object);
  27994. doNotTrigger = true;
  27995. }
  27996. else {
  27997. object.unselect();
  27998. this._removeFromSelection(object);
  27999. }
  28000. if (doNotTrigger == false) {
  28001. this.emit('select', this.getSelection());
  28002. }
  28003. };
  28004. /**
  28005. * This is called when someone clicks on a node. either select or deselect it.
  28006. * If there is an existing selection and we don't want to append to it, clear the existing selection
  28007. *
  28008. * @param {Node || Edge} object
  28009. * @private
  28010. */
  28011. exports._blurObject = function(object) {
  28012. if (object.hover == true) {
  28013. object.hover = false;
  28014. this.emit("blurNode",{node:object.id});
  28015. }
  28016. };
  28017. /**
  28018. * This is called when someone clicks on a node. either select or deselect it.
  28019. * If there is an existing selection and we don't want to append to it, clear the existing selection
  28020. *
  28021. * @param {Node || Edge} object
  28022. * @private
  28023. */
  28024. exports._hoverObject = function(object) {
  28025. if (object.hover == false) {
  28026. object.hover = true;
  28027. this._addToHover(object);
  28028. if (object instanceof Node) {
  28029. this.emit("hoverNode",{node:object.id});
  28030. }
  28031. }
  28032. if (object instanceof Node) {
  28033. this._hoverConnectedEdges(object);
  28034. }
  28035. };
  28036. /**
  28037. * handles the selection part of the touch, only for navigation controls elements;
  28038. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  28039. * This is the most responsive solution
  28040. *
  28041. * @param {Object} pointer
  28042. * @private
  28043. */
  28044. exports._handleTouch = function(pointer) {
  28045. };
  28046. /**
  28047. * handles the selection part of the tap;
  28048. *
  28049. * @param {Object} pointer
  28050. * @private
  28051. */
  28052. exports._handleTap = function(pointer) {
  28053. var node = this._getNodeAt(pointer);
  28054. if (node != null) {
  28055. this._selectObject(node, false);
  28056. }
  28057. else {
  28058. var edge = this._getEdgeAt(pointer);
  28059. if (edge != null) {
  28060. this._selectObject(edge, false);
  28061. }
  28062. else {
  28063. this._unselectAll();
  28064. }
  28065. }
  28066. var properties = this.getSelection();
  28067. properties['pointer'] = {
  28068. DOM: {x: pointer.x, y: pointer.y},
  28069. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  28070. }
  28071. this.emit("click", properties);
  28072. this._redraw();
  28073. };
  28074. /**
  28075. * handles the selection part of the double tap and opens a cluster if needed
  28076. *
  28077. * @param {Object} pointer
  28078. * @private
  28079. */
  28080. exports._handleDoubleTap = function(pointer) {
  28081. var node = this._getNodeAt(pointer);
  28082. if (node != null && node !== undefined) {
  28083. // we reset the areaCenter here so the opening of the node will occur
  28084. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  28085. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  28086. this.openCluster(node);
  28087. }
  28088. var properties = this.getSelection();
  28089. properties['pointer'] = {
  28090. DOM: {x: pointer.x, y: pointer.y},
  28091. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  28092. }
  28093. this.emit("doubleClick", properties);
  28094. };
  28095. /**
  28096. * Handle the onHold selection part
  28097. *
  28098. * @param pointer
  28099. * @private
  28100. */
  28101. exports._handleOnHold = function(pointer) {
  28102. var node = this._getNodeAt(pointer);
  28103. if (node != null) {
  28104. this._selectObject(node,true);
  28105. }
  28106. else {
  28107. var edge = this._getEdgeAt(pointer);
  28108. if (edge != null) {
  28109. this._selectObject(edge,true);
  28110. }
  28111. }
  28112. this._redraw();
  28113. };
  28114. /**
  28115. * handle the onRelease event. These functions are here for the navigation controls module
  28116. * and data manipulation module.
  28117. *
  28118. * @private
  28119. */
  28120. exports._handleOnRelease = function(pointer) {
  28121. this._manipulationReleaseOverload(pointer);
  28122. this._navigationReleaseOverload(pointer);
  28123. };
  28124. exports._manipulationReleaseOverload = function (pointer) {};
  28125. exports._navigationReleaseOverload = function (pointer) {};
  28126. /**
  28127. *
  28128. * retrieve the currently selected objects
  28129. * @return {{nodes: Array.<String>, edges: Array.<String>}} selection
  28130. */
  28131. exports.getSelection = function() {
  28132. var nodeIds = this.getSelectedNodes();
  28133. var edgeIds = this.getSelectedEdges();
  28134. return {nodes:nodeIds, edges:edgeIds};
  28135. };
  28136. /**
  28137. *
  28138. * retrieve the currently selected nodes
  28139. * @return {String[]} selection An array with the ids of the
  28140. * selected nodes.
  28141. */
  28142. exports.getSelectedNodes = function() {
  28143. var idArray = [];
  28144. if (this.constants.selectable == true) {
  28145. for (var nodeId in this.selectionObj.nodes) {
  28146. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28147. idArray.push(nodeId);
  28148. }
  28149. }
  28150. }
  28151. return idArray
  28152. };
  28153. /**
  28154. *
  28155. * retrieve the currently selected edges
  28156. * @return {Array} selection An array with the ids of the
  28157. * selected nodes.
  28158. */
  28159. exports.getSelectedEdges = function() {
  28160. var idArray = [];
  28161. if (this.constants.selectable == true) {
  28162. for (var edgeId in this.selectionObj.edges) {
  28163. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28164. idArray.push(edgeId);
  28165. }
  28166. }
  28167. }
  28168. return idArray;
  28169. };
  28170. /**
  28171. * select zero or more nodes DEPRICATED
  28172. * @param {Number[] | String[]} selection An array with the ids of the
  28173. * selected nodes.
  28174. */
  28175. exports.setSelection = function() {
  28176. console.log("setSelection is deprecated. Please use selectNodes instead.")
  28177. };
  28178. /**
  28179. * select zero or more nodes with the option to highlight edges
  28180. * @param {Number[] | String[]} selection An array with the ids of the
  28181. * selected nodes.
  28182. * @param {boolean} [highlightEdges]
  28183. */
  28184. exports.selectNodes = function(selection, highlightEdges) {
  28185. var i, iMax, id;
  28186. if (!selection || (selection.length == undefined))
  28187. throw 'Selection must be an array with ids';
  28188. // first unselect any selected node
  28189. this._unselectAll(true);
  28190. for (i = 0, iMax = selection.length; i < iMax; i++) {
  28191. id = selection[i];
  28192. var node = this.nodes[id];
  28193. if (!node) {
  28194. throw new RangeError('Node with id "' + id + '" not found');
  28195. }
  28196. this._selectObject(node,true,true,highlightEdges,true);
  28197. }
  28198. this.redraw();
  28199. };
  28200. /**
  28201. * select zero or more edges
  28202. * @param {Number[] | String[]} selection An array with the ids of the
  28203. * selected nodes.
  28204. */
  28205. exports.selectEdges = function(selection) {
  28206. var i, iMax, id;
  28207. if (!selection || (selection.length == undefined))
  28208. throw 'Selection must be an array with ids';
  28209. // first unselect any selected node
  28210. this._unselectAll(true);
  28211. for (i = 0, iMax = selection.length; i < iMax; i++) {
  28212. id = selection[i];
  28213. var edge = this.edges[id];
  28214. if (!edge) {
  28215. throw new RangeError('Edge with id "' + id + '" not found');
  28216. }
  28217. this._selectObject(edge,true,true,false,true);
  28218. }
  28219. this.redraw();
  28220. };
  28221. /**
  28222. * Validate the selection: remove ids of nodes which no longer exist
  28223. * @private
  28224. */
  28225. exports._updateSelection = function () {
  28226. for(var nodeId in this.selectionObj.nodes) {
  28227. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28228. if (!this.nodes.hasOwnProperty(nodeId)) {
  28229. delete this.selectionObj.nodes[nodeId];
  28230. }
  28231. }
  28232. }
  28233. for(var edgeId in this.selectionObj.edges) {
  28234. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28235. if (!this.edges.hasOwnProperty(edgeId)) {
  28236. delete this.selectionObj.edges[edgeId];
  28237. }
  28238. }
  28239. }
  28240. };
  28241. /***/ },
  28242. /* 67 */
  28243. /***/ function(module, exports, __webpack_require__) {
  28244. var util = __webpack_require__(1);
  28245. var Node = __webpack_require__(56);
  28246. var Edge = __webpack_require__(57);
  28247. /**
  28248. * clears the toolbar div element of children
  28249. *
  28250. * @private
  28251. */
  28252. exports._clearManipulatorBar = function() {
  28253. while (this.manipulationDiv.hasChildNodes()) {
  28254. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  28255. }
  28256. this.manipulationDOM = {};
  28257. this._manipulationReleaseOverload = function () {};
  28258. delete this.sectors['support']['nodes']['targetNode'];
  28259. delete this.sectors['support']['nodes']['targetViaNode'];
  28260. this.controlNodesActive = false;
  28261. };
  28262. /**
  28263. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  28264. * these functions to their original functionality, we saved them in this.cachedFunctions.
  28265. * This function restores these functions to their original function.
  28266. *
  28267. * @private
  28268. */
  28269. exports._restoreOverloadedFunctions = function() {
  28270. for (var functionName in this.cachedFunctions) {
  28271. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  28272. this[functionName] = this.cachedFunctions[functionName];
  28273. }
  28274. }
  28275. };
  28276. /**
  28277. * Enable or disable edit-mode.
  28278. *
  28279. * @private
  28280. */
  28281. exports._toggleEditMode = function() {
  28282. this.editMode = !this.editMode;
  28283. var toolbar = this.manipulationDiv;
  28284. var closeDiv = this.closeDiv;
  28285. var editModeDiv = this.editModeDiv;
  28286. if (this.editMode == true) {
  28287. toolbar.style.display="block";
  28288. closeDiv.style.display="block";
  28289. editModeDiv.style.display="none";
  28290. closeDiv.onclick = this._toggleEditMode.bind(this);
  28291. }
  28292. else {
  28293. toolbar.style.display="none";
  28294. closeDiv.style.display="none";
  28295. editModeDiv.style.display="block";
  28296. closeDiv.onclick = null;
  28297. }
  28298. this._createManipulatorBar()
  28299. };
  28300. /**
  28301. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  28302. *
  28303. * @private
  28304. */
  28305. exports._createManipulatorBar = function() {
  28306. // remove bound functions
  28307. if (this.boundFunction) {
  28308. this.off('select', this.boundFunction);
  28309. }
  28310. var locale = this.constants.locales[this.constants.locale];
  28311. if (this.edgeBeingEdited !== undefined) {
  28312. this.edgeBeingEdited._disableControlNodes();
  28313. this.edgeBeingEdited = undefined;
  28314. this.selectedControlNode = null;
  28315. this.controlNodesActive = false;
  28316. this._redraw();
  28317. }
  28318. // restore overloaded functions
  28319. this._restoreOverloadedFunctions();
  28320. // resume calculation
  28321. this.freezeSimulation = false;
  28322. // reset global variables
  28323. this.blockConnectingEdgeSelection = false;
  28324. this.forceAppendSelection = false;
  28325. this.manipulationDOM = {};
  28326. if (this.editMode == true) {
  28327. while (this.manipulationDiv.hasChildNodes()) {
  28328. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  28329. }
  28330. this.manipulationDOM['addNodeSpan'] = document.createElement('span');
  28331. this.manipulationDOM['addNodeSpan'].className = 'network-manipulationUI add';
  28332. this.manipulationDOM['addNodeLabelSpan'] = document.createElement('span');
  28333. this.manipulationDOM['addNodeLabelSpan'].className = 'network-manipulationLabel';
  28334. this.manipulationDOM['addNodeLabelSpan'].innerHTML = locale['addNode'];
  28335. this.manipulationDOM['addNodeSpan'].appendChild(this.manipulationDOM['addNodeLabelSpan']);
  28336. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28337. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28338. this.manipulationDOM['addEdgeSpan'] = document.createElement('span');
  28339. this.manipulationDOM['addEdgeSpan'].className = 'network-manipulationUI connect';
  28340. this.manipulationDOM['addEdgeLabelSpan'] = document.createElement('span');
  28341. this.manipulationDOM['addEdgeLabelSpan'].className = 'network-manipulationLabel';
  28342. this.manipulationDOM['addEdgeLabelSpan'].innerHTML = locale['addEdge'];
  28343. this.manipulationDOM['addEdgeSpan'].appendChild(this.manipulationDOM['addEdgeLabelSpan']);
  28344. this.manipulationDiv.appendChild(this.manipulationDOM['addNodeSpan']);
  28345. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28346. this.manipulationDiv.appendChild(this.manipulationDOM['addEdgeSpan']);
  28347. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  28348. this.manipulationDOM['seperatorLineDiv2'] = document.createElement('div');
  28349. this.manipulationDOM['seperatorLineDiv2'].className = 'network-seperatorLine';
  28350. this.manipulationDOM['editNodeSpan'] = document.createElement('span');
  28351. this.manipulationDOM['editNodeSpan'].className = 'network-manipulationUI edit';
  28352. this.manipulationDOM['editNodeLabelSpan'] = document.createElement('span');
  28353. this.manipulationDOM['editNodeLabelSpan'].className = 'network-manipulationLabel';
  28354. this.manipulationDOM['editNodeLabelSpan'].innerHTML = locale['editNode'];
  28355. this.manipulationDOM['editNodeSpan'].appendChild(this.manipulationDOM['editNodeLabelSpan']);
  28356. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv2']);
  28357. this.manipulationDiv.appendChild(this.manipulationDOM['editNodeSpan']);
  28358. }
  28359. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  28360. this.manipulationDOM['seperatorLineDiv3'] = document.createElement('div');
  28361. this.manipulationDOM['seperatorLineDiv3'].className = 'network-seperatorLine';
  28362. this.manipulationDOM['editEdgeSpan'] = document.createElement('span');
  28363. this.manipulationDOM['editEdgeSpan'].className = 'network-manipulationUI edit';
  28364. this.manipulationDOM['editEdgeLabelSpan'] = document.createElement('span');
  28365. this.manipulationDOM['editEdgeLabelSpan'].className = 'network-manipulationLabel';
  28366. this.manipulationDOM['editEdgeLabelSpan'].innerHTML = locale['editEdge'];
  28367. this.manipulationDOM['editEdgeSpan'].appendChild(this.manipulationDOM['editEdgeLabelSpan']);
  28368. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv3']);
  28369. this.manipulationDiv.appendChild(this.manipulationDOM['editEdgeSpan']);
  28370. }
  28371. if (this._selectionIsEmpty() == false) {
  28372. this.manipulationDOM['seperatorLineDiv4'] = document.createElement('div');
  28373. this.manipulationDOM['seperatorLineDiv4'].className = 'network-seperatorLine';
  28374. this.manipulationDOM['deleteSpan'] = document.createElement('span');
  28375. this.manipulationDOM['deleteSpan'].className = 'network-manipulationUI delete';
  28376. this.manipulationDOM['deleteLabelSpan'] = document.createElement('span');
  28377. this.manipulationDOM['deleteLabelSpan'].className = 'network-manipulationLabel';
  28378. this.manipulationDOM['deleteLabelSpan'].innerHTML = locale['del'];
  28379. this.manipulationDOM['deleteSpan'].appendChild(this.manipulationDOM['deleteLabelSpan']);
  28380. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv4']);
  28381. this.manipulationDiv.appendChild(this.manipulationDOM['deleteSpan']);
  28382. }
  28383. // bind the icons
  28384. this.manipulationDOM['addNodeSpan'].onclick = this._createAddNodeToolbar.bind(this);
  28385. this.manipulationDOM['addEdgeSpan'].onclick = this._createAddEdgeToolbar.bind(this);
  28386. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  28387. this.manipulationDOM['editNodeSpan'].onclick = this._editNode.bind(this);
  28388. }
  28389. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  28390. this.manipulationDOM['editEdgeSpan'].onclick = this._createEditEdgeToolbar.bind(this);
  28391. }
  28392. if (this._selectionIsEmpty() == false) {
  28393. this.manipulationDOM['deleteSpan'].onclick = this._deleteSelected.bind(this);
  28394. }
  28395. this.closeDiv.onclick = this._toggleEditMode.bind(this);
  28396. this.boundFunction = this._createManipulatorBar.bind(this);
  28397. this.on('select', this.boundFunction);
  28398. }
  28399. else {
  28400. while (this.editModeDiv.hasChildNodes()) {
  28401. this.editModeDiv.removeChild(this.editModeDiv.firstChild);
  28402. }
  28403. this.manipulationDOM['editModeSpan'] = document.createElement('span');
  28404. this.manipulationDOM['editModeSpan'].className = 'network-manipulationUI edit editmode';
  28405. this.manipulationDOM['editModeLabelSpan'] = document.createElement('span');
  28406. this.manipulationDOM['editModeLabelSpan'].className = 'network-manipulationLabel';
  28407. this.manipulationDOM['editModeLabelSpan'].innerHTML = locale['edit'];
  28408. this.manipulationDOM['editModeSpan'].appendChild(this.manipulationDOM['editModeLabelSpan']);
  28409. this.editModeDiv.appendChild(this.manipulationDOM['editModeSpan']);
  28410. this.manipulationDOM['editModeSpan'].onclick = this._toggleEditMode.bind(this);
  28411. }
  28412. };
  28413. /**
  28414. * Create the toolbar for adding Nodes
  28415. *
  28416. * @private
  28417. */
  28418. exports._createAddNodeToolbar = function() {
  28419. // clear the toolbar
  28420. this._clearManipulatorBar();
  28421. if (this.boundFunction) {
  28422. this.off('select', this.boundFunction);
  28423. }
  28424. var locale = this.constants.locales[this.constants.locale];
  28425. this.manipulationDOM = {};
  28426. this.manipulationDOM['backSpan'] = document.createElement('span');
  28427. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  28428. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  28429. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  28430. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  28431. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  28432. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28433. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28434. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  28435. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  28436. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  28437. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  28438. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['addDescription'];
  28439. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  28440. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  28441. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28442. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  28443. // bind the icon
  28444. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  28445. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  28446. this.boundFunction = this._addNode.bind(this);
  28447. this.on('select', this.boundFunction);
  28448. };
  28449. /**
  28450. * create the toolbar to connect nodes
  28451. *
  28452. * @private
  28453. */
  28454. exports._createAddEdgeToolbar = function() {
  28455. // clear the toolbar
  28456. this._clearManipulatorBar();
  28457. this._unselectAll(true);
  28458. this.freezeSimulation = true;
  28459. var locale = this.constants.locales[this.constants.locale];
  28460. if (this.boundFunction) {
  28461. this.off('select', this.boundFunction);
  28462. }
  28463. this._unselectAll();
  28464. this.forceAppendSelection = false;
  28465. this.blockConnectingEdgeSelection = true;
  28466. this.manipulationDOM = {};
  28467. this.manipulationDOM['backSpan'] = document.createElement('span');
  28468. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  28469. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  28470. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  28471. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  28472. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  28473. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28474. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28475. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  28476. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  28477. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  28478. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  28479. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['edgeDescription'];
  28480. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  28481. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  28482. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28483. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  28484. // bind the icon
  28485. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  28486. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  28487. this.boundFunction = this._handleConnect.bind(this);
  28488. this.on('select', this.boundFunction);
  28489. // temporarily overload functions
  28490. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  28491. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  28492. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  28493. this.cachedFunctions["_handleDragEnd"] = this._handleDragEnd;
  28494. this._handleTouch = this._handleConnect;
  28495. this._manipulationReleaseOverload = function () {};
  28496. this._handleDragStart = function () {};
  28497. this._handleDragEnd = this._finishConnect;
  28498. // redraw to show the unselect
  28499. this._redraw();
  28500. };
  28501. /**
  28502. * create the toolbar to edit edges
  28503. *
  28504. * @private
  28505. */
  28506. exports._createEditEdgeToolbar = function() {
  28507. // clear the toolbar
  28508. this._clearManipulatorBar();
  28509. this.controlNodesActive = true;
  28510. if (this.boundFunction) {
  28511. this.off('select', this.boundFunction);
  28512. }
  28513. this.edgeBeingEdited = this._getSelectedEdge();
  28514. this.edgeBeingEdited._enableControlNodes();
  28515. var locale = this.constants.locales[this.constants.locale];
  28516. this.manipulationDOM = {};
  28517. this.manipulationDOM['backSpan'] = document.createElement('span');
  28518. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  28519. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  28520. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  28521. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  28522. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  28523. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  28524. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  28525. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  28526. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  28527. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  28528. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  28529. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['editEdgeDescription'];
  28530. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  28531. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  28532. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  28533. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  28534. // bind the icon
  28535. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  28536. // temporarily overload functions
  28537. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  28538. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  28539. this.cachedFunctions["_handleTap"] = this._handleTap;
  28540. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  28541. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  28542. this._handleTouch = this._selectControlNode;
  28543. this._handleTap = function () {};
  28544. this._handleOnDrag = this._controlNodeDrag;
  28545. this._handleDragStart = function () {}
  28546. this._manipulationReleaseOverload = this._releaseControlNode;
  28547. // redraw to show the unselect
  28548. this._redraw();
  28549. };
  28550. /**
  28551. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28552. * to walk the user through the process.
  28553. *
  28554. * @private
  28555. */
  28556. exports._selectControlNode = function(pointer) {
  28557. this.edgeBeingEdited.controlNodes.from.unselect();
  28558. this.edgeBeingEdited.controlNodes.to.unselect();
  28559. this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y));
  28560. if (this.selectedControlNode !== null) {
  28561. this.selectedControlNode.select();
  28562. this.freezeSimulation = true;
  28563. }
  28564. this._redraw();
  28565. };
  28566. /**
  28567. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28568. * to walk the user through the process.
  28569. *
  28570. * @private
  28571. */
  28572. exports._controlNodeDrag = function(event) {
  28573. var pointer = this._getPointer(event.gesture.center);
  28574. if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) {
  28575. this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x);
  28576. this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y);
  28577. }
  28578. this._redraw();
  28579. };
  28580. exports._releaseControlNode = function(pointer) {
  28581. var newNode = this._getNodeAt(pointer);
  28582. if (newNode !== null) {
  28583. if (this.edgeBeingEdited.controlNodes.from.selected == true) {
  28584. this._editEdge(newNode.id, this.edgeBeingEdited.to.id);
  28585. this.edgeBeingEdited.controlNodes.from.unselect();
  28586. }
  28587. if (this.edgeBeingEdited.controlNodes.to.selected == true) {
  28588. this._editEdge(this.edgeBeingEdited.from.id, newNode.id);
  28589. this.edgeBeingEdited.controlNodes.to.unselect();
  28590. }
  28591. }
  28592. else {
  28593. this.edgeBeingEdited._restoreControlNodes();
  28594. }
  28595. this.freezeSimulation = false;
  28596. this._redraw();
  28597. };
  28598. /**
  28599. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28600. * to walk the user through the process.
  28601. *
  28602. * @private
  28603. */
  28604. exports._handleConnect = function(pointer) {
  28605. if (this._getSelectedNodeCount() == 0) {
  28606. var node = this._getNodeAt(pointer);
  28607. if (node != null) {
  28608. if (node.clusterSize > 1) {
  28609. alert(this.constants.locales[this.constants.locale]['createEdgeError'])
  28610. }
  28611. else {
  28612. this._selectObject(node,false);
  28613. var supportNodes = this.sectors['support']['nodes'];
  28614. // create a node the temporary line can look at
  28615. supportNodes['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  28616. var targetNode = supportNodes['targetNode'];
  28617. targetNode.x = node.x;
  28618. targetNode.y = node.y;
  28619. // create a temporary edge
  28620. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:targetNode.id}, this, this.constants);
  28621. var connectionEdge = this.edges['connectionEdge'];
  28622. connectionEdge.from = node;
  28623. connectionEdge.connected = true;
  28624. connectionEdge.options.smoothCurves = {enabled: true,
  28625. dynamic: false,
  28626. type: "continuous",
  28627. roundness: 0.5
  28628. };
  28629. connectionEdge.selected = true;
  28630. connectionEdge.to = targetNode;
  28631. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  28632. this._handleOnDrag = function(event) {
  28633. var pointer = this._getPointer(event.gesture.center);
  28634. var connectionEdge = this.edges['connectionEdge'];
  28635. connectionEdge.to.x = this._XconvertDOMtoCanvas(pointer.x);
  28636. connectionEdge.to.y = this._YconvertDOMtoCanvas(pointer.y);
  28637. };
  28638. this.moving = true;
  28639. this.start();
  28640. }
  28641. }
  28642. }
  28643. };
  28644. exports._finishConnect = function(event) {
  28645. if (this._getSelectedNodeCount() == 1) {
  28646. var pointer = this._getPointer(event.gesture.center);
  28647. // restore the drag function
  28648. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  28649. delete this.cachedFunctions["_handleOnDrag"];
  28650. // remember the edge id
  28651. var connectFromId = this.edges['connectionEdge'].fromId;
  28652. // remove the temporary nodes and edge
  28653. delete this.edges['connectionEdge'];
  28654. delete this.sectors['support']['nodes']['targetNode'];
  28655. delete this.sectors['support']['nodes']['targetViaNode'];
  28656. var node = this._getNodeAt(pointer);
  28657. if (node != null) {
  28658. if (node.clusterSize > 1) {
  28659. alert(this.constants.locales[this.constants.locale]["createEdgeError"])
  28660. }
  28661. else {
  28662. this._createEdge(connectFromId,node.id);
  28663. this._createManipulatorBar();
  28664. }
  28665. }
  28666. this._unselectAll();
  28667. }
  28668. };
  28669. /**
  28670. * Adds a node on the specified location
  28671. */
  28672. exports._addNode = function() {
  28673. if (this._selectionIsEmpty() && this.editMode == true) {
  28674. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  28675. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  28676. if (this.triggerFunctions.add) {
  28677. if (this.triggerFunctions.add.length == 2) {
  28678. var me = this;
  28679. this.triggerFunctions.add(defaultData, function(finalizedData) {
  28680. me.nodesData.add(finalizedData);
  28681. me._createManipulatorBar();
  28682. me.moving = true;
  28683. me.start();
  28684. });
  28685. }
  28686. else {
  28687. throw new Error('The function for add does not support two arguments (data,callback)');
  28688. this._createManipulatorBar();
  28689. this.moving = true;
  28690. this.start();
  28691. }
  28692. }
  28693. else {
  28694. this.nodesData.add(defaultData);
  28695. this._createManipulatorBar();
  28696. this.moving = true;
  28697. this.start();
  28698. }
  28699. }
  28700. };
  28701. /**
  28702. * connect two nodes with a new edge.
  28703. *
  28704. * @private
  28705. */
  28706. exports._createEdge = function(sourceNodeId,targetNodeId) {
  28707. if (this.editMode == true) {
  28708. var defaultData = {from:sourceNodeId, to:targetNodeId};
  28709. if (this.triggerFunctions.connect) {
  28710. if (this.triggerFunctions.connect.length == 2) {
  28711. var me = this;
  28712. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  28713. me.edgesData.add(finalizedData);
  28714. me.moving = true;
  28715. me.start();
  28716. });
  28717. }
  28718. else {
  28719. throw new Error('The function for connect does not support two arguments (data,callback)');
  28720. this.moving = true;
  28721. this.start();
  28722. }
  28723. }
  28724. else {
  28725. this.edgesData.add(defaultData);
  28726. this.moving = true;
  28727. this.start();
  28728. }
  28729. }
  28730. };
  28731. /**
  28732. * connect two nodes with a new edge.
  28733. *
  28734. * @private
  28735. */
  28736. exports._editEdge = function(sourceNodeId,targetNodeId) {
  28737. if (this.editMode == true) {
  28738. var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId};
  28739. if (this.triggerFunctions.editEdge) {
  28740. if (this.triggerFunctions.editEdge.length == 2) {
  28741. var me = this;
  28742. this.triggerFunctions.editEdge(defaultData, function(finalizedData) {
  28743. me.edgesData.update(finalizedData);
  28744. me.moving = true;
  28745. me.start();
  28746. });
  28747. }
  28748. else {
  28749. throw new Error('The function for edit does not support two arguments (data, callback)');
  28750. this.moving = true;
  28751. this.start();
  28752. }
  28753. }
  28754. else {
  28755. this.edgesData.update(defaultData);
  28756. this.moving = true;
  28757. this.start();
  28758. }
  28759. }
  28760. };
  28761. /**
  28762. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  28763. *
  28764. * @private
  28765. */
  28766. exports._editNode = function() {
  28767. if (this.triggerFunctions.edit && this.editMode == true) {
  28768. var node = this._getSelectedNode();
  28769. var data = {id:node.id,
  28770. label: node.label,
  28771. group: node.options.group,
  28772. shape: node.options.shape,
  28773. color: {
  28774. background:node.options.color.background,
  28775. border:node.options.color.border,
  28776. highlight: {
  28777. background:node.options.color.highlight.background,
  28778. border:node.options.color.highlight.border
  28779. }
  28780. }};
  28781. if (this.triggerFunctions.edit.length == 2) {
  28782. var me = this;
  28783. this.triggerFunctions.edit(data, function (finalizedData) {
  28784. me.nodesData.update(finalizedData);
  28785. me._createManipulatorBar();
  28786. me.moving = true;
  28787. me.start();
  28788. });
  28789. }
  28790. else {
  28791. throw new Error('The function for edit does not support two arguments (data, callback)');
  28792. }
  28793. }
  28794. else {
  28795. throw new Error('No edit function has been bound to this button');
  28796. }
  28797. };
  28798. /**
  28799. * delete everything in the selection
  28800. *
  28801. * @private
  28802. */
  28803. exports._deleteSelected = function() {
  28804. if (!this._selectionIsEmpty() && this.editMode == true) {
  28805. if (!this._clusterInSelection()) {
  28806. var selectedNodes = this.getSelectedNodes();
  28807. var selectedEdges = this.getSelectedEdges();
  28808. if (this.triggerFunctions.del) {
  28809. var me = this;
  28810. var data = {nodes: selectedNodes, edges: selectedEdges};
  28811. if (this.triggerFunctions.del.length == 2) {
  28812. this.triggerFunctions.del(data, function (finalizedData) {
  28813. me.edgesData.remove(finalizedData.edges);
  28814. me.nodesData.remove(finalizedData.nodes);
  28815. me._unselectAll();
  28816. me.moving = true;
  28817. me.start();
  28818. });
  28819. }
  28820. else {
  28821. throw new Error('The function for delete does not support two arguments (data, callback)')
  28822. }
  28823. }
  28824. else {
  28825. this.edgesData.remove(selectedEdges);
  28826. this.nodesData.remove(selectedNodes);
  28827. this._unselectAll();
  28828. this.moving = true;
  28829. this.start();
  28830. }
  28831. }
  28832. else {
  28833. alert(this.constants.locales[this.constants.locale]["deleteClusterError"]);
  28834. }
  28835. }
  28836. };
  28837. /***/ },
  28838. /* 68 */
  28839. /***/ function(module, exports, __webpack_require__) {
  28840. var util = __webpack_require__(1);
  28841. var Hammer = __webpack_require__(19);
  28842. exports._cleanNavigation = function() {
  28843. // clean hammer bindings
  28844. if (this.navigationHammers.existing.length != 0) {
  28845. for (var i = 0; i < this.navigationHammers.existing.length; i++) {
  28846. this.navigationHammers.existing[i].dispose();
  28847. }
  28848. this.navigationHammers.existing = [];
  28849. }
  28850. this._navigationReleaseOverload = function () {};
  28851. // clean up previous navigation items
  28852. if (this.navigationDivs && this.navigationDivs['wrapper'] && this.navigationDivs['wrapper'].parentNode) {
  28853. this.navigationDivs['wrapper'].parentNode.removeChild(this.navigationDivs['wrapper']);
  28854. }
  28855. };
  28856. /**
  28857. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  28858. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  28859. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  28860. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  28861. *
  28862. * @private
  28863. */
  28864. exports._loadNavigationElements = function() {
  28865. this._cleanNavigation();
  28866. this.navigationDivs = {};
  28867. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  28868. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','_zoomExtent'];
  28869. this.navigationDivs['wrapper'] = document.createElement('div');
  28870. this.frame.appendChild(this.navigationDivs['wrapper']);
  28871. for (var i = 0; i < navigationDivs.length; i++) {
  28872. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  28873. this.navigationDivs[navigationDivs[i]].className = 'network-navigation ' + navigationDivs[i];
  28874. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  28875. var hammer = Hammer(this.navigationDivs[navigationDivs[i]], {prevent_default: true});
  28876. hammer.on('touch', this[navigationDivActions[i]].bind(this));
  28877. this.navigationHammers._new.push(hammer);
  28878. }
  28879. this._navigationReleaseOverload = this._stopMovement;
  28880. this.navigationHammers.existing = this.navigationHammers._new;
  28881. };
  28882. /**
  28883. * this stops all movement induced by the navigation buttons
  28884. *
  28885. * @private
  28886. */
  28887. exports._zoomExtent = function(event) {
  28888. this.zoomExtent({duration:700});
  28889. event.stopPropagation();
  28890. };
  28891. /**
  28892. * this stops all movement induced by the navigation buttons
  28893. *
  28894. * @private
  28895. */
  28896. exports._stopMovement = function() {
  28897. this._xStopMoving();
  28898. this._yStopMoving();
  28899. this._stopZoom();
  28900. };
  28901. /**
  28902. * move the screen up
  28903. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  28904. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  28905. * To avoid this behaviour, we do the translation in the start loop.
  28906. *
  28907. * @private
  28908. */
  28909. exports._moveUp = function(event) {
  28910. this.yIncrement = this.constants.keyboard.speed.y;
  28911. this.start(); // if there is no node movement, the calculation wont be done
  28912. event.preventDefault();
  28913. };
  28914. /**
  28915. * move the screen down
  28916. * @private
  28917. */
  28918. exports._moveDown = function(event) {
  28919. this.yIncrement = -this.constants.keyboard.speed.y;
  28920. this.start(); // if there is no node movement, the calculation wont be done
  28921. event.preventDefault();
  28922. };
  28923. /**
  28924. * move the screen left
  28925. * @private
  28926. */
  28927. exports._moveLeft = function(event) {
  28928. this.xIncrement = this.constants.keyboard.speed.x;
  28929. this.start(); // if there is no node movement, the calculation wont be done
  28930. event.preventDefault();
  28931. };
  28932. /**
  28933. * move the screen right
  28934. * @private
  28935. */
  28936. exports._moveRight = function(event) {
  28937. this.xIncrement = -this.constants.keyboard.speed.y;
  28938. this.start(); // if there is no node movement, the calculation wont be done
  28939. event.preventDefault();
  28940. };
  28941. /**
  28942. * Zoom in, using the same method as the movement.
  28943. * @private
  28944. */
  28945. exports._zoomIn = function(event) {
  28946. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  28947. this.start(); // if there is no node movement, the calculation wont be done
  28948. event.preventDefault();
  28949. };
  28950. /**
  28951. * Zoom out
  28952. * @private
  28953. */
  28954. exports._zoomOut = function(event) {
  28955. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  28956. this.start(); // if there is no node movement, the calculation wont be done
  28957. event.preventDefault();
  28958. };
  28959. /**
  28960. * Stop zooming and unhighlight the zoom controls
  28961. * @private
  28962. */
  28963. exports._stopZoom = function(event) {
  28964. this.zoomIncrement = 0;
  28965. event && event.preventDefault();
  28966. };
  28967. /**
  28968. * Stop moving in the Y direction and unHighlight the up and down
  28969. * @private
  28970. */
  28971. exports._yStopMoving = function(event) {
  28972. this.yIncrement = 0;
  28973. event && event.preventDefault();
  28974. };
  28975. /**
  28976. * Stop moving in the X direction and unHighlight left and right.
  28977. * @private
  28978. */
  28979. exports._xStopMoving = function(event) {
  28980. this.xIncrement = 0;
  28981. event && event.preventDefault();
  28982. };
  28983. /***/ },
  28984. /* 69 */
  28985. /***/ function(module, exports, __webpack_require__) {
  28986. exports._resetLevels = function() {
  28987. for (var nodeId in this.nodes) {
  28988. if (this.nodes.hasOwnProperty(nodeId)) {
  28989. var node = this.nodes[nodeId];
  28990. if (node.preassignedLevel == false) {
  28991. node.level = -1;
  28992. node.hierarchyEnumerated = false;
  28993. }
  28994. }
  28995. }
  28996. };
  28997. /**
  28998. * This is the main function to layout the nodes in a hierarchical way.
  28999. * It checks if the node details are supplied correctly
  29000. *
  29001. * @private
  29002. */
  29003. exports._setupHierarchicalLayout = function() {
  29004. if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) {
  29005. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  29006. this.constants.hierarchicalLayout.levelSeparation = this.constants.hierarchicalLayout.levelSeparation < 0 ? this.constants.hierarchicalLayout.levelSeparation : this.constants.hierarchicalLayout.levelSeparation * -1;
  29007. }
  29008. else {
  29009. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  29010. }
  29011. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") {
  29012. if (this.constants.smoothCurves.enabled == true) {
  29013. this.constants.smoothCurves.type = "vertical";
  29014. }
  29015. }
  29016. else {
  29017. if (this.constants.smoothCurves.enabled == true) {
  29018. this.constants.smoothCurves.type = "horizontal";
  29019. }
  29020. }
  29021. // get the size of the largest hubs and check if the user has defined a level for a node.
  29022. var hubsize = 0;
  29023. var node, nodeId;
  29024. var definedLevel = false;
  29025. var undefinedLevel = false;
  29026. for (nodeId in this.nodes) {
  29027. if (this.nodes.hasOwnProperty(nodeId)) {
  29028. node = this.nodes[nodeId];
  29029. if (node.level != -1) {
  29030. definedLevel = true;
  29031. }
  29032. else {
  29033. undefinedLevel = true;
  29034. }
  29035. if (hubsize < node.edges.length) {
  29036. hubsize = node.edges.length;
  29037. }
  29038. }
  29039. }
  29040. // if the user defined some levels but not all, alert and run without hierarchical layout
  29041. if (undefinedLevel == true && definedLevel == true) {
  29042. throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  29043. this.zoomExtent(undefined,true,this.constants.clustering.enabled);
  29044. if (!this.constants.clustering.enabled) {
  29045. this.start();
  29046. }
  29047. }
  29048. else {
  29049. // setup the system to use hierarchical method.
  29050. this._changeConstants();
  29051. // define levels if undefined by the users. Based on hubsize
  29052. if (undefinedLevel == true) {
  29053. if (this.constants.hierarchicalLayout.layout == "hubsize") {
  29054. this._determineLevels(hubsize);
  29055. }
  29056. else {
  29057. this._determineLevelsDirected();
  29058. }
  29059. }
  29060. // check the distribution of the nodes per level.
  29061. var distribution = this._getDistribution();
  29062. // place the nodes on the canvas. This also stablilizes the system.
  29063. this._placeNodesByHierarchy(distribution);
  29064. // start the simulation.
  29065. this.start();
  29066. }
  29067. }
  29068. };
  29069. /**
  29070. * This function places the nodes on the canvas based on the hierarchial distribution.
  29071. *
  29072. * @param {Object} distribution | obtained by the function this._getDistribution()
  29073. * @private
  29074. */
  29075. exports._placeNodesByHierarchy = function(distribution) {
  29076. var nodeId, node;
  29077. // start placing all the level 0 nodes first. Then recursively position their branches.
  29078. for (var level in distribution) {
  29079. if (distribution.hasOwnProperty(level)) {
  29080. for (nodeId in distribution[level].nodes) {
  29081. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  29082. node = distribution[level].nodes[nodeId];
  29083. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  29084. if (node.xFixed) {
  29085. node.x = distribution[level].minPos;
  29086. node.xFixed = false;
  29087. distribution[level].minPos += distribution[level].nodeSpacing;
  29088. }
  29089. }
  29090. else {
  29091. if (node.yFixed) {
  29092. node.y = distribution[level].minPos;
  29093. node.yFixed = false;
  29094. distribution[level].minPos += distribution[level].nodeSpacing;
  29095. }
  29096. }
  29097. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  29098. }
  29099. }
  29100. }
  29101. }
  29102. // stabilize the system after positioning. This function calls zoomExtent.
  29103. this._stabilize();
  29104. };
  29105. /**
  29106. * This function get the distribution of levels based on hubsize
  29107. *
  29108. * @returns {Object}
  29109. * @private
  29110. */
  29111. exports._getDistribution = function() {
  29112. var distribution = {};
  29113. var nodeId, node, level;
  29114. // 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.
  29115. // the fix of X is removed after the x value has been set.
  29116. for (nodeId in this.nodes) {
  29117. if (this.nodes.hasOwnProperty(nodeId)) {
  29118. node = this.nodes[nodeId];
  29119. node.xFixed = true;
  29120. node.yFixed = true;
  29121. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  29122. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  29123. }
  29124. else {
  29125. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  29126. }
  29127. if (distribution[node.level] === undefined) {
  29128. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  29129. }
  29130. distribution[node.level].amount += 1;
  29131. distribution[node.level].nodes[nodeId] = node;
  29132. }
  29133. }
  29134. // determine the largest amount of nodes of all levels
  29135. var maxCount = 0;
  29136. for (level in distribution) {
  29137. if (distribution.hasOwnProperty(level)) {
  29138. if (maxCount < distribution[level].amount) {
  29139. maxCount = distribution[level].amount;
  29140. }
  29141. }
  29142. }
  29143. // set the initial position and spacing of each nodes accordingly
  29144. for (level in distribution) {
  29145. if (distribution.hasOwnProperty(level)) {
  29146. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  29147. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  29148. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  29149. }
  29150. }
  29151. return distribution;
  29152. };
  29153. /**
  29154. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  29155. *
  29156. * @param hubsize
  29157. * @private
  29158. */
  29159. exports._determineLevels = function(hubsize) {
  29160. var nodeId, node;
  29161. // determine hubs
  29162. for (nodeId in this.nodes) {
  29163. if (this.nodes.hasOwnProperty(nodeId)) {
  29164. node = this.nodes[nodeId];
  29165. if (node.edges.length == hubsize) {
  29166. node.level = 0;
  29167. }
  29168. }
  29169. }
  29170. // branch from hubs
  29171. for (nodeId in this.nodes) {
  29172. if (this.nodes.hasOwnProperty(nodeId)) {
  29173. node = this.nodes[nodeId];
  29174. if (node.level == 0) {
  29175. this._setLevel(1,node.edges,node.id);
  29176. }
  29177. }
  29178. }
  29179. };
  29180. /**
  29181. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  29182. *
  29183. * @param hubsize
  29184. * @private
  29185. */
  29186. exports._determineLevelsDirected = function() {
  29187. var nodeId, node;
  29188. // set first node to source
  29189. for (nodeId in this.nodes) {
  29190. if (this.nodes.hasOwnProperty(nodeId)) {
  29191. this.nodes[nodeId].level = 10000;
  29192. break;
  29193. }
  29194. }
  29195. // branch from hubs
  29196. for (nodeId in this.nodes) {
  29197. if (this.nodes.hasOwnProperty(nodeId)) {
  29198. node = this.nodes[nodeId];
  29199. if (node.level == 10000) {
  29200. this._setLevelDirected(10000,node.edges,node.id);
  29201. }
  29202. }
  29203. }
  29204. // branch from hubs
  29205. var minLevel = 10000;
  29206. for (nodeId in this.nodes) {
  29207. if (this.nodes.hasOwnProperty(nodeId)) {
  29208. node = this.nodes[nodeId];
  29209. minLevel = node.level < minLevel ? node.level : minLevel;
  29210. }
  29211. }
  29212. // branch from hubs
  29213. for (nodeId in this.nodes) {
  29214. if (this.nodes.hasOwnProperty(nodeId)) {
  29215. node = this.nodes[nodeId];
  29216. node.level -= minLevel;
  29217. }
  29218. }
  29219. };
  29220. /**
  29221. * Since hierarchical layout does not support:
  29222. * - smooth curves (based on the physics),
  29223. * - clustering (based on dynamic node counts)
  29224. *
  29225. * We disable both features so there will be no problems.
  29226. *
  29227. * @private
  29228. */
  29229. exports._changeConstants = function() {
  29230. this.constants.clustering.enabled = false;
  29231. this.constants.physics.barnesHut.enabled = false;
  29232. this.constants.physics.hierarchicalRepulsion.enabled = true;
  29233. this._loadSelectedForceSolver();
  29234. if (this.constants.smoothCurves.enabled == true) {
  29235. this.constants.smoothCurves.dynamic = false;
  29236. }
  29237. this._configureSmoothCurves();
  29238. };
  29239. /**
  29240. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  29241. * on a X position that ensures there will be no overlap.
  29242. *
  29243. * @param edges
  29244. * @param parentId
  29245. * @param distribution
  29246. * @param parentLevel
  29247. * @private
  29248. */
  29249. exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) {
  29250. for (var i = 0; i < edges.length; i++) {
  29251. var childNode = null;
  29252. if (edges[i].toId == parentId) {
  29253. childNode = edges[i].from;
  29254. }
  29255. else {
  29256. childNode = edges[i].to;
  29257. }
  29258. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  29259. var nodeMoved = false;
  29260. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  29261. if (childNode.xFixed && childNode.level > parentLevel) {
  29262. childNode.xFixed = false;
  29263. childNode.x = distribution[childNode.level].minPos;
  29264. nodeMoved = true;
  29265. }
  29266. }
  29267. else {
  29268. if (childNode.yFixed && childNode.level > parentLevel) {
  29269. childNode.yFixed = false;
  29270. childNode.y = distribution[childNode.level].minPos;
  29271. nodeMoved = true;
  29272. }
  29273. }
  29274. if (nodeMoved == true) {
  29275. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  29276. if (childNode.edges.length > 1) {
  29277. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  29278. }
  29279. }
  29280. }
  29281. };
  29282. /**
  29283. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  29284. *
  29285. * @param level
  29286. * @param edges
  29287. * @param parentId
  29288. * @private
  29289. */
  29290. exports._setLevel = function(level, edges, parentId) {
  29291. for (var i = 0; i < edges.length; i++) {
  29292. var childNode = null;
  29293. if (edges[i].toId == parentId) {
  29294. childNode = edges[i].from;
  29295. }
  29296. else {
  29297. childNode = edges[i].to;
  29298. }
  29299. if (childNode.level == -1 || childNode.level > level) {
  29300. childNode.level = level;
  29301. if (childNode.edges.length > 1) {
  29302. this._setLevel(level+1, childNode.edges, childNode.id);
  29303. }
  29304. }
  29305. }
  29306. };
  29307. /**
  29308. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  29309. *
  29310. * @param level
  29311. * @param edges
  29312. * @param parentId
  29313. * @private
  29314. */
  29315. exports._setLevelDirected = function(level, edges, parentId) {
  29316. this.nodes[parentId].hierarchyEnumerated = true;
  29317. for (var i = 0; i < edges.length; i++) {
  29318. var childNode = null;
  29319. var direction = 1;
  29320. if (edges[i].toId == parentId) {
  29321. childNode = edges[i].from;
  29322. direction = -1;
  29323. }
  29324. else {
  29325. childNode = edges[i].to;
  29326. }
  29327. if (childNode.level == -1) {
  29328. childNode.level = level + direction;
  29329. }
  29330. }
  29331. for (var i = 0; i < edges.length; i++) {
  29332. var childNode = null;
  29333. if (edges[i].toId == parentId) {childNode = edges[i].from;}
  29334. else {childNode = edges[i].to;}
  29335. if (childNode.edges.length > 1 && childNode.hierarchyEnumerated === false) {
  29336. this._setLevelDirected(childNode.level, childNode.edges, childNode.id);
  29337. }
  29338. }
  29339. };
  29340. /**
  29341. * Unfix nodes
  29342. *
  29343. * @private
  29344. */
  29345. exports._restoreNodes = function() {
  29346. for (var nodeId in this.nodes) {
  29347. if (this.nodes.hasOwnProperty(nodeId)) {
  29348. this.nodes[nodeId].xFixed = false;
  29349. this.nodes[nodeId].yFixed = false;
  29350. }
  29351. }
  29352. };
  29353. /***/ },
  29354. /* 70 */
  29355. /***/ function(module, exports, __webpack_require__) {
  29356. // English
  29357. exports['en'] = {
  29358. edit: 'Edit',
  29359. del: 'Delete selected',
  29360. back: 'Back',
  29361. addNode: 'Add Node',
  29362. addEdge: 'Add Edge',
  29363. editNode: 'Edit Node',
  29364. editEdge: 'Edit Edge',
  29365. addDescription: 'Click in an empty space to place a new node.',
  29366. edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
  29367. editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
  29368. createEdgeError: 'Cannot link edges to a cluster.',
  29369. deleteClusterError: 'Clusters cannot be deleted.'
  29370. };
  29371. exports['en_EN'] = exports['en'];
  29372. exports['en_US'] = exports['en'];
  29373. // Dutch
  29374. exports['nl'] = {
  29375. edit: 'Wijzigen',
  29376. del: 'Selectie verwijderen',
  29377. back: 'Terug',
  29378. addNode: 'Node toevoegen',
  29379. addEdge: 'Link toevoegen',
  29380. editNode: 'Node wijzigen',
  29381. editEdge: 'Link wijzigen',
  29382. addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.',
  29383. edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.',
  29384. editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.',
  29385. createEdgeError: 'Kan geen link maken naar een cluster.',
  29386. deleteClusterError: 'Clusters kunnen niet worden verwijderd.'
  29387. };
  29388. exports['nl_NL'] = exports['nl'];
  29389. exports['nl_BE'] = exports['nl'];
  29390. /***/ },
  29391. /* 71 */
  29392. /***/ function(module, exports, __webpack_require__) {
  29393. /**
  29394. * Canvas shapes used by Network
  29395. */
  29396. if (typeof CanvasRenderingContext2D !== 'undefined') {
  29397. /**
  29398. * Draw a circle shape
  29399. */
  29400. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  29401. this.beginPath();
  29402. this.arc(x, y, r, 0, 2*Math.PI, false);
  29403. };
  29404. /**
  29405. * Draw a square shape
  29406. * @param {Number} x horizontal center
  29407. * @param {Number} y vertical center
  29408. * @param {Number} r size, width and height of the square
  29409. */
  29410. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  29411. this.beginPath();
  29412. this.rect(x - r, y - r, r * 2, r * 2);
  29413. };
  29414. /**
  29415. * Draw a triangle shape
  29416. * @param {Number} x horizontal center
  29417. * @param {Number} y vertical center
  29418. * @param {Number} r radius, half the length of the sides of the triangle
  29419. */
  29420. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  29421. // http://en.wikipedia.org/wiki/Equilateral_triangle
  29422. this.beginPath();
  29423. var s = r * 2;
  29424. var s2 = s / 2;
  29425. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  29426. var h = Math.sqrt(s * s - s2 * s2); // height
  29427. this.moveTo(x, y - (h - ir));
  29428. this.lineTo(x + s2, y + ir);
  29429. this.lineTo(x - s2, y + ir);
  29430. this.lineTo(x, y - (h - ir));
  29431. this.closePath();
  29432. };
  29433. /**
  29434. * Draw a triangle shape in downward orientation
  29435. * @param {Number} x horizontal center
  29436. * @param {Number} y vertical center
  29437. * @param {Number} r radius
  29438. */
  29439. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  29440. // http://en.wikipedia.org/wiki/Equilateral_triangle
  29441. this.beginPath();
  29442. var s = r * 2;
  29443. var s2 = s / 2;
  29444. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  29445. var h = Math.sqrt(s * s - s2 * s2); // height
  29446. this.moveTo(x, y + (h - ir));
  29447. this.lineTo(x + s2, y - ir);
  29448. this.lineTo(x - s2, y - ir);
  29449. this.lineTo(x, y + (h - ir));
  29450. this.closePath();
  29451. };
  29452. /**
  29453. * Draw a star shape, a star with 5 points
  29454. * @param {Number} x horizontal center
  29455. * @param {Number} y vertical center
  29456. * @param {Number} r radius, half the length of the sides of the triangle
  29457. */
  29458. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  29459. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  29460. this.beginPath();
  29461. for (var n = 0; n < 10; n++) {
  29462. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  29463. this.lineTo(
  29464. x + radius * Math.sin(n * 2 * Math.PI / 10),
  29465. y - radius * Math.cos(n * 2 * Math.PI / 10)
  29466. );
  29467. }
  29468. this.closePath();
  29469. };
  29470. /**
  29471. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  29472. */
  29473. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  29474. var r2d = Math.PI/180;
  29475. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  29476. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  29477. this.beginPath();
  29478. this.moveTo(x+r,y);
  29479. this.lineTo(x+w-r,y);
  29480. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  29481. this.lineTo(x+w,y+h-r);
  29482. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  29483. this.lineTo(x+r,y+h);
  29484. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  29485. this.lineTo(x,y+r);
  29486. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  29487. };
  29488. /**
  29489. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  29490. */
  29491. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  29492. var kappa = .5522848,
  29493. ox = (w / 2) * kappa, // control point offset horizontal
  29494. oy = (h / 2) * kappa, // control point offset vertical
  29495. xe = x + w, // x-end
  29496. ye = y + h, // y-end
  29497. xm = x + w / 2, // x-middle
  29498. ym = y + h / 2; // y-middle
  29499. this.beginPath();
  29500. this.moveTo(x, ym);
  29501. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  29502. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  29503. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  29504. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  29505. };
  29506. /**
  29507. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  29508. */
  29509. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  29510. var f = 1/3;
  29511. var wEllipse = w;
  29512. var hEllipse = h * f;
  29513. var kappa = .5522848,
  29514. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  29515. oy = (hEllipse / 2) * kappa, // control point offset vertical
  29516. xe = x + wEllipse, // x-end
  29517. ye = y + hEllipse, // y-end
  29518. xm = x + wEllipse / 2, // x-middle
  29519. ym = y + hEllipse / 2, // y-middle
  29520. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  29521. yeb = y + h; // y-end, bottom ellipse
  29522. this.beginPath();
  29523. this.moveTo(xe, ym);
  29524. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  29525. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  29526. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  29527. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  29528. this.lineTo(xe, ymb);
  29529. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  29530. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  29531. this.lineTo(x, ym);
  29532. };
  29533. /**
  29534. * Draw an arrow point (no line)
  29535. */
  29536. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  29537. // tail
  29538. var xt = x - length * Math.cos(angle);
  29539. var yt = y - length * Math.sin(angle);
  29540. // inner tail
  29541. // TODO: allow to customize different shapes
  29542. var xi = x - length * 0.9 * Math.cos(angle);
  29543. var yi = y - length * 0.9 * Math.sin(angle);
  29544. // left
  29545. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  29546. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  29547. // right
  29548. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  29549. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  29550. this.beginPath();
  29551. this.moveTo(x, y);
  29552. this.lineTo(xl, yl);
  29553. this.lineTo(xi, yi);
  29554. this.lineTo(xr, yr);
  29555. this.closePath();
  29556. };
  29557. /**
  29558. * Sets up the dashedLine functionality for drawing
  29559. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  29560. * @author David Jordan
  29561. * @date 2012-08-08
  29562. */
  29563. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  29564. if (!dashArray) dashArray=[10,5];
  29565. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  29566. var dashCount = dashArray.length;
  29567. this.moveTo(x, y);
  29568. var dx = (x2-x), dy = (y2-y);
  29569. var slope = dy/dx;
  29570. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  29571. var dashIndex=0, draw=true;
  29572. while (distRemaining>=0.1){
  29573. var dashLength = dashArray[dashIndex++%dashCount];
  29574. if (dashLength > distRemaining) dashLength = distRemaining;
  29575. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  29576. if (dx<0) xStep = -xStep;
  29577. x += xStep;
  29578. y += slope*xStep;
  29579. this[draw ? 'lineTo' : 'moveTo'](x,y);
  29580. distRemaining -= dashLength;
  29581. draw = !draw;
  29582. }
  29583. };
  29584. // TODO: add diamond shape
  29585. }
  29586. /***/ }
  29587. /******/ ])
  29588. });