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.

30957 lines
963 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 3.2.0
  8. * @date 2014-08-14
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. (function webpackUniversalModuleDefinition(root, factory) {
  26. if(typeof exports === 'object' && typeof module === 'object')
  27. module.exports = factory();
  28. else if(typeof define === 'function' && define.amd)
  29. define(factory);
  30. else if(typeof exports === 'object')
  31. exports["vis"] = factory();
  32. else
  33. root["vis"] = factory();
  34. })(this, function() {
  35. return /******/ (function(modules) { // webpackBootstrap
  36. /******/ // The module cache
  37. /******/ var installedModules = {};
  38. /******/
  39. /******/ // The require function
  40. /******/ function __webpack_require__(moduleId) {
  41. /******/
  42. /******/ // Check if module is in cache
  43. /******/ if(installedModules[moduleId])
  44. /******/ return installedModules[moduleId].exports;
  45. /******/
  46. /******/ // Create a new module (and put it into the cache)
  47. /******/ var module = installedModules[moduleId] = {
  48. /******/ exports: {},
  49. /******/ id: moduleId,
  50. /******/ loaded: false
  51. /******/ };
  52. /******/
  53. /******/ // Execute the module function
  54. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  55. /******/
  56. /******/ // Flag the module as loaded
  57. /******/ module.loaded = true;
  58. /******/
  59. /******/ // Return the exports of the module
  60. /******/ return module.exports;
  61. /******/ }
  62. /******/
  63. /******/
  64. /******/ // expose the modules object (__webpack_modules__)
  65. /******/ __webpack_require__.m = modules;
  66. /******/
  67. /******/ // expose the module cache
  68. /******/ __webpack_require__.c = installedModules;
  69. /******/
  70. /******/ // __webpack_public_path__
  71. /******/ __webpack_require__.p = "";
  72. /******/
  73. /******/ // Load entry module and return exports
  74. /******/ return __webpack_require__(0);
  75. /******/ })
  76. /************************************************************************/
  77. /******/ ([
  78. /* 0 */
  79. /***/ function(module, exports, __webpack_require__) {
  80. // utils
  81. exports.util = __webpack_require__(1);
  82. exports.DOMutil = __webpack_require__(2);
  83. // data
  84. exports.DataSet = __webpack_require__(3);
  85. exports.DataView = __webpack_require__(4);
  86. // Graph3d
  87. exports.Graph3d = __webpack_require__(5);
  88. exports.graph3d = {
  89. Camera: __webpack_require__(6),
  90. Filter: __webpack_require__(7),
  91. Point2d: __webpack_require__(8),
  92. Point3d: __webpack_require__(9),
  93. Slider: __webpack_require__(10),
  94. StepNumber: __webpack_require__(11)
  95. };
  96. // Timeline
  97. exports.Timeline = __webpack_require__(12);
  98. exports.Graph2d = __webpack_require__(13);
  99. exports.timeline = {
  100. DataStep: __webpack_require__(14),
  101. Range: __webpack_require__(15),
  102. stack: __webpack_require__(16),
  103. TimeStep: __webpack_require__(17),
  104. components: {
  105. items: {
  106. Item: __webpack_require__(29),
  107. ItemBox: __webpack_require__(28),
  108. ItemPoint: __webpack_require__(30),
  109. ItemRange: __webpack_require__(31)
  110. },
  111. Component: __webpack_require__(18),
  112. CurrentTime: __webpack_require__(19),
  113. CustomTime: __webpack_require__(20),
  114. DataAxis: __webpack_require__(21),
  115. GraphGroup: __webpack_require__(22),
  116. Group: __webpack_require__(23),
  117. ItemSet: __webpack_require__(24),
  118. Legend: __webpack_require__(25),
  119. LineGraph: __webpack_require__(26),
  120. TimeAxis: __webpack_require__(27)
  121. }
  122. };
  123. // Network
  124. exports.Network = __webpack_require__(32);
  125. exports.network = {
  126. Edge: __webpack_require__(33),
  127. Groups: __webpack_require__(34),
  128. Images: __webpack_require__(35),
  129. Node: __webpack_require__(36),
  130. Popup: __webpack_require__(37),
  131. dotparser: __webpack_require__(38),
  132. gephiParser: __webpack_require__(39)
  133. };
  134. // Deprecated since v3.0.0
  135. exports.Graph = function () {
  136. throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)');
  137. };
  138. // bundled external libraries
  139. exports.moment = __webpack_require__(40);
  140. exports.hammer = __webpack_require__(41);
  141. /***/ },
  142. /* 1 */
  143. /***/ function(module, exports, __webpack_require__) {
  144. // utility functions
  145. // first check if moment.js is already loaded in the browser window, if so,
  146. // use this instance. Else, load via commonjs.
  147. var moment = __webpack_require__(40);
  148. /**
  149. * Test whether given object is a number
  150. * @param {*} object
  151. * @return {Boolean} isNumber
  152. */
  153. exports.isNumber = function(object) {
  154. return (object instanceof Number || typeof object == 'number');
  155. };
  156. /**
  157. * Test whether given object is a string
  158. * @param {*} object
  159. * @return {Boolean} isString
  160. */
  161. exports.isString = function(object) {
  162. return (object instanceof String || typeof object == 'string');
  163. };
  164. /**
  165. * Test whether given object is a Date, or a String containing a Date
  166. * @param {Date | String} object
  167. * @return {Boolean} isDate
  168. */
  169. exports.isDate = function(object) {
  170. if (object instanceof Date) {
  171. return true;
  172. }
  173. else if (exports.isString(object)) {
  174. // test whether this string contains a date
  175. var match = ASPDateRegex.exec(object);
  176. if (match) {
  177. return true;
  178. }
  179. else if (!isNaN(Date.parse(object))) {
  180. return true;
  181. }
  182. }
  183. return false;
  184. };
  185. /**
  186. * Test whether given object is an instance of google.visualization.DataTable
  187. * @param {*} object
  188. * @return {Boolean} isDataTable
  189. */
  190. exports.isDataTable = function(object) {
  191. return (typeof (google) !== 'undefined') &&
  192. (google.visualization) &&
  193. (google.visualization.DataTable) &&
  194. (object instanceof google.visualization.DataTable);
  195. };
  196. /**
  197. * Create a semi UUID
  198. * source: http://stackoverflow.com/a/105074/1262753
  199. * @return {String} uuid
  200. */
  201. exports.randomUUID = function() {
  202. var S4 = function () {
  203. return Math.floor(
  204. Math.random() * 0x10000 /* 65536 */
  205. ).toString(16);
  206. };
  207. return (
  208. S4() + S4() + '-' +
  209. S4() + '-' +
  210. S4() + '-' +
  211. S4() + '-' +
  212. S4() + S4() + S4()
  213. );
  214. };
  215. /**
  216. * Extend object a with the properties of object b or a series of objects
  217. * Only properties with defined values are copied
  218. * @param {Object} a
  219. * @param {... Object} b
  220. * @return {Object} a
  221. */
  222. exports.extend = function (a, b) {
  223. for (var i = 1, len = arguments.length; i < len; i++) {
  224. var other = arguments[i];
  225. for (var prop in other) {
  226. if (other.hasOwnProperty(prop)) {
  227. a[prop] = other[prop];
  228. }
  229. }
  230. }
  231. return a;
  232. };
  233. /**
  234. * Extend object a with selected properties of object b or a series of objects
  235. * Only properties with defined values are copied
  236. * @param {Array.<String>} props
  237. * @param {Object} a
  238. * @param {... Object} b
  239. * @return {Object} a
  240. */
  241. exports.selectiveExtend = function (props, a, b) {
  242. if (!Array.isArray(props)) {
  243. throw new Error('Array with property names expected as first argument');
  244. }
  245. for (var i = 2; i < arguments.length; i++) {
  246. var other = arguments[i];
  247. for (var p = 0; p < props.length; p++) {
  248. var prop = props[p];
  249. if (other.hasOwnProperty(prop)) {
  250. a[prop] = other[prop];
  251. }
  252. }
  253. }
  254. return a;
  255. };
  256. /**
  257. * Extend object a with selected properties of object b or a series of objects
  258. * Only properties with defined values are copied
  259. * @param {Array.<String>} props
  260. * @param {Object} a
  261. * @param {... Object} b
  262. * @return {Object} a
  263. */
  264. exports.selectiveDeepExtend = function (props, a, b) {
  265. // TODO: add support for Arrays to deepExtend
  266. if (Array.isArray(b)) {
  267. throw new TypeError('Arrays are not supported by deepExtend');
  268. }
  269. for (var i = 2; i < arguments.length; i++) {
  270. var other = arguments[i];
  271. for (var p = 0; p < props.length; p++) {
  272. var prop = props[p];
  273. if (other.hasOwnProperty(prop)) {
  274. if (b[prop] && b[prop].constructor === Object) {
  275. if (a[prop] === undefined) {
  276. a[prop] = {};
  277. }
  278. if (a[prop].constructor === Object) {
  279. exports.deepExtend(a[prop], b[prop]);
  280. }
  281. else {
  282. a[prop] = b[prop];
  283. }
  284. } else if (Array.isArray(b[prop])) {
  285. throw new TypeError('Arrays are not supported by deepExtend');
  286. } else {
  287. a[prop] = b[prop];
  288. }
  289. }
  290. }
  291. }
  292. return a;
  293. };
  294. /**
  295. * Extend object a with selected properties of object b or a series of objects
  296. * Only properties with defined values are copied
  297. * @param {Array.<String>} props
  298. * @param {Object} a
  299. * @param {... Object} b
  300. * @return {Object} a
  301. */
  302. exports.selectiveNotDeepExtend = function (props, a, b) {
  303. // TODO: add support for Arrays to deepExtend
  304. if (Array.isArray(b)) {
  305. throw new TypeError('Arrays are not supported by deepExtend');
  306. }
  307. for (var prop in b) {
  308. if (b.hasOwnProperty(prop)) {
  309. if (props.indexOf(prop) == -1) {
  310. if (b[prop] && b[prop].constructor === Object) {
  311. if (a[prop] === undefined) {
  312. a[prop] = {};
  313. }
  314. if (a[prop].constructor === Object) {
  315. exports.deepExtend(a[prop], b[prop]);
  316. }
  317. else {
  318. a[prop] = b[prop];
  319. }
  320. } else if (Array.isArray(b[prop])) {
  321. throw new TypeError('Arrays are not supported by deepExtend');
  322. } else {
  323. a[prop] = b[prop];
  324. }
  325. }
  326. }
  327. }
  328. return a;
  329. };
  330. /**
  331. * Deep extend an object a with the properties of object b
  332. * @param {Object} a
  333. * @param {Object} b
  334. * @returns {Object}
  335. */
  336. exports.deepExtend = function(a, b) {
  337. // TODO: add support for Arrays to deepExtend
  338. if (Array.isArray(b)) {
  339. throw new TypeError('Arrays are not supported by deepExtend');
  340. }
  341. for (var prop in b) {
  342. if (b.hasOwnProperty(prop)) {
  343. if (b[prop] && b[prop].constructor === Object) {
  344. if (a[prop] === undefined) {
  345. a[prop] = {};
  346. }
  347. if (a[prop].constructor === Object) {
  348. exports.deepExtend(a[prop], b[prop]);
  349. }
  350. else {
  351. a[prop] = b[prop];
  352. }
  353. } else if (Array.isArray(b[prop])) {
  354. throw new TypeError('Arrays are not supported by deepExtend');
  355. } else {
  356. a[prop] = b[prop];
  357. }
  358. }
  359. }
  360. return a;
  361. };
  362. /**
  363. * Test whether all elements in two arrays are equal.
  364. * @param {Array} a
  365. * @param {Array} b
  366. * @return {boolean} Returns true if both arrays have the same length and same
  367. * elements.
  368. */
  369. exports.equalArray = function (a, b) {
  370. if (a.length != b.length) return false;
  371. for (var i = 0, len = a.length; i < len; i++) {
  372. if (a[i] != b[i]) return false;
  373. }
  374. return true;
  375. };
  376. /**
  377. * Convert an object to another type
  378. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  379. * @param {String | undefined} type Name of the type. Available types:
  380. * 'Boolean', 'Number', 'String',
  381. * 'Date', 'Moment', ISODate', 'ASPDate'.
  382. * @return {*} object
  383. * @throws Error
  384. */
  385. exports.convert = function(object, type) {
  386. var match;
  387. if (object === undefined) {
  388. return undefined;
  389. }
  390. if (object === null) {
  391. return null;
  392. }
  393. if (!type) {
  394. return object;
  395. }
  396. if (!(typeof type === 'string') && !(type instanceof String)) {
  397. throw new Error('Type must be a string');
  398. }
  399. //noinspection FallthroughInSwitchStatementJS
  400. switch (type) {
  401. case 'boolean':
  402. case 'Boolean':
  403. return Boolean(object);
  404. case 'number':
  405. case 'Number':
  406. return Number(object.valueOf());
  407. case 'string':
  408. case 'String':
  409. return String(object);
  410. case 'Date':
  411. if (exports.isNumber(object)) {
  412. return new Date(object);
  413. }
  414. if (object instanceof Date) {
  415. return new Date(object.valueOf());
  416. }
  417. else if (moment.isMoment(object)) {
  418. return new Date(object.valueOf());
  419. }
  420. if (exports.isString(object)) {
  421. match = ASPDateRegex.exec(object);
  422. if (match) {
  423. // object is an ASP date
  424. return new Date(Number(match[1])); // parse number
  425. }
  426. else {
  427. return moment(object).toDate(); // parse string
  428. }
  429. }
  430. else {
  431. throw new Error(
  432. 'Cannot convert object of type ' + exports.getType(object) +
  433. ' to type Date');
  434. }
  435. case 'Moment':
  436. if (exports.isNumber(object)) {
  437. return moment(object);
  438. }
  439. if (object instanceof Date) {
  440. return moment(object.valueOf());
  441. }
  442. else if (moment.isMoment(object)) {
  443. return moment(object);
  444. }
  445. if (exports.isString(object)) {
  446. match = ASPDateRegex.exec(object);
  447. if (match) {
  448. // object is an ASP date
  449. return moment(Number(match[1])); // parse number
  450. }
  451. else {
  452. return moment(object); // parse string
  453. }
  454. }
  455. else {
  456. throw new Error(
  457. 'Cannot convert object of type ' + exports.getType(object) +
  458. ' to type Date');
  459. }
  460. case 'ISODate':
  461. if (exports.isNumber(object)) {
  462. return new Date(object);
  463. }
  464. else if (object instanceof Date) {
  465. return object.toISOString();
  466. }
  467. else if (moment.isMoment(object)) {
  468. return object.toDate().toISOString();
  469. }
  470. else if (exports.isString(object)) {
  471. match = ASPDateRegex.exec(object);
  472. if (match) {
  473. // object is an ASP date
  474. return new Date(Number(match[1])).toISOString(); // parse number
  475. }
  476. else {
  477. return new Date(object).toISOString(); // parse string
  478. }
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + exports.getType(object) +
  483. ' to type ISODate');
  484. }
  485. case 'ASPDate':
  486. if (exports.isNumber(object)) {
  487. return '/Date(' + object + ')/';
  488. }
  489. else if (object instanceof Date) {
  490. return '/Date(' + object.valueOf() + ')/';
  491. }
  492. else if (exports.isString(object)) {
  493. match = ASPDateRegex.exec(object);
  494. var value;
  495. if (match) {
  496. // object is an ASP date
  497. value = new Date(Number(match[1])).valueOf(); // parse number
  498. }
  499. else {
  500. value = new Date(object).valueOf(); // parse string
  501. }
  502. return '/Date(' + value + ')/';
  503. }
  504. else {
  505. throw new Error(
  506. 'Cannot convert object of type ' + exports.getType(object) +
  507. ' to type ASPDate');
  508. }
  509. default:
  510. throw new Error('Unknown type "' + type + '"');
  511. }
  512. };
  513. // parse ASP.Net Date pattern,
  514. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  515. // code from http://momentjs.com/
  516. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  517. /**
  518. * Get the type of an object, for example exports.getType([]) returns 'Array'
  519. * @param {*} object
  520. * @return {String} type
  521. */
  522. exports.getType = function(object) {
  523. var type = typeof object;
  524. if (type == 'object') {
  525. if (object == null) {
  526. return 'null';
  527. }
  528. if (object instanceof Boolean) {
  529. return 'Boolean';
  530. }
  531. if (object instanceof Number) {
  532. return 'Number';
  533. }
  534. if (object instanceof String) {
  535. return 'String';
  536. }
  537. if (object instanceof Array) {
  538. return 'Array';
  539. }
  540. if (object instanceof Date) {
  541. return 'Date';
  542. }
  543. return 'Object';
  544. }
  545. else if (type == 'number') {
  546. return 'Number';
  547. }
  548. else if (type == 'boolean') {
  549. return 'Boolean';
  550. }
  551. else if (type == 'string') {
  552. return 'String';
  553. }
  554. return type;
  555. };
  556. /**
  557. * Retrieve the absolute left value of a DOM element
  558. * @param {Element} elem A dom element, for example a div
  559. * @return {number} left The absolute left position of this element
  560. * in the browser page.
  561. */
  562. exports.getAbsoluteLeft = function(elem) {
  563. return elem.getBoundingClientRect().left + window.pageXOffset;
  564. };
  565. /**
  566. * Retrieve the absolute top value of a DOM element
  567. * @param {Element} elem A dom element, for example a div
  568. * @return {number} top The absolute top position of this element
  569. * in the browser page.
  570. */
  571. exports.getAbsoluteTop = function(elem) {
  572. return elem.getBoundingClientRect().top + window.pageYOffset;
  573. };
  574. /**
  575. * add a className to the given elements style
  576. * @param {Element} elem
  577. * @param {String} className
  578. */
  579. exports.addClassName = function(elem, className) {
  580. var classes = elem.className.split(' ');
  581. if (classes.indexOf(className) == -1) {
  582. classes.push(className); // add the class to the array
  583. elem.className = classes.join(' ');
  584. }
  585. };
  586. /**
  587. * add a className to the given elements style
  588. * @param {Element} elem
  589. * @param {String} className
  590. */
  591. exports.removeClassName = function(elem, className) {
  592. var classes = elem.className.split(' ');
  593. var index = classes.indexOf(className);
  594. if (index != -1) {
  595. classes.splice(index, 1); // remove the class from the array
  596. elem.className = classes.join(' ');
  597. }
  598. };
  599. /**
  600. * For each method for both arrays and objects.
  601. * In case of an array, the built-in Array.forEach() is applied.
  602. * In case of an Object, the method loops over all properties of the object.
  603. * @param {Object | Array} object An Object or Array
  604. * @param {function} callback Callback method, called for each item in
  605. * the object or array with three parameters:
  606. * callback(value, index, object)
  607. */
  608. exports.forEach = function(object, callback) {
  609. var i,
  610. len;
  611. if (object instanceof Array) {
  612. // array
  613. for (i = 0, len = object.length; i < len; i++) {
  614. callback(object[i], i, object);
  615. }
  616. }
  617. else {
  618. // object
  619. for (i in object) {
  620. if (object.hasOwnProperty(i)) {
  621. callback(object[i], i, object);
  622. }
  623. }
  624. }
  625. };
  626. /**
  627. * Convert an object into an array: all objects properties are put into the
  628. * array. The resulting array is unordered.
  629. * @param {Object} object
  630. * @param {Array} array
  631. */
  632. exports.toArray = function(object) {
  633. var array = [];
  634. for (var prop in object) {
  635. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  636. }
  637. return array;
  638. }
  639. /**
  640. * Update a property in an object
  641. * @param {Object} object
  642. * @param {String} key
  643. * @param {*} value
  644. * @return {Boolean} changed
  645. */
  646. exports.updateProperty = function(object, key, value) {
  647. if (object[key] !== value) {
  648. object[key] = value;
  649. return true;
  650. }
  651. else {
  652. return false;
  653. }
  654. };
  655. /**
  656. * Add and event listener. Works for all browsers
  657. * @param {Element} element An html element
  658. * @param {string} action The action, for example "click",
  659. * without the prefix "on"
  660. * @param {function} listener The callback function to be executed
  661. * @param {boolean} [useCapture]
  662. */
  663. exports.addEventListener = function(element, action, listener, useCapture) {
  664. if (element.addEventListener) {
  665. if (useCapture === undefined)
  666. useCapture = false;
  667. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  668. action = "DOMMouseScroll"; // For Firefox
  669. }
  670. element.addEventListener(action, listener, useCapture);
  671. } else {
  672. element.attachEvent("on" + action, listener); // IE browsers
  673. }
  674. };
  675. /**
  676. * Remove an event listener from an element
  677. * @param {Element} element An html dom element
  678. * @param {string} action The name of the event, for example "mousedown"
  679. * @param {function} listener The listener function
  680. * @param {boolean} [useCapture]
  681. */
  682. exports.removeEventListener = function(element, action, listener, useCapture) {
  683. if (element.removeEventListener) {
  684. // non-IE browsers
  685. if (useCapture === undefined)
  686. useCapture = false;
  687. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  688. action = "DOMMouseScroll"; // For Firefox
  689. }
  690. element.removeEventListener(action, listener, useCapture);
  691. } else {
  692. // IE browsers
  693. element.detachEvent("on" + action, listener);
  694. }
  695. };
  696. /**
  697. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  698. */
  699. exports.preventDefault = function (event) {
  700. if (!event)
  701. event = window.event;
  702. if (event.preventDefault) {
  703. event.preventDefault(); // non-IE browsers
  704. }
  705. else {
  706. event.returnValue = false; // IE browsers
  707. }
  708. };
  709. /**
  710. * Get HTML element which is the target of the event
  711. * @param {Event} event
  712. * @return {Element} target element
  713. */
  714. exports.getTarget = function(event) {
  715. // code from http://www.quirksmode.org/js/events_properties.html
  716. if (!event) {
  717. event = window.event;
  718. }
  719. var target;
  720. if (event.target) {
  721. target = event.target;
  722. }
  723. else if (event.srcElement) {
  724. target = event.srcElement;
  725. }
  726. if (target.nodeType != undefined && target.nodeType == 3) {
  727. // defeat Safari bug
  728. target = target.parentNode;
  729. }
  730. return target;
  731. };
  732. exports.option = {};
  733. /**
  734. * Convert a value into a boolean
  735. * @param {Boolean | function | undefined} value
  736. * @param {Boolean} [defaultValue]
  737. * @returns {Boolean} bool
  738. */
  739. exports.option.asBoolean = function (value, defaultValue) {
  740. if (typeof value == 'function') {
  741. value = value();
  742. }
  743. if (value != null) {
  744. return (value != false);
  745. }
  746. return defaultValue || null;
  747. };
  748. /**
  749. * Convert a value into a number
  750. * @param {Boolean | function | undefined} value
  751. * @param {Number} [defaultValue]
  752. * @returns {Number} number
  753. */
  754. exports.option.asNumber = function (value, defaultValue) {
  755. if (typeof value == 'function') {
  756. value = value();
  757. }
  758. if (value != null) {
  759. return Number(value) || defaultValue || null;
  760. }
  761. return defaultValue || null;
  762. };
  763. /**
  764. * Convert a value into a string
  765. * @param {String | function | undefined} value
  766. * @param {String} [defaultValue]
  767. * @returns {String} str
  768. */
  769. exports.option.asString = function (value, defaultValue) {
  770. if (typeof value == 'function') {
  771. value = value();
  772. }
  773. if (value != null) {
  774. return String(value);
  775. }
  776. return defaultValue || null;
  777. };
  778. /**
  779. * Convert a size or location into a string with pixels or a percentage
  780. * @param {String | Number | function | undefined} value
  781. * @param {String} [defaultValue]
  782. * @returns {String} size
  783. */
  784. exports.option.asSize = function (value, defaultValue) {
  785. if (typeof value == 'function') {
  786. value = value();
  787. }
  788. if (exports.isString(value)) {
  789. return value;
  790. }
  791. else if (exports.isNumber(value)) {
  792. return value + 'px';
  793. }
  794. else {
  795. return defaultValue || null;
  796. }
  797. };
  798. /**
  799. * Convert a value into a DOM element
  800. * @param {HTMLElement | function | undefined} value
  801. * @param {HTMLElement} [defaultValue]
  802. * @returns {HTMLElement | null} dom
  803. */
  804. exports.option.asElement = function (value, defaultValue) {
  805. if (typeof value == 'function') {
  806. value = value();
  807. }
  808. return value || defaultValue || null;
  809. };
  810. exports.GiveDec = function(Hex) {
  811. var Value;
  812. if (Hex == "A")
  813. Value = 10;
  814. else if (Hex == "B")
  815. Value = 11;
  816. else if (Hex == "C")
  817. Value = 12;
  818. else if (Hex == "D")
  819. Value = 13;
  820. else if (Hex == "E")
  821. Value = 14;
  822. else if (Hex == "F")
  823. Value = 15;
  824. else
  825. Value = eval(Hex);
  826. return Value;
  827. };
  828. exports.GiveHex = function(Dec) {
  829. var Value;
  830. if(Dec == 10)
  831. Value = "A";
  832. else if (Dec == 11)
  833. Value = "B";
  834. else if (Dec == 12)
  835. Value = "C";
  836. else if (Dec == 13)
  837. Value = "D";
  838. else if (Dec == 14)
  839. Value = "E";
  840. else if (Dec == 15)
  841. Value = "F";
  842. else
  843. Value = "" + Dec;
  844. return Value;
  845. };
  846. /**
  847. * Parse a color property into an object with border, background, and
  848. * highlight colors
  849. * @param {Object | String} color
  850. * @return {Object} colorObject
  851. */
  852. exports.parseColor = function(color) {
  853. var c;
  854. if (exports.isString(color)) {
  855. if (exports.isValidRGB(color)) {
  856. var rgb = color.substr(4).substr(0,color.length-5).split(',');
  857. color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]);
  858. }
  859. if (exports.isValidHex(color)) {
  860. var hsv = exports.hexToHSV(color);
  861. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  862. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  863. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  864. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  865. c = {
  866. background: color,
  867. border:darkerColorHex,
  868. highlight: {
  869. background:lighterColorHex,
  870. border:darkerColorHex
  871. },
  872. hover: {
  873. background:lighterColorHex,
  874. border:darkerColorHex
  875. }
  876. };
  877. }
  878. else {
  879. c = {
  880. background:color,
  881. border:color,
  882. highlight: {
  883. background:color,
  884. border:color
  885. },
  886. hover: {
  887. background:color,
  888. border:color
  889. }
  890. };
  891. }
  892. }
  893. else {
  894. c = {};
  895. c.background = color.background || 'white';
  896. c.border = color.border || c.background;
  897. if (exports.isString(color.highlight)) {
  898. c.highlight = {
  899. border: color.highlight,
  900. background: color.highlight
  901. }
  902. }
  903. else {
  904. c.highlight = {};
  905. c.highlight.background = color.highlight && color.highlight.background || c.background;
  906. c.highlight.border = color.highlight && color.highlight.border || c.border;
  907. }
  908. if (exports.isString(color.hover)) {
  909. c.hover = {
  910. border: color.hover,
  911. background: color.hover
  912. }
  913. }
  914. else {
  915. c.hover = {};
  916. c.hover.background = color.hover && color.hover.background || c.background;
  917. c.hover.border = color.hover && color.hover.border || c.border;
  918. }
  919. }
  920. return c;
  921. };
  922. /**
  923. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  924. *
  925. * @param {String} hex
  926. * @returns {{r: *, g: *, b: *}}
  927. */
  928. exports.hexToRGB = function(hex) {
  929. hex = hex.replace("#","").toUpperCase();
  930. var a = exports.GiveDec(hex.substring(0, 1));
  931. var b = exports.GiveDec(hex.substring(1, 2));
  932. var c = exports.GiveDec(hex.substring(2, 3));
  933. var d = exports.GiveDec(hex.substring(3, 4));
  934. var e = exports.GiveDec(hex.substring(4, 5));
  935. var f = exports.GiveDec(hex.substring(5, 6));
  936. var r = (a * 16) + b;
  937. var g = (c * 16) + d;
  938. var b = (e * 16) + f;
  939. return {r:r,g:g,b:b};
  940. };
  941. exports.RGBToHex = function(red,green,blue) {
  942. var a = exports.GiveHex(Math.floor(red / 16));
  943. var b = exports.GiveHex(red % 16);
  944. var c = exports.GiveHex(Math.floor(green / 16));
  945. var d = exports.GiveHex(green % 16);
  946. var e = exports.GiveHex(Math.floor(blue / 16));
  947. var f = exports.GiveHex(blue % 16);
  948. var hex = a + b + c + d + e + f;
  949. return "#" + hex;
  950. };
  951. /**
  952. * http://www.javascripter.net/faq/rgb2hsv.htm
  953. *
  954. * @param red
  955. * @param green
  956. * @param blue
  957. * @returns {*}
  958. * @constructor
  959. */
  960. exports.RGBToHSV = function(red,green,blue) {
  961. red=red/255; green=green/255; blue=blue/255;
  962. var minRGB = Math.min(red,Math.min(green,blue));
  963. var maxRGB = Math.max(red,Math.max(green,blue));
  964. // Black-gray-white
  965. if (minRGB == maxRGB) {
  966. return {h:0,s:0,v:minRGB};
  967. }
  968. // Colors other than black-gray-white:
  969. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  970. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  971. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  972. var saturation = (maxRGB - minRGB)/maxRGB;
  973. var value = maxRGB;
  974. return {h:hue,s:saturation,v:value};
  975. };
  976. /**
  977. * https://gist.github.com/mjijackson/5311256
  978. * @param h
  979. * @param s
  980. * @param v
  981. * @returns {{r: number, g: number, b: number}}
  982. * @constructor
  983. */
  984. exports.HSVToRGB = function(h, s, v) {
  985. var r, g, b;
  986. var i = Math.floor(h * 6);
  987. var f = h * 6 - i;
  988. var p = v * (1 - s);
  989. var q = v * (1 - f * s);
  990. var t = v * (1 - (1 - f) * s);
  991. switch (i % 6) {
  992. case 0: r = v, g = t, b = p; break;
  993. case 1: r = q, g = v, b = p; break;
  994. case 2: r = p, g = v, b = t; break;
  995. case 3: r = p, g = q, b = v; break;
  996. case 4: r = t, g = p, b = v; break;
  997. case 5: r = v, g = p, b = q; break;
  998. }
  999. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1000. };
  1001. exports.HSVToHex = function(h, s, v) {
  1002. var rgb = exports.HSVToRGB(h, s, v);
  1003. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1004. };
  1005. exports.hexToHSV = function(hex) {
  1006. var rgb = exports.hexToRGB(hex);
  1007. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1008. };
  1009. exports.isValidHex = function(hex) {
  1010. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1011. return isOk;
  1012. };
  1013. exports.isValidRGB = function(rgb) {
  1014. rgb = rgb.replace(" ","");
  1015. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1016. return isOk;
  1017. }
  1018. /**
  1019. * This recursively redirects the prototype of JSON objects to the referenceObject
  1020. * This is used for default options.
  1021. *
  1022. * @param referenceObject
  1023. * @returns {*}
  1024. */
  1025. exports.selectiveBridgeObject = function(fields, referenceObject) {
  1026. if (typeof referenceObject == "object") {
  1027. var objectTo = Object.create(referenceObject);
  1028. for (var i = 0; i < fields.length; i++) {
  1029. if (referenceObject.hasOwnProperty(fields[i])) {
  1030. if (typeof referenceObject[fields[i]] == "object") {
  1031. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1032. }
  1033. }
  1034. }
  1035. return objectTo;
  1036. }
  1037. else {
  1038. return null;
  1039. }
  1040. };
  1041. /**
  1042. * This recursively redirects the prototype of JSON objects to the referenceObject
  1043. * This is used for default options.
  1044. *
  1045. * @param referenceObject
  1046. * @returns {*}
  1047. */
  1048. exports.bridgeObject = function(referenceObject) {
  1049. if (typeof referenceObject == "object") {
  1050. var objectTo = Object.create(referenceObject);
  1051. for (var i in referenceObject) {
  1052. if (referenceObject.hasOwnProperty(i)) {
  1053. if (typeof referenceObject[i] == "object") {
  1054. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1055. }
  1056. }
  1057. }
  1058. return objectTo;
  1059. }
  1060. else {
  1061. return null;
  1062. }
  1063. };
  1064. /**
  1065. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1066. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1067. *
  1068. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1069. * @param [object] options | options
  1070. * @param [String] option | this is the option key in the options argument
  1071. * @private
  1072. */
  1073. exports.mergeOptions = function (mergeTarget, options, option) {
  1074. if (options[option] !== undefined) {
  1075. if (typeof options[option] == 'boolean') {
  1076. mergeTarget[option].enabled = options[option];
  1077. }
  1078. else {
  1079. mergeTarget[option].enabled = true;
  1080. for (prop in options[option]) {
  1081. if (options[option].hasOwnProperty(prop)) {
  1082. mergeTarget[option][prop] = options[option][prop];
  1083. }
  1084. }
  1085. }
  1086. }
  1087. }
  1088. /**
  1089. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1090. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1091. *
  1092. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1093. * @param [object] options | options
  1094. * @param [String] option | this is the option key in the options argument
  1095. * @private
  1096. */
  1097. exports.mergeOptions = function (mergeTarget, options, option) {
  1098. if (options[option] !== undefined) {
  1099. if (typeof options[option] == 'boolean') {
  1100. mergeTarget[option].enabled = options[option];
  1101. }
  1102. else {
  1103. mergeTarget[option].enabled = true;
  1104. for (prop in options[option]) {
  1105. if (options[option].hasOwnProperty(prop)) {
  1106. mergeTarget[option][prop] = options[option][prop];
  1107. }
  1108. }
  1109. }
  1110. }
  1111. }
  1112. /**
  1113. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  1114. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  1115. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check
  1116. * if the time we selected (start or end) is within the current range).
  1117. *
  1118. * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is
  1119. * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest,
  1120. * either the start OR end time has to be in the range.
  1121. *
  1122. * @param {Item[]} orderedItems Items ordered by start
  1123. * @param {{start: number, end: number}} range
  1124. * @param {String} field
  1125. * @param {String} field2
  1126. * @returns {number}
  1127. * @private
  1128. */
  1129. exports.binarySearch = function(orderedItems, range, field, field2) {
  1130. var array = orderedItems;
  1131. var maxIterations = 10000;
  1132. var iteration = 0;
  1133. var found = false;
  1134. var low = 0;
  1135. var high = array.length;
  1136. var newLow = low;
  1137. var newHigh = high;
  1138. var guess = Math.floor(0.5*(high+low));
  1139. var value;
  1140. if (high == 0) {
  1141. guess = -1;
  1142. }
  1143. else if (high == 1) {
  1144. if (array[guess].isVisible(range)) {
  1145. guess = 0;
  1146. }
  1147. else {
  1148. guess = -1;
  1149. }
  1150. }
  1151. else {
  1152. high -= 1;
  1153. while (found == false && iteration < maxIterations) {
  1154. value = field2 === undefined ? array[guess][field] : array[guess][field][field2];
  1155. if (array[guess].isVisible(range)) {
  1156. found = true;
  1157. }
  1158. else {
  1159. if (value < range.start) { // it is too small --> increase low
  1160. newLow = Math.floor(0.5*(high+low));
  1161. }
  1162. else { // it is too big --> decrease high
  1163. newHigh = Math.floor(0.5*(high+low));
  1164. }
  1165. // not in list;
  1166. if (low == newLow && high == newHigh) {
  1167. guess = -1;
  1168. found = true;
  1169. }
  1170. else {
  1171. high = newHigh; low = newLow;
  1172. guess = Math.floor(0.5*(high+low));
  1173. }
  1174. }
  1175. iteration++;
  1176. }
  1177. if (iteration >= maxIterations) {
  1178. console.log("BinarySearch too many iterations. Aborting.");
  1179. }
  1180. }
  1181. return guess;
  1182. };
  1183. /**
  1184. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  1185. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  1186. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check
  1187. * if the time we selected (start or end) is within the current range).
  1188. *
  1189. * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is
  1190. * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest,
  1191. * either the start OR end time has to be in the range.
  1192. *
  1193. * @param {Array} orderedItems
  1194. * @param {{start: number, end: number}} target
  1195. * @param {String} field
  1196. * @param {String} sidePreference 'before' or 'after'
  1197. * @returns {number}
  1198. * @private
  1199. */
  1200. exports.binarySearchGeneric = function(orderedItems, target, field, sidePreference) {
  1201. var maxIterations = 10000;
  1202. var iteration = 0;
  1203. var array = orderedItems;
  1204. var found = false;
  1205. var low = 0;
  1206. var high = array.length;
  1207. var newLow = low;
  1208. var newHigh = high;
  1209. var guess = Math.floor(0.5*(high+low));
  1210. var newGuess;
  1211. var prevValue, value, nextValue;
  1212. if (high == 0) {guess = -1;}
  1213. else if (high == 1) {
  1214. value = array[guess][field];
  1215. if (value == target) {
  1216. guess = 0;
  1217. }
  1218. else {
  1219. guess = -1;
  1220. }
  1221. }
  1222. else {
  1223. high -= 1;
  1224. while (found == false && iteration < maxIterations) {
  1225. prevValue = array[Math.max(0,guess - 1)][field];
  1226. value = array[guess][field];
  1227. nextValue = array[Math.min(array.length-1,guess + 1)][field];
  1228. if (value == target || prevValue < target && value > target || value < target && nextValue > target) {
  1229. found = true;
  1230. if (value != target) {
  1231. if (sidePreference == 'before') {
  1232. if (prevValue < target && value > target) {
  1233. guess = Math.max(0,guess - 1);
  1234. }
  1235. }
  1236. else {
  1237. if (value < target && nextValue > target) {
  1238. guess = Math.min(array.length-1,guess + 1);
  1239. }
  1240. }
  1241. }
  1242. }
  1243. else {
  1244. if (value < target) { // it is too small --> increase low
  1245. newLow = Math.floor(0.5*(high+low));
  1246. }
  1247. else { // it is too big --> decrease high
  1248. newHigh = Math.floor(0.5*(high+low));
  1249. }
  1250. newGuess = Math.floor(0.5*(high+low));
  1251. // not in list;
  1252. if (low == newLow && high == newHigh) {
  1253. guess = -1;
  1254. found = true;
  1255. }
  1256. else {
  1257. high = newHigh; low = newLow;
  1258. guess = Math.floor(0.5*(high+low));
  1259. }
  1260. }
  1261. iteration++;
  1262. }
  1263. if (iteration >= maxIterations) {
  1264. console.log("BinarySearch too many iterations. Aborting.");
  1265. }
  1266. }
  1267. return guess;
  1268. };
  1269. /***/ },
  1270. /* 2 */
  1271. /***/ function(module, exports, __webpack_require__) {
  1272. // DOM utility methods
  1273. /**
  1274. * this prepares the JSON container for allocating SVG elements
  1275. * @param JSONcontainer
  1276. * @private
  1277. */
  1278. exports.prepareElements = function(JSONcontainer) {
  1279. // cleanup the redundant svgElements;
  1280. for (var elementType in JSONcontainer) {
  1281. if (JSONcontainer.hasOwnProperty(elementType)) {
  1282. JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
  1283. JSONcontainer[elementType].used = [];
  1284. }
  1285. }
  1286. };
  1287. /**
  1288. * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
  1289. * which to remove the redundant elements.
  1290. *
  1291. * @param JSONcontainer
  1292. * @private
  1293. */
  1294. exports.cleanupElements = function(JSONcontainer) {
  1295. // cleanup the redundant svgElements;
  1296. for (var elementType in JSONcontainer) {
  1297. if (JSONcontainer.hasOwnProperty(elementType)) {
  1298. if (JSONcontainer[elementType].redundant) {
  1299. for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
  1300. JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
  1301. }
  1302. JSONcontainer[elementType].redundant = [];
  1303. }
  1304. }
  1305. }
  1306. };
  1307. /**
  1308. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  1309. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  1310. *
  1311. * @param elementType
  1312. * @param JSONcontainer
  1313. * @param svgContainer
  1314. * @returns {*}
  1315. * @private
  1316. */
  1317. exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
  1318. var element;
  1319. // allocate SVG element, if it doesnt yet exist, create one.
  1320. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  1321. // check if there is an redundant element
  1322. if (JSONcontainer[elementType].redundant.length > 0) {
  1323. element = JSONcontainer[elementType].redundant[0];
  1324. JSONcontainer[elementType].redundant.shift();
  1325. }
  1326. else {
  1327. // create a new element and add it to the SVG
  1328. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  1329. svgContainer.appendChild(element);
  1330. }
  1331. }
  1332. else {
  1333. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  1334. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  1335. JSONcontainer[elementType] = {used: [], redundant: []};
  1336. svgContainer.appendChild(element);
  1337. }
  1338. JSONcontainer[elementType].used.push(element);
  1339. return element;
  1340. };
  1341. /**
  1342. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  1343. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  1344. *
  1345. * @param elementType
  1346. * @param JSONcontainer
  1347. * @param DOMContainer
  1348. * @returns {*}
  1349. * @private
  1350. */
  1351. exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer) {
  1352. var element;
  1353. // allocate DOM element, if it doesnt yet exist, create one.
  1354. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  1355. // check if there is an redundant element
  1356. if (JSONcontainer[elementType].redundant.length > 0) {
  1357. element = JSONcontainer[elementType].redundant[0];
  1358. JSONcontainer[elementType].redundant.shift();
  1359. }
  1360. else {
  1361. // create a new element and add it to the SVG
  1362. element = document.createElement(elementType);
  1363. DOMContainer.appendChild(element);
  1364. }
  1365. }
  1366. else {
  1367. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  1368. element = document.createElement(elementType);
  1369. JSONcontainer[elementType] = {used: [], redundant: []};
  1370. DOMContainer.appendChild(element);
  1371. }
  1372. JSONcontainer[elementType].used.push(element);
  1373. return element;
  1374. };
  1375. /**
  1376. * draw a point object. this is a seperate function because it can also be called by the legend.
  1377. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
  1378. * as well.
  1379. *
  1380. * @param x
  1381. * @param y
  1382. * @param group
  1383. * @param JSONcontainer
  1384. * @param svgContainer
  1385. * @returns {*}
  1386. */
  1387. exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) {
  1388. var point;
  1389. if (group.options.drawPoints.style == 'circle') {
  1390. point = exports.getSVGElement('circle',JSONcontainer,svgContainer);
  1391. point.setAttributeNS(null, "cx", x);
  1392. point.setAttributeNS(null, "cy", y);
  1393. point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size);
  1394. point.setAttributeNS(null, "class", group.className + " point");
  1395. }
  1396. else {
  1397. point = exports.getSVGElement('rect',JSONcontainer,svgContainer);
  1398. point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size);
  1399. point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size);
  1400. point.setAttributeNS(null, "width", group.options.drawPoints.size);
  1401. point.setAttributeNS(null, "height", group.options.drawPoints.size);
  1402. point.setAttributeNS(null, "class", group.className + " point");
  1403. }
  1404. return point;
  1405. };
  1406. /**
  1407. * draw a bar SVG element centered on the X coordinate
  1408. *
  1409. * @param x
  1410. * @param y
  1411. * @param className
  1412. */
  1413. exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
  1414. // if (height != 0) {
  1415. var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer);
  1416. rect.setAttributeNS(null, "x", x - 0.5 * width);
  1417. rect.setAttributeNS(null, "y", y);
  1418. rect.setAttributeNS(null, "width", width);
  1419. rect.setAttributeNS(null, "height", height);
  1420. rect.setAttributeNS(null, "class", className);
  1421. // }
  1422. };
  1423. /***/ },
  1424. /* 3 */
  1425. /***/ function(module, exports, __webpack_require__) {
  1426. var util = __webpack_require__(1);
  1427. /**
  1428. * DataSet
  1429. *
  1430. * Usage:
  1431. * var dataSet = new DataSet({
  1432. * fieldId: '_id',
  1433. * type: {
  1434. * // ...
  1435. * }
  1436. * });
  1437. *
  1438. * dataSet.add(item);
  1439. * dataSet.add(data);
  1440. * dataSet.update(item);
  1441. * dataSet.update(data);
  1442. * dataSet.remove(id);
  1443. * dataSet.remove(ids);
  1444. * var data = dataSet.get();
  1445. * var data = dataSet.get(id);
  1446. * var data = dataSet.get(ids);
  1447. * var data = dataSet.get(ids, options, data);
  1448. * dataSet.clear();
  1449. *
  1450. * A data set can:
  1451. * - add/remove/update data
  1452. * - gives triggers upon changes in the data
  1453. * - can import/export data in various data formats
  1454. *
  1455. * @param {Array | DataTable} [data] Optional array with initial data
  1456. * @param {Object} [options] Available options:
  1457. * {String} fieldId Field name of the id in the
  1458. * items, 'id' by default.
  1459. * {Object.<String, String} type
  1460. * A map with field names as key,
  1461. * and the field type as value.
  1462. * @constructor DataSet
  1463. */
  1464. // TODO: add a DataSet constructor DataSet(data, options)
  1465. function DataSet (data, options) {
  1466. // correctly read optional arguments
  1467. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1468. options = data;
  1469. data = null;
  1470. }
  1471. this._options = options || {};
  1472. this._data = {}; // map with data indexed by id
  1473. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  1474. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  1475. // all variants of a Date are internally stored as Date, so we can convert
  1476. // from everything to everything (also from ISODate to Number for example)
  1477. if (this._options.type) {
  1478. for (var field in this._options.type) {
  1479. if (this._options.type.hasOwnProperty(field)) {
  1480. var value = this._options.type[field];
  1481. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1482. this._type[field] = 'Date';
  1483. }
  1484. else {
  1485. this._type[field] = value;
  1486. }
  1487. }
  1488. }
  1489. }
  1490. // TODO: deprecated since version 1.1.1 (or 2.0.0?)
  1491. if (this._options.convert) {
  1492. throw new Error('Option "convert" is deprecated. Use "type" instead.');
  1493. }
  1494. this._subscribers = {}; // event subscribers
  1495. // add initial data when provided
  1496. if (data) {
  1497. this.add(data);
  1498. }
  1499. }
  1500. /**
  1501. * Subscribe to an event, add an event listener
  1502. * @param {String} event Event name. Available events: 'put', 'update',
  1503. * 'remove'
  1504. * @param {function} callback Callback method. Called with three parameters:
  1505. * {String} event
  1506. * {Object | null} params
  1507. * {String | Number} senderId
  1508. */
  1509. DataSet.prototype.on = function(event, callback) {
  1510. var subscribers = this._subscribers[event];
  1511. if (!subscribers) {
  1512. subscribers = [];
  1513. this._subscribers[event] = subscribers;
  1514. }
  1515. subscribers.push({
  1516. callback: callback
  1517. });
  1518. };
  1519. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1520. DataSet.prototype.subscribe = DataSet.prototype.on;
  1521. /**
  1522. * Unsubscribe from an event, remove an event listener
  1523. * @param {String} event
  1524. * @param {function} callback
  1525. */
  1526. DataSet.prototype.off = function(event, callback) {
  1527. var subscribers = this._subscribers[event];
  1528. if (subscribers) {
  1529. this._subscribers[event] = subscribers.filter(function (listener) {
  1530. return (listener.callback != callback);
  1531. });
  1532. }
  1533. };
  1534. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1535. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1536. /**
  1537. * Trigger an event
  1538. * @param {String} event
  1539. * @param {Object | null} params
  1540. * @param {String} [senderId] Optional id of the sender.
  1541. * @private
  1542. */
  1543. DataSet.prototype._trigger = function (event, params, senderId) {
  1544. if (event == '*') {
  1545. throw new Error('Cannot trigger event *');
  1546. }
  1547. var subscribers = [];
  1548. if (event in this._subscribers) {
  1549. subscribers = subscribers.concat(this._subscribers[event]);
  1550. }
  1551. if ('*' in this._subscribers) {
  1552. subscribers = subscribers.concat(this._subscribers['*']);
  1553. }
  1554. for (var i = 0; i < subscribers.length; i++) {
  1555. var subscriber = subscribers[i];
  1556. if (subscriber.callback) {
  1557. subscriber.callback(event, params, senderId || null);
  1558. }
  1559. }
  1560. };
  1561. /**
  1562. * Add data.
  1563. * Adding an item will fail when there already is an item with the same id.
  1564. * @param {Object | Array | DataTable} data
  1565. * @param {String} [senderId] Optional sender id
  1566. * @return {Array} addedIds Array with the ids of the added items
  1567. */
  1568. DataSet.prototype.add = function (data, senderId) {
  1569. var addedIds = [],
  1570. id,
  1571. me = this;
  1572. if (Array.isArray(data)) {
  1573. // Array
  1574. for (var i = 0, len = data.length; i < len; i++) {
  1575. id = me._addItem(data[i]);
  1576. addedIds.push(id);
  1577. }
  1578. }
  1579. else if (util.isDataTable(data)) {
  1580. // Google DataTable
  1581. var columns = this._getColumnNames(data);
  1582. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1583. var item = {};
  1584. for (var col = 0, cols = columns.length; col < cols; col++) {
  1585. var field = columns[col];
  1586. item[field] = data.getValue(row, col);
  1587. }
  1588. id = me._addItem(item);
  1589. addedIds.push(id);
  1590. }
  1591. }
  1592. else if (data instanceof Object) {
  1593. // Single item
  1594. id = me._addItem(data);
  1595. addedIds.push(id);
  1596. }
  1597. else {
  1598. throw new Error('Unknown dataType');
  1599. }
  1600. if (addedIds.length) {
  1601. this._trigger('add', {items: addedIds}, senderId);
  1602. }
  1603. return addedIds;
  1604. };
  1605. /**
  1606. * Update existing items. When an item does not exist, it will be created
  1607. * @param {Object | Array | DataTable} data
  1608. * @param {String} [senderId] Optional sender id
  1609. * @return {Array} updatedIds The ids of the added or updated items
  1610. */
  1611. DataSet.prototype.update = function (data, senderId) {
  1612. var addedIds = [],
  1613. updatedIds = [],
  1614. me = this,
  1615. fieldId = me._fieldId;
  1616. var addOrUpdate = function (item) {
  1617. var id = item[fieldId];
  1618. if (me._data[id]) {
  1619. // update item
  1620. id = me._updateItem(item);
  1621. updatedIds.push(id);
  1622. }
  1623. else {
  1624. // add new item
  1625. id = me._addItem(item);
  1626. addedIds.push(id);
  1627. }
  1628. };
  1629. if (Array.isArray(data)) {
  1630. // Array
  1631. for (var i = 0, len = data.length; i < len; i++) {
  1632. addOrUpdate(data[i]);
  1633. }
  1634. }
  1635. else if (util.isDataTable(data)) {
  1636. // Google DataTable
  1637. var columns = this._getColumnNames(data);
  1638. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1639. var item = {};
  1640. for (var col = 0, cols = columns.length; col < cols; col++) {
  1641. var field = columns[col];
  1642. item[field] = data.getValue(row, col);
  1643. }
  1644. addOrUpdate(item);
  1645. }
  1646. }
  1647. else if (data instanceof Object) {
  1648. // Single item
  1649. addOrUpdate(data);
  1650. }
  1651. else {
  1652. throw new Error('Unknown dataType');
  1653. }
  1654. if (addedIds.length) {
  1655. this._trigger('add', {items: addedIds}, senderId);
  1656. }
  1657. if (updatedIds.length) {
  1658. this._trigger('update', {items: updatedIds}, senderId);
  1659. }
  1660. return addedIds.concat(updatedIds);
  1661. };
  1662. /**
  1663. * Get a data item or multiple items.
  1664. *
  1665. * Usage:
  1666. *
  1667. * get()
  1668. * get(options: Object)
  1669. * get(options: Object, data: Array | DataTable)
  1670. *
  1671. * get(id: Number | String)
  1672. * get(id: Number | String, options: Object)
  1673. * get(id: Number | String, options: Object, data: Array | DataTable)
  1674. *
  1675. * get(ids: Number[] | String[])
  1676. * get(ids: Number[] | String[], options: Object)
  1677. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1678. *
  1679. * Where:
  1680. *
  1681. * {Number | String} id The id of an item
  1682. * {Number[] | String{}} ids An array with ids of items
  1683. * {Object} options An Object with options. Available options:
  1684. * {String} [returnType] Type of data to be
  1685. * returned. Can be 'DataTable' or 'Array' (default)
  1686. * {Object.<String, String>} [type]
  1687. * {String[]} [fields] field names to be returned
  1688. * {function} [filter] filter items
  1689. * {String | function} [order] Order the items by
  1690. * a field name or custom sort function.
  1691. * {Array | DataTable} [data] If provided, items will be appended to this
  1692. * array or table. Required in case of Google
  1693. * DataTable.
  1694. *
  1695. * @throws Error
  1696. */
  1697. DataSet.prototype.get = function (args) {
  1698. var me = this;
  1699. // parse the arguments
  1700. var id, ids, options, data;
  1701. var firstType = util.getType(arguments[0]);
  1702. if (firstType == 'String' || firstType == 'Number') {
  1703. // get(id [, options] [, data])
  1704. id = arguments[0];
  1705. options = arguments[1];
  1706. data = arguments[2];
  1707. }
  1708. else if (firstType == 'Array') {
  1709. // get(ids [, options] [, data])
  1710. ids = arguments[0];
  1711. options = arguments[1];
  1712. data = arguments[2];
  1713. }
  1714. else {
  1715. // get([, options] [, data])
  1716. options = arguments[0];
  1717. data = arguments[1];
  1718. }
  1719. // determine the return type
  1720. var returnType;
  1721. if (options && options.returnType) {
  1722. var allowedValues = ["DataTable", "Array", "Object"];
  1723. returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
  1724. if (data && (returnType != util.getType(data))) {
  1725. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1726. 'does not correspond with specified options.type (' + options.type + ')');
  1727. }
  1728. if (returnType == 'DataTable' && !util.isDataTable(data)) {
  1729. throw new Error('Parameter "data" must be a DataTable ' +
  1730. 'when options.type is "DataTable"');
  1731. }
  1732. }
  1733. else if (data) {
  1734. returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1735. }
  1736. else {
  1737. returnType = 'Array';
  1738. }
  1739. // build options
  1740. var type = options && options.type || this._options.type;
  1741. var filter = options && options.filter;
  1742. var items = [], item, itemId, i, len;
  1743. // convert items
  1744. if (id != undefined) {
  1745. // return a single item
  1746. item = me._getItem(id, type);
  1747. if (filter && !filter(item)) {
  1748. item = null;
  1749. }
  1750. }
  1751. else if (ids != undefined) {
  1752. // return a subset of items
  1753. for (i = 0, len = ids.length; i < len; i++) {
  1754. item = me._getItem(ids[i], type);
  1755. if (!filter || filter(item)) {
  1756. items.push(item);
  1757. }
  1758. }
  1759. }
  1760. else {
  1761. // return all items
  1762. for (itemId in this._data) {
  1763. if (this._data.hasOwnProperty(itemId)) {
  1764. item = me._getItem(itemId, type);
  1765. if (!filter || filter(item)) {
  1766. items.push(item);
  1767. }
  1768. }
  1769. }
  1770. }
  1771. // order the results
  1772. if (options && options.order && id == undefined) {
  1773. this._sort(items, options.order);
  1774. }
  1775. // filter fields of the items
  1776. if (options && options.fields) {
  1777. var fields = options.fields;
  1778. if (id != undefined) {
  1779. item = this._filterFields(item, fields);
  1780. }
  1781. else {
  1782. for (i = 0, len = items.length; i < len; i++) {
  1783. items[i] = this._filterFields(items[i], fields);
  1784. }
  1785. }
  1786. }
  1787. // return the results
  1788. if (returnType == 'DataTable') {
  1789. var columns = this._getColumnNames(data);
  1790. if (id != undefined) {
  1791. // append a single item to the data table
  1792. me._appendRow(data, columns, item);
  1793. }
  1794. else {
  1795. // copy the items to the provided data table
  1796. for (i = 0; i < items.length; i++) {
  1797. me._appendRow(data, columns, items[i]);
  1798. }
  1799. }
  1800. return data;
  1801. }
  1802. else if (returnType == "Object") {
  1803. var result = {};
  1804. for (i = 0; i < items.length; i++) {
  1805. result[items[i].id] = items[i];
  1806. }
  1807. return result;
  1808. }
  1809. else {
  1810. // return an array
  1811. if (id != undefined) {
  1812. // a single item
  1813. return item;
  1814. }
  1815. else {
  1816. // multiple items
  1817. if (data) {
  1818. // copy the items to the provided array
  1819. for (i = 0, len = items.length; i < len; i++) {
  1820. data.push(items[i]);
  1821. }
  1822. return data;
  1823. }
  1824. else {
  1825. // just return our array
  1826. return items;
  1827. }
  1828. }
  1829. }
  1830. };
  1831. /**
  1832. * Get ids of all items or from a filtered set of items.
  1833. * @param {Object} [options] An Object with options. Available options:
  1834. * {function} [filter] filter items
  1835. * {String | function} [order] Order the items by
  1836. * a field name or custom sort function.
  1837. * @return {Array} ids
  1838. */
  1839. DataSet.prototype.getIds = function (options) {
  1840. var data = this._data,
  1841. filter = options && options.filter,
  1842. order = options && options.order,
  1843. type = options && options.type || this._options.type,
  1844. i,
  1845. len,
  1846. id,
  1847. item,
  1848. items,
  1849. ids = [];
  1850. if (filter) {
  1851. // get filtered items
  1852. if (order) {
  1853. // create ordered list
  1854. items = [];
  1855. for (id in data) {
  1856. if (data.hasOwnProperty(id)) {
  1857. item = this._getItem(id, type);
  1858. if (filter(item)) {
  1859. items.push(item);
  1860. }
  1861. }
  1862. }
  1863. this._sort(items, order);
  1864. for (i = 0, len = items.length; i < len; i++) {
  1865. ids[i] = items[i][this._fieldId];
  1866. }
  1867. }
  1868. else {
  1869. // create unordered list
  1870. for (id in data) {
  1871. if (data.hasOwnProperty(id)) {
  1872. item = this._getItem(id, type);
  1873. if (filter(item)) {
  1874. ids.push(item[this._fieldId]);
  1875. }
  1876. }
  1877. }
  1878. }
  1879. }
  1880. else {
  1881. // get all items
  1882. if (order) {
  1883. // create an ordered list
  1884. items = [];
  1885. for (id in data) {
  1886. if (data.hasOwnProperty(id)) {
  1887. items.push(data[id]);
  1888. }
  1889. }
  1890. this._sort(items, order);
  1891. for (i = 0, len = items.length; i < len; i++) {
  1892. ids[i] = items[i][this._fieldId];
  1893. }
  1894. }
  1895. else {
  1896. // create unordered list
  1897. for (id in data) {
  1898. if (data.hasOwnProperty(id)) {
  1899. item = data[id];
  1900. ids.push(item[this._fieldId]);
  1901. }
  1902. }
  1903. }
  1904. }
  1905. return ids;
  1906. };
  1907. /**
  1908. * Returns the DataSet itself. Is overwritten for example by the DataView,
  1909. * which returns the DataSet it is connected to instead.
  1910. */
  1911. DataSet.prototype.getDataSet = function () {
  1912. return this;
  1913. };
  1914. /**
  1915. * Execute a callback function for every item in the dataset.
  1916. * @param {function} callback
  1917. * @param {Object} [options] Available options:
  1918. * {Object.<String, String>} [type]
  1919. * {String[]} [fields] filter fields
  1920. * {function} [filter] filter items
  1921. * {String | function} [order] Order the items by
  1922. * a field name or custom sort function.
  1923. */
  1924. DataSet.prototype.forEach = function (callback, options) {
  1925. var filter = options && options.filter,
  1926. type = options && options.type || this._options.type,
  1927. data = this._data,
  1928. item,
  1929. id;
  1930. if (options && options.order) {
  1931. // execute forEach on ordered list
  1932. var items = this.get(options);
  1933. for (var i = 0, len = items.length; i < len; i++) {
  1934. item = items[i];
  1935. id = item[this._fieldId];
  1936. callback(item, id);
  1937. }
  1938. }
  1939. else {
  1940. // unordered
  1941. for (id in data) {
  1942. if (data.hasOwnProperty(id)) {
  1943. item = this._getItem(id, type);
  1944. if (!filter || filter(item)) {
  1945. callback(item, id);
  1946. }
  1947. }
  1948. }
  1949. }
  1950. };
  1951. /**
  1952. * Map every item in the dataset.
  1953. * @param {function} callback
  1954. * @param {Object} [options] Available options:
  1955. * {Object.<String, String>} [type]
  1956. * {String[]} [fields] filter fields
  1957. * {function} [filter] filter items
  1958. * {String | function} [order] Order the items by
  1959. * a field name or custom sort function.
  1960. * @return {Object[]} mappedItems
  1961. */
  1962. DataSet.prototype.map = function (callback, options) {
  1963. var filter = options && options.filter,
  1964. type = options && options.type || this._options.type,
  1965. mappedItems = [],
  1966. data = this._data,
  1967. item;
  1968. // convert and filter items
  1969. for (var id in data) {
  1970. if (data.hasOwnProperty(id)) {
  1971. item = this._getItem(id, type);
  1972. if (!filter || filter(item)) {
  1973. mappedItems.push(callback(item, id));
  1974. }
  1975. }
  1976. }
  1977. // order items
  1978. if (options && options.order) {
  1979. this._sort(mappedItems, options.order);
  1980. }
  1981. return mappedItems;
  1982. };
  1983. /**
  1984. * Filter the fields of an item
  1985. * @param {Object} item
  1986. * @param {String[]} fields Field names
  1987. * @return {Object} filteredItem
  1988. * @private
  1989. */
  1990. DataSet.prototype._filterFields = function (item, fields) {
  1991. var filteredItem = {};
  1992. for (var field in item) {
  1993. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1994. filteredItem[field] = item[field];
  1995. }
  1996. }
  1997. return filteredItem;
  1998. };
  1999. /**
  2000. * Sort the provided array with items
  2001. * @param {Object[]} items
  2002. * @param {String | function} order A field name or custom sort function.
  2003. * @private
  2004. */
  2005. DataSet.prototype._sort = function (items, order) {
  2006. if (util.isString(order)) {
  2007. // order by provided field name
  2008. var name = order; // field name
  2009. items.sort(function (a, b) {
  2010. var av = a[name];
  2011. var bv = b[name];
  2012. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  2013. });
  2014. }
  2015. else if (typeof order === 'function') {
  2016. // order by sort function
  2017. items.sort(order);
  2018. }
  2019. // TODO: extend order by an Object {field:String, direction:String}
  2020. // where direction can be 'asc' or 'desc'
  2021. else {
  2022. throw new TypeError('Order must be a function or a string');
  2023. }
  2024. };
  2025. /**
  2026. * Remove an object by pointer or by id
  2027. * @param {String | Number | Object | Array} id Object or id, or an array with
  2028. * objects or ids to be removed
  2029. * @param {String} [senderId] Optional sender id
  2030. * @return {Array} removedIds
  2031. */
  2032. DataSet.prototype.remove = function (id, senderId) {
  2033. var removedIds = [],
  2034. i, len, removedId;
  2035. if (Array.isArray(id)) {
  2036. for (i = 0, len = id.length; i < len; i++) {
  2037. removedId = this._remove(id[i]);
  2038. if (removedId != null) {
  2039. removedIds.push(removedId);
  2040. }
  2041. }
  2042. }
  2043. else {
  2044. removedId = this._remove(id);
  2045. if (removedId != null) {
  2046. removedIds.push(removedId);
  2047. }
  2048. }
  2049. if (removedIds.length) {
  2050. this._trigger('remove', {items: removedIds}, senderId);
  2051. }
  2052. return removedIds;
  2053. };
  2054. /**
  2055. * Remove an item by its id
  2056. * @param {Number | String | Object} id id or item
  2057. * @returns {Number | String | null} id
  2058. * @private
  2059. */
  2060. DataSet.prototype._remove = function (id) {
  2061. if (util.isNumber(id) || util.isString(id)) {
  2062. if (this._data[id]) {
  2063. delete this._data[id];
  2064. return id;
  2065. }
  2066. }
  2067. else if (id instanceof Object) {
  2068. var itemId = id[this._fieldId];
  2069. if (itemId && this._data[itemId]) {
  2070. delete this._data[itemId];
  2071. return itemId;
  2072. }
  2073. }
  2074. return null;
  2075. };
  2076. /**
  2077. * Clear the data
  2078. * @param {String} [senderId] Optional sender id
  2079. * @return {Array} removedIds The ids of all removed items
  2080. */
  2081. DataSet.prototype.clear = function (senderId) {
  2082. var ids = Object.keys(this._data);
  2083. this._data = {};
  2084. this._trigger('remove', {items: ids}, senderId);
  2085. return ids;
  2086. };
  2087. /**
  2088. * Find the item with maximum value of a specified field
  2089. * @param {String} field
  2090. * @return {Object | null} item Item containing max value, or null if no items
  2091. */
  2092. DataSet.prototype.max = function (field) {
  2093. var data = this._data,
  2094. max = null,
  2095. maxField = null;
  2096. for (var id in data) {
  2097. if (data.hasOwnProperty(id)) {
  2098. var item = data[id];
  2099. var itemField = item[field];
  2100. if (itemField != null && (!max || itemField > maxField)) {
  2101. max = item;
  2102. maxField = itemField;
  2103. }
  2104. }
  2105. }
  2106. return max;
  2107. };
  2108. /**
  2109. * Find the item with minimum value of a specified field
  2110. * @param {String} field
  2111. * @return {Object | null} item Item containing max value, or null if no items
  2112. */
  2113. DataSet.prototype.min = function (field) {
  2114. var data = this._data,
  2115. min = null,
  2116. minField = null;
  2117. for (var id in data) {
  2118. if (data.hasOwnProperty(id)) {
  2119. var item = data[id];
  2120. var itemField = item[field];
  2121. if (itemField != null && (!min || itemField < minField)) {
  2122. min = item;
  2123. minField = itemField;
  2124. }
  2125. }
  2126. }
  2127. return min;
  2128. };
  2129. /**
  2130. * Find all distinct values of a specified field
  2131. * @param {String} field
  2132. * @return {Array} values Array containing all distinct values. If data items
  2133. * do not contain the specified field are ignored.
  2134. * The returned array is unordered.
  2135. */
  2136. DataSet.prototype.distinct = function (field) {
  2137. var data = this._data;
  2138. var values = [];
  2139. var fieldType = this._options.type && this._options.type[field] || null;
  2140. var count = 0;
  2141. var i;
  2142. for (var prop in data) {
  2143. if (data.hasOwnProperty(prop)) {
  2144. var item = data[prop];
  2145. var value = item[field];
  2146. var exists = false;
  2147. for (i = 0; i < count; i++) {
  2148. if (values[i] == value) {
  2149. exists = true;
  2150. break;
  2151. }
  2152. }
  2153. if (!exists && (value !== undefined)) {
  2154. values[count] = value;
  2155. count++;
  2156. }
  2157. }
  2158. }
  2159. if (fieldType) {
  2160. for (i = 0; i < values.length; i++) {
  2161. values[i] = util.convert(values[i], fieldType);
  2162. }
  2163. }
  2164. return values;
  2165. };
  2166. /**
  2167. * Add a single item. Will fail when an item with the same id already exists.
  2168. * @param {Object} item
  2169. * @return {String} id
  2170. * @private
  2171. */
  2172. DataSet.prototype._addItem = function (item) {
  2173. var id = item[this._fieldId];
  2174. if (id != undefined) {
  2175. // check whether this id is already taken
  2176. if (this._data[id]) {
  2177. // item already exists
  2178. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  2179. }
  2180. }
  2181. else {
  2182. // generate an id
  2183. id = util.randomUUID();
  2184. item[this._fieldId] = id;
  2185. }
  2186. var d = {};
  2187. for (var field in item) {
  2188. if (item.hasOwnProperty(field)) {
  2189. var fieldType = this._type[field]; // type may be undefined
  2190. d[field] = util.convert(item[field], fieldType);
  2191. }
  2192. }
  2193. this._data[id] = d;
  2194. return id;
  2195. };
  2196. /**
  2197. * Get an item. Fields can be converted to a specific type
  2198. * @param {String} id
  2199. * @param {Object.<String, String>} [types] field types to convert
  2200. * @return {Object | null} item
  2201. * @private
  2202. */
  2203. DataSet.prototype._getItem = function (id, types) {
  2204. var field, value;
  2205. // get the item from the dataset
  2206. var raw = this._data[id];
  2207. if (!raw) {
  2208. return null;
  2209. }
  2210. // convert the items field types
  2211. var converted = {};
  2212. if (types) {
  2213. for (field in raw) {
  2214. if (raw.hasOwnProperty(field)) {
  2215. value = raw[field];
  2216. converted[field] = util.convert(value, types[field]);
  2217. }
  2218. }
  2219. }
  2220. else {
  2221. // no field types specified, no converting needed
  2222. for (field in raw) {
  2223. if (raw.hasOwnProperty(field)) {
  2224. value = raw[field];
  2225. converted[field] = value;
  2226. }
  2227. }
  2228. }
  2229. return converted;
  2230. };
  2231. /**
  2232. * Update a single item: merge with existing item.
  2233. * Will fail when the item has no id, or when there does not exist an item
  2234. * with the same id.
  2235. * @param {Object} item
  2236. * @return {String} id
  2237. * @private
  2238. */
  2239. DataSet.prototype._updateItem = function (item) {
  2240. var id = item[this._fieldId];
  2241. if (id == undefined) {
  2242. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  2243. }
  2244. var d = this._data[id];
  2245. if (!d) {
  2246. // item doesn't exist
  2247. throw new Error('Cannot update item: no item with id ' + id + ' found');
  2248. }
  2249. // merge with current item
  2250. for (var field in item) {
  2251. if (item.hasOwnProperty(field)) {
  2252. var fieldType = this._type[field]; // type may be undefined
  2253. d[field] = util.convert(item[field], fieldType);
  2254. }
  2255. }
  2256. return id;
  2257. };
  2258. /**
  2259. * Get an array with the column names of a Google DataTable
  2260. * @param {DataTable} dataTable
  2261. * @return {String[]} columnNames
  2262. * @private
  2263. */
  2264. DataSet.prototype._getColumnNames = function (dataTable) {
  2265. var columns = [];
  2266. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  2267. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  2268. }
  2269. return columns;
  2270. };
  2271. /**
  2272. * Append an item as a row to the dataTable
  2273. * @param dataTable
  2274. * @param columns
  2275. * @param item
  2276. * @private
  2277. */
  2278. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  2279. var row = dataTable.addRow();
  2280. for (var col = 0, cols = columns.length; col < cols; col++) {
  2281. var field = columns[col];
  2282. dataTable.setValue(row, col, item[field]);
  2283. }
  2284. };
  2285. module.exports = DataSet;
  2286. /***/ },
  2287. /* 4 */
  2288. /***/ function(module, exports, __webpack_require__) {
  2289. var util = __webpack_require__(1);
  2290. var DataSet = __webpack_require__(3);
  2291. /**
  2292. * DataView
  2293. *
  2294. * a dataview offers a filtered view on a dataset or an other dataview.
  2295. *
  2296. * @param {DataSet | DataView} data
  2297. * @param {Object} [options] Available options: see method get
  2298. *
  2299. * @constructor DataView
  2300. */
  2301. function DataView (data, options) {
  2302. this._data = null;
  2303. this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
  2304. this._options = options || {};
  2305. this._fieldId = 'id'; // name of the field containing id
  2306. this._subscribers = {}; // event subscribers
  2307. var me = this;
  2308. this.listener = function () {
  2309. me._onEvent.apply(me, arguments);
  2310. };
  2311. this.setData(data);
  2312. }
  2313. // TODO: implement a function .config() to dynamically update things like configured filter
  2314. // and trigger changes accordingly
  2315. /**
  2316. * Set a data source for the view
  2317. * @param {DataSet | DataView} data
  2318. */
  2319. DataView.prototype.setData = function (data) {
  2320. var ids, i, len;
  2321. if (this._data) {
  2322. // unsubscribe from current dataset
  2323. if (this._data.unsubscribe) {
  2324. this._data.unsubscribe('*', this.listener);
  2325. }
  2326. // trigger a remove of all items in memory
  2327. ids = [];
  2328. for (var id in this._ids) {
  2329. if (this._ids.hasOwnProperty(id)) {
  2330. ids.push(id);
  2331. }
  2332. }
  2333. this._ids = {};
  2334. this._trigger('remove', {items: ids});
  2335. }
  2336. this._data = data;
  2337. if (this._data) {
  2338. // update fieldId
  2339. this._fieldId = this._options.fieldId ||
  2340. (this._data && this._data.options && this._data.options.fieldId) ||
  2341. 'id';
  2342. // trigger an add of all added items
  2343. ids = this._data.getIds({filter: this._options && this._options.filter});
  2344. for (i = 0, len = ids.length; i < len; i++) {
  2345. id = ids[i];
  2346. this._ids[id] = true;
  2347. }
  2348. this._trigger('add', {items: ids});
  2349. // subscribe to new dataset
  2350. if (this._data.on) {
  2351. this._data.on('*', this.listener);
  2352. }
  2353. }
  2354. };
  2355. /**
  2356. * Get data from the data view
  2357. *
  2358. * Usage:
  2359. *
  2360. * get()
  2361. * get(options: Object)
  2362. * get(options: Object, data: Array | DataTable)
  2363. *
  2364. * get(id: Number)
  2365. * get(id: Number, options: Object)
  2366. * get(id: Number, options: Object, data: Array | DataTable)
  2367. *
  2368. * get(ids: Number[])
  2369. * get(ids: Number[], options: Object)
  2370. * get(ids: Number[], options: Object, data: Array | DataTable)
  2371. *
  2372. * Where:
  2373. *
  2374. * {Number | String} id The id of an item
  2375. * {Number[] | String{}} ids An array with ids of items
  2376. * {Object} options An Object with options. Available options:
  2377. * {String} [type] Type of data to be returned. Can
  2378. * be 'DataTable' or 'Array' (default)
  2379. * {Object.<String, String>} [convert]
  2380. * {String[]} [fields] field names to be returned
  2381. * {function} [filter] filter items
  2382. * {String | function} [order] Order the items by
  2383. * a field name or custom sort function.
  2384. * {Array | DataTable} [data] If provided, items will be appended to this
  2385. * array or table. Required in case of Google
  2386. * DataTable.
  2387. * @param args
  2388. */
  2389. DataView.prototype.get = function (args) {
  2390. var me = this;
  2391. // parse the arguments
  2392. var ids, options, data;
  2393. var firstType = util.getType(arguments[0]);
  2394. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2395. // get(id(s) [, options] [, data])
  2396. ids = arguments[0]; // can be a single id or an array with ids
  2397. options = arguments[1];
  2398. data = arguments[2];
  2399. }
  2400. else {
  2401. // get([, options] [, data])
  2402. options = arguments[0];
  2403. data = arguments[1];
  2404. }
  2405. // extend the options with the default options and provided options
  2406. var viewOptions = util.extend({}, this._options, options);
  2407. // create a combined filter method when needed
  2408. if (this._options.filter && options && options.filter) {
  2409. viewOptions.filter = function (item) {
  2410. return me._options.filter(item) && options.filter(item);
  2411. }
  2412. }
  2413. // build up the call to the linked data set
  2414. var getArguments = [];
  2415. if (ids != undefined) {
  2416. getArguments.push(ids);
  2417. }
  2418. getArguments.push(viewOptions);
  2419. getArguments.push(data);
  2420. return this._data && this._data.get.apply(this._data, getArguments);
  2421. };
  2422. /**
  2423. * Get ids of all items or from a filtered set of items.
  2424. * @param {Object} [options] An Object with options. Available options:
  2425. * {function} [filter] filter items
  2426. * {String | function} [order] Order the items by
  2427. * a field name or custom sort function.
  2428. * @return {Array} ids
  2429. */
  2430. DataView.prototype.getIds = function (options) {
  2431. var ids;
  2432. if (this._data) {
  2433. var defaultFilter = this._options.filter;
  2434. var filter;
  2435. if (options && options.filter) {
  2436. if (defaultFilter) {
  2437. filter = function (item) {
  2438. return defaultFilter(item) && options.filter(item);
  2439. }
  2440. }
  2441. else {
  2442. filter = options.filter;
  2443. }
  2444. }
  2445. else {
  2446. filter = defaultFilter;
  2447. }
  2448. ids = this._data.getIds({
  2449. filter: filter,
  2450. order: options && options.order
  2451. });
  2452. }
  2453. else {
  2454. ids = [];
  2455. }
  2456. return ids;
  2457. };
  2458. /**
  2459. * Get the DataSet to which this DataView is connected. In case there is a chain
  2460. * of multiple DataViews, the root DataSet of this chain is returned.
  2461. * @return {DataSet} dataSet
  2462. */
  2463. DataView.prototype.getDataSet = function () {
  2464. var dataSet = this;
  2465. while (dataSet instanceof DataView) {
  2466. dataSet = dataSet._data;
  2467. }
  2468. return dataSet || null;
  2469. };
  2470. /**
  2471. * Event listener. Will propagate all events from the connected data set to
  2472. * the subscribers of the DataView, but will filter the items and only trigger
  2473. * when there are changes in the filtered data set.
  2474. * @param {String} event
  2475. * @param {Object | null} params
  2476. * @param {String} senderId
  2477. * @private
  2478. */
  2479. DataView.prototype._onEvent = function (event, params, senderId) {
  2480. var i, len, id, item,
  2481. ids = params && params.items,
  2482. data = this._data,
  2483. added = [],
  2484. updated = [],
  2485. removed = [];
  2486. if (ids && data) {
  2487. switch (event) {
  2488. case 'add':
  2489. // filter the ids of the added items
  2490. for (i = 0, len = ids.length; i < len; i++) {
  2491. id = ids[i];
  2492. item = this.get(id);
  2493. if (item) {
  2494. this._ids[id] = true;
  2495. added.push(id);
  2496. }
  2497. }
  2498. break;
  2499. case 'update':
  2500. // determine the event from the views viewpoint: an updated
  2501. // item can be added, updated, or removed from this view.
  2502. for (i = 0, len = ids.length; i < len; i++) {
  2503. id = ids[i];
  2504. item = this.get(id);
  2505. if (item) {
  2506. if (this._ids[id]) {
  2507. updated.push(id);
  2508. }
  2509. else {
  2510. this._ids[id] = true;
  2511. added.push(id);
  2512. }
  2513. }
  2514. else {
  2515. if (this._ids[id]) {
  2516. delete this._ids[id];
  2517. removed.push(id);
  2518. }
  2519. else {
  2520. // nothing interesting for me :-(
  2521. }
  2522. }
  2523. }
  2524. break;
  2525. case 'remove':
  2526. // filter the ids of the removed items
  2527. for (i = 0, len = ids.length; i < len; i++) {
  2528. id = ids[i];
  2529. if (this._ids[id]) {
  2530. delete this._ids[id];
  2531. removed.push(id);
  2532. }
  2533. }
  2534. break;
  2535. }
  2536. if (added.length) {
  2537. this._trigger('add', {items: added}, senderId);
  2538. }
  2539. if (updated.length) {
  2540. this._trigger('update', {items: updated}, senderId);
  2541. }
  2542. if (removed.length) {
  2543. this._trigger('remove', {items: removed}, senderId);
  2544. }
  2545. }
  2546. };
  2547. // copy subscription functionality from DataSet
  2548. DataView.prototype.on = DataSet.prototype.on;
  2549. DataView.prototype.off = DataSet.prototype.off;
  2550. DataView.prototype._trigger = DataSet.prototype._trigger;
  2551. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2552. DataView.prototype.subscribe = DataView.prototype.on;
  2553. DataView.prototype.unsubscribe = DataView.prototype.off;
  2554. module.exports = DataView;
  2555. /***/ },
  2556. /* 5 */
  2557. /***/ function(module, exports, __webpack_require__) {
  2558. var Emitter = __webpack_require__(46);
  2559. var DataSet = __webpack_require__(3);
  2560. var DataView = __webpack_require__(4);
  2561. var util = __webpack_require__(1);
  2562. var Point3d = __webpack_require__(9);
  2563. var Point2d = __webpack_require__(8);
  2564. var Camera = __webpack_require__(6);
  2565. var Filter = __webpack_require__(7);
  2566. var Slider = __webpack_require__(10);
  2567. var StepNumber = __webpack_require__(11);
  2568. /**
  2569. * @constructor Graph3d
  2570. * Graph3d displays data in 3d.
  2571. *
  2572. * Graph3d is developed in javascript as a Google Visualization Chart.
  2573. *
  2574. * @param {Element} container The DOM element in which the Graph3d will
  2575. * be created. Normally a div element.
  2576. * @param {DataSet | DataView | Array} [data]
  2577. * @param {Object} [options]
  2578. */
  2579. function Graph3d(container, data, options) {
  2580. if (!(this instanceof Graph3d)) {
  2581. throw new SyntaxError('Constructor must be called with the new operator');
  2582. }
  2583. // create variables and set default values
  2584. this.containerElement = container;
  2585. this.width = '400px';
  2586. this.height = '400px';
  2587. this.margin = 10; // px
  2588. this.defaultXCenter = '55%';
  2589. this.defaultYCenter = '50%';
  2590. this.xLabel = 'x';
  2591. this.yLabel = 'y';
  2592. this.zLabel = 'z';
  2593. this.filterLabel = 'time';
  2594. this.legendLabel = 'value';
  2595. this.style = Graph3d.STYLE.DOT;
  2596. this.showPerspective = true;
  2597. this.showGrid = true;
  2598. this.keepAspectRatio = true;
  2599. this.showShadow = false;
  2600. this.showGrayBottom = false; // TODO: this does not work correctly
  2601. this.showTooltip = false;
  2602. this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
  2603. this.animationInterval = 1000; // milliseconds
  2604. this.animationPreload = false;
  2605. this.camera = new Camera();
  2606. this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  2607. this.dataTable = null; // The original data table
  2608. this.dataPoints = null; // The table with point objects
  2609. // the column indexes
  2610. this.colX = undefined;
  2611. this.colY = undefined;
  2612. this.colZ = undefined;
  2613. this.colValue = undefined;
  2614. this.colFilter = undefined;
  2615. this.xMin = 0;
  2616. this.xStep = undefined; // auto by default
  2617. this.xMax = 1;
  2618. this.yMin = 0;
  2619. this.yStep = undefined; // auto by default
  2620. this.yMax = 1;
  2621. this.zMin = 0;
  2622. this.zStep = undefined; // auto by default
  2623. this.zMax = 1;
  2624. this.valueMin = 0;
  2625. this.valueMax = 1;
  2626. this.xBarWidth = 1;
  2627. this.yBarWidth = 1;
  2628. // TODO: customize axis range
  2629. // constants
  2630. this.colorAxis = '#4D4D4D';
  2631. this.colorGrid = '#D3D3D3';
  2632. this.colorDot = '#7DC1FF';
  2633. this.colorDotBorder = '#3267D2';
  2634. // create a frame and canvas
  2635. this.create();
  2636. // apply options (also when undefined)
  2637. this.setOptions(options);
  2638. // apply data
  2639. if (data) {
  2640. this.setData(data);
  2641. }
  2642. }
  2643. // Extend Graph3d with an Emitter mixin
  2644. Emitter(Graph3d.prototype);
  2645. /**
  2646. * Calculate the scaling values, dependent on the range in x, y, and z direction
  2647. */
  2648. Graph3d.prototype._setScale = function() {
  2649. this.scale = new Point3d(1 / (this.xMax - this.xMin),
  2650. 1 / (this.yMax - this.yMin),
  2651. 1 / (this.zMax - this.zMin));
  2652. // keep aspect ration between x and y scale if desired
  2653. if (this.keepAspectRatio) {
  2654. if (this.scale.x < this.scale.y) {
  2655. //noinspection JSSuspiciousNameCombination
  2656. this.scale.y = this.scale.x;
  2657. }
  2658. else {
  2659. //noinspection JSSuspiciousNameCombination
  2660. this.scale.x = this.scale.y;
  2661. }
  2662. }
  2663. // scale the vertical axis
  2664. this.scale.z *= this.verticalRatio;
  2665. // TODO: can this be automated? verticalRatio?
  2666. // determine scale for (optional) value
  2667. this.scale.value = 1 / (this.valueMax - this.valueMin);
  2668. // position the camera arm
  2669. var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
  2670. var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
  2671. var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
  2672. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  2673. };
  2674. /**
  2675. * Convert a 3D location to a 2D location on screen
  2676. * http://en.wikipedia.org/wiki/3D_projection
  2677. * @param {Point3d} point3d A 3D point with parameters x, y, z
  2678. * @return {Point2d} point2d A 2D point with parameters x, y
  2679. */
  2680. Graph3d.prototype._convert3Dto2D = function(point3d) {
  2681. var translation = this._convertPointToTranslation(point3d);
  2682. return this._convertTranslationToScreen(translation);
  2683. };
  2684. /**
  2685. * Convert a 3D location its translation seen from the camera
  2686. * http://en.wikipedia.org/wiki/3D_projection
  2687. * @param {Point3d} point3d A 3D point with parameters x, y, z
  2688. * @return {Point3d} translation A 3D point with parameters x, y, z This is
  2689. * the translation of the point, seen from the
  2690. * camera
  2691. */
  2692. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  2693. var ax = point3d.x * this.scale.x,
  2694. ay = point3d.y * this.scale.y,
  2695. az = point3d.z * this.scale.z,
  2696. cx = this.camera.getCameraLocation().x,
  2697. cy = this.camera.getCameraLocation().y,
  2698. cz = this.camera.getCameraLocation().z,
  2699. // calculate angles
  2700. sinTx = Math.sin(this.camera.getCameraRotation().x),
  2701. cosTx = Math.cos(this.camera.getCameraRotation().x),
  2702. sinTy = Math.sin(this.camera.getCameraRotation().y),
  2703. cosTy = Math.cos(this.camera.getCameraRotation().y),
  2704. sinTz = Math.sin(this.camera.getCameraRotation().z),
  2705. cosTz = Math.cos(this.camera.getCameraRotation().z),
  2706. // calculate translation
  2707. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  2708. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  2709. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  2710. return new Point3d(dx, dy, dz);
  2711. };
  2712. /**
  2713. * Convert a translation point to a point on the screen
  2714. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  2715. * the translation of the point, seen from the
  2716. * camera
  2717. * @return {Point2d} point2d A 2D point with parameters x, y
  2718. */
  2719. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  2720. var ex = this.eye.x,
  2721. ey = this.eye.y,
  2722. ez = this.eye.z,
  2723. dx = translation.x,
  2724. dy = translation.y,
  2725. dz = translation.z;
  2726. // calculate position on screen from translation
  2727. var bx;
  2728. var by;
  2729. if (this.showPerspective) {
  2730. bx = (dx - ex) * (ez / dz);
  2731. by = (dy - ey) * (ez / dz);
  2732. }
  2733. else {
  2734. bx = dx * -(ez / this.camera.getArmLength());
  2735. by = dy * -(ez / this.camera.getArmLength());
  2736. }
  2737. // shift and scale the point to the center of the screen
  2738. // use the width of the graph to scale both horizontally and vertically.
  2739. return new Point2d(
  2740. this.xcenter + bx * this.frame.canvas.clientWidth,
  2741. this.ycenter - by * this.frame.canvas.clientWidth);
  2742. };
  2743. /**
  2744. * Set the background styling for the graph
  2745. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  2746. */
  2747. Graph3d.prototype._setBackgroundColor = function(backgroundColor) {
  2748. var fill = 'white';
  2749. var stroke = 'gray';
  2750. var strokeWidth = 1;
  2751. if (typeof(backgroundColor) === 'string') {
  2752. fill = backgroundColor;
  2753. stroke = 'none';
  2754. strokeWidth = 0;
  2755. }
  2756. else if (typeof(backgroundColor) === 'object') {
  2757. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  2758. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  2759. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  2760. }
  2761. else if (backgroundColor === undefined) {
  2762. // use use defaults
  2763. }
  2764. else {
  2765. throw 'Unsupported type of backgroundColor';
  2766. }
  2767. this.frame.style.backgroundColor = fill;
  2768. this.frame.style.borderColor = stroke;
  2769. this.frame.style.borderWidth = strokeWidth + 'px';
  2770. this.frame.style.borderStyle = 'solid';
  2771. };
  2772. /// enumerate the available styles
  2773. Graph3d.STYLE = {
  2774. BAR: 0,
  2775. BARCOLOR: 1,
  2776. BARSIZE: 2,
  2777. DOT : 3,
  2778. DOTLINE : 4,
  2779. DOTCOLOR: 5,
  2780. DOTSIZE: 6,
  2781. GRID : 7,
  2782. LINE: 8,
  2783. SURFACE : 9
  2784. };
  2785. /**
  2786. * Retrieve the style index from given styleName
  2787. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  2788. * @return {Number} styleNumber Enumeration value representing the style, or -1
  2789. * when not found
  2790. */
  2791. Graph3d.prototype._getStyleNumber = function(styleName) {
  2792. switch (styleName) {
  2793. case 'dot': return Graph3d.STYLE.DOT;
  2794. case 'dot-line': return Graph3d.STYLE.DOTLINE;
  2795. case 'dot-color': return Graph3d.STYLE.DOTCOLOR;
  2796. case 'dot-size': return Graph3d.STYLE.DOTSIZE;
  2797. case 'line': return Graph3d.STYLE.LINE;
  2798. case 'grid': return Graph3d.STYLE.GRID;
  2799. case 'surface': return Graph3d.STYLE.SURFACE;
  2800. case 'bar': return Graph3d.STYLE.BAR;
  2801. case 'bar-color': return Graph3d.STYLE.BARCOLOR;
  2802. case 'bar-size': return Graph3d.STYLE.BARSIZE;
  2803. }
  2804. return -1;
  2805. };
  2806. /**
  2807. * Determine the indexes of the data columns, based on the given style and data
  2808. * @param {DataSet} data
  2809. * @param {Number} style
  2810. */
  2811. Graph3d.prototype._determineColumnIndexes = function(data, style) {
  2812. if (this.style === Graph3d.STYLE.DOT ||
  2813. this.style === Graph3d.STYLE.DOTLINE ||
  2814. this.style === Graph3d.STYLE.LINE ||
  2815. this.style === Graph3d.STYLE.GRID ||
  2816. this.style === Graph3d.STYLE.SURFACE ||
  2817. this.style === Graph3d.STYLE.BAR) {
  2818. // 3 columns expected, and optionally a 4th with filter values
  2819. this.colX = 0;
  2820. this.colY = 1;
  2821. this.colZ = 2;
  2822. this.colValue = undefined;
  2823. if (data.getNumberOfColumns() > 3) {
  2824. this.colFilter = 3;
  2825. }
  2826. }
  2827. else if (this.style === Graph3d.STYLE.DOTCOLOR ||
  2828. this.style === Graph3d.STYLE.DOTSIZE ||
  2829. this.style === Graph3d.STYLE.BARCOLOR ||
  2830. this.style === Graph3d.STYLE.BARSIZE) {
  2831. // 4 columns expected, and optionally a 5th with filter values
  2832. this.colX = 0;
  2833. this.colY = 1;
  2834. this.colZ = 2;
  2835. this.colValue = 3;
  2836. if (data.getNumberOfColumns() > 4) {
  2837. this.colFilter = 4;
  2838. }
  2839. }
  2840. else {
  2841. throw 'Unknown style "' + this.style + '"';
  2842. }
  2843. };
  2844. Graph3d.prototype.getNumberOfRows = function(data) {
  2845. return data.length;
  2846. }
  2847. Graph3d.prototype.getNumberOfColumns = function(data) {
  2848. var counter = 0;
  2849. for (var column in data[0]) {
  2850. if (data[0].hasOwnProperty(column)) {
  2851. counter++;
  2852. }
  2853. }
  2854. return counter;
  2855. }
  2856. Graph3d.prototype.getDistinctValues = function(data, column) {
  2857. var distinctValues = [];
  2858. for (var i = 0; i < data.length; i++) {
  2859. if (distinctValues.indexOf(data[i][column]) == -1) {
  2860. distinctValues.push(data[i][column]);
  2861. }
  2862. }
  2863. return distinctValues;
  2864. }
  2865. Graph3d.prototype.getColumnRange = function(data,column) {
  2866. var minMax = {min:data[0][column],max:data[0][column]};
  2867. for (var i = 0; i < data.length; i++) {
  2868. if (minMax.min > data[i][column]) { minMax.min = data[i][column]; }
  2869. if (minMax.max < data[i][column]) { minMax.max = data[i][column]; }
  2870. }
  2871. return minMax;
  2872. };
  2873. /**
  2874. * Initialize the data from the data table. Calculate minimum and maximum values
  2875. * and column index values
  2876. * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
  2877. * @param {Number} style Style Number
  2878. */
  2879. Graph3d.prototype._dataInitialize = function (rawData, style) {
  2880. var me = this;
  2881. // unsubscribe from the dataTable
  2882. if (this.dataSet) {
  2883. this.dataSet.off('*', this._onChange);
  2884. }
  2885. if (rawData === undefined)
  2886. return;
  2887. if (Array.isArray(rawData)) {
  2888. rawData = new DataSet(rawData);
  2889. }
  2890. var data;
  2891. if (rawData instanceof DataSet || rawData instanceof DataView) {
  2892. data = rawData.get();
  2893. }
  2894. else {
  2895. throw new Error('Array, DataSet, or DataView expected');
  2896. }
  2897. if (data.length == 0)
  2898. return;
  2899. this.dataSet = rawData;
  2900. this.dataTable = data;
  2901. // subscribe to changes in the dataset
  2902. this._onChange = function () {
  2903. me.setData(me.dataSet);
  2904. };
  2905. this.dataSet.on('*', this._onChange);
  2906. // _determineColumnIndexes
  2907. // getNumberOfRows (points)
  2908. // getNumberOfColumns (x,y,z,v,t,t1,t2...)
  2909. // getDistinctValues (unique values?)
  2910. // getColumnRange
  2911. // determine the location of x,y,z,value,filter columns
  2912. this.colX = 'x';
  2913. this.colY = 'y';
  2914. this.colZ = 'z';
  2915. this.colValue = 'style';
  2916. this.colFilter = 'filter';
  2917. // check if a filter column is provided
  2918. if (data[0].hasOwnProperty('filter')) {
  2919. if (this.dataFilter === undefined) {
  2920. this.dataFilter = new Filter(rawData, this.colFilter, this);
  2921. this.dataFilter.setOnLoadCallback(function() {me.redraw();});
  2922. }
  2923. }
  2924. var withBars = this.style == Graph3d.STYLE.BAR ||
  2925. this.style == Graph3d.STYLE.BARCOLOR ||
  2926. this.style == Graph3d.STYLE.BARSIZE;
  2927. // determine barWidth from data
  2928. if (withBars) {
  2929. if (this.defaultXBarWidth !== undefined) {
  2930. this.xBarWidth = this.defaultXBarWidth;
  2931. }
  2932. else {
  2933. var dataX = this.getDistinctValues(data,this.colX);
  2934. this.xBarWidth = (dataX[1] - dataX[0]) || 1;
  2935. }
  2936. if (this.defaultYBarWidth !== undefined) {
  2937. this.yBarWidth = this.defaultYBarWidth;
  2938. }
  2939. else {
  2940. var dataY = this.getDistinctValues(data,this.colY);
  2941. this.yBarWidth = (dataY[1] - dataY[0]) || 1;
  2942. }
  2943. }
  2944. // calculate minimums and maximums
  2945. var xRange = this.getColumnRange(data,this.colX);
  2946. if (withBars) {
  2947. xRange.min -= this.xBarWidth / 2;
  2948. xRange.max += this.xBarWidth / 2;
  2949. }
  2950. this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min;
  2951. this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max;
  2952. if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
  2953. this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5;
  2954. var yRange = this.getColumnRange(data,this.colY);
  2955. if (withBars) {
  2956. yRange.min -= this.yBarWidth / 2;
  2957. yRange.max += this.yBarWidth / 2;
  2958. }
  2959. this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min;
  2960. this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max;
  2961. if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
  2962. this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5;
  2963. var zRange = this.getColumnRange(data,this.colZ);
  2964. this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min;
  2965. this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max;
  2966. if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
  2967. this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5;
  2968. if (this.colValue !== undefined) {
  2969. var valueRange = this.getColumnRange(data,this.colValue);
  2970. this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min;
  2971. this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max;
  2972. if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
  2973. }
  2974. // set the scale dependent on the ranges.
  2975. this._setScale();
  2976. };
  2977. /**
  2978. * Filter the data based on the current filter
  2979. * @param {Array} data
  2980. * @return {Array} dataPoints Array with point objects which can be drawn on screen
  2981. */
  2982. Graph3d.prototype._getDataPoints = function (data) {
  2983. // TODO: store the created matrix dataPoints in the filters instead of reloading each time
  2984. var x, y, i, z, obj, point;
  2985. var dataPoints = [];
  2986. if (this.style === Graph3d.STYLE.GRID ||
  2987. this.style === Graph3d.STYLE.SURFACE) {
  2988. // copy all values from the google data table to a matrix
  2989. // the provided values are supposed to form a grid of (x,y) positions
  2990. // create two lists with all present x and y values
  2991. var dataX = [];
  2992. var dataY = [];
  2993. for (i = 0; i < this.getNumberOfRows(data); i++) {
  2994. x = data[i][this.colX] || 0;
  2995. y = data[i][this.colY] || 0;
  2996. if (dataX.indexOf(x) === -1) {
  2997. dataX.push(x);
  2998. }
  2999. if (dataY.indexOf(y) === -1) {
  3000. dataY.push(y);
  3001. }
  3002. }
  3003. function sortNumber(a, b) {
  3004. return a - b;
  3005. }
  3006. dataX.sort(sortNumber);
  3007. dataY.sort(sortNumber);
  3008. // create a grid, a 2d matrix, with all values.
  3009. var dataMatrix = []; // temporary data matrix
  3010. for (i = 0; i < data.length; i++) {
  3011. x = data[i][this.colX] || 0;
  3012. y = data[i][this.colY] || 0;
  3013. z = data[i][this.colZ] || 0;
  3014. var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
  3015. var yIndex = dataY.indexOf(y);
  3016. if (dataMatrix[xIndex] === undefined) {
  3017. dataMatrix[xIndex] = [];
  3018. }
  3019. var point3d = new Point3d();
  3020. point3d.x = x;
  3021. point3d.y = y;
  3022. point3d.z = z;
  3023. obj = {};
  3024. obj.point = point3d;
  3025. obj.trans = undefined;
  3026. obj.screen = undefined;
  3027. obj.bottom = new Point3d(x, y, this.zMin);
  3028. dataMatrix[xIndex][yIndex] = obj;
  3029. dataPoints.push(obj);
  3030. }
  3031. // fill in the pointers to the neighbors.
  3032. for (x = 0; x < dataMatrix.length; x++) {
  3033. for (y = 0; y < dataMatrix[x].length; y++) {
  3034. if (dataMatrix[x][y]) {
  3035. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  3036. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  3037. dataMatrix[x][y].pointCross =
  3038. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  3039. dataMatrix[x+1][y+1] :
  3040. undefined;
  3041. }
  3042. }
  3043. }
  3044. }
  3045. else { // 'dot', 'dot-line', etc.
  3046. // copy all values from the google data table to a list with Point3d objects
  3047. for (i = 0; i < data.length; i++) {
  3048. point = new Point3d();
  3049. point.x = data[i][this.colX] || 0;
  3050. point.y = data[i][this.colY] || 0;
  3051. point.z = data[i][this.colZ] || 0;
  3052. if (this.colValue !== undefined) {
  3053. point.value = data[i][this.colValue] || 0;
  3054. }
  3055. obj = {};
  3056. obj.point = point;
  3057. obj.bottom = new Point3d(point.x, point.y, this.zMin);
  3058. obj.trans = undefined;
  3059. obj.screen = undefined;
  3060. dataPoints.push(obj);
  3061. }
  3062. }
  3063. return dataPoints;
  3064. };
  3065. /**
  3066. * Create the main frame for the Graph3d.
  3067. * This function is executed once when a Graph3d object is created. The frame
  3068. * contains a canvas, and this canvas contains all objects like the axis and
  3069. * nodes.
  3070. */
  3071. Graph3d.prototype.create = function () {
  3072. // remove all elements from the container element.
  3073. while (this.containerElement.hasChildNodes()) {
  3074. this.containerElement.removeChild(this.containerElement.firstChild);
  3075. }
  3076. this.frame = document.createElement('div');
  3077. this.frame.style.position = 'relative';
  3078. this.frame.style.overflow = 'hidden';
  3079. // create the graph canvas (HTML canvas element)
  3080. this.frame.canvas = document.createElement( 'canvas' );
  3081. this.frame.canvas.style.position = 'relative';
  3082. this.frame.appendChild(this.frame.canvas);
  3083. //if (!this.frame.canvas.getContext) {
  3084. {
  3085. var noCanvas = document.createElement( 'DIV' );
  3086. noCanvas.style.color = 'red';
  3087. noCanvas.style.fontWeight = 'bold' ;
  3088. noCanvas.style.padding = '10px';
  3089. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  3090. this.frame.canvas.appendChild(noCanvas);
  3091. }
  3092. this.frame.filter = document.createElement( 'div' );
  3093. this.frame.filter.style.position = 'absolute';
  3094. this.frame.filter.style.bottom = '0px';
  3095. this.frame.filter.style.left = '0px';
  3096. this.frame.filter.style.width = '100%';
  3097. this.frame.appendChild(this.frame.filter);
  3098. // add event listeners to handle moving and zooming the contents
  3099. var me = this;
  3100. var onmousedown = function (event) {me._onMouseDown(event);};
  3101. var ontouchstart = function (event) {me._onTouchStart(event);};
  3102. var onmousewheel = function (event) {me._onWheel(event);};
  3103. var ontooltip = function (event) {me._onTooltip(event);};
  3104. // TODO: these events are never cleaned up... can give a 'memory leakage'
  3105. util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
  3106. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  3107. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  3108. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  3109. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  3110. // add the new graph to the container element
  3111. this.containerElement.appendChild(this.frame);
  3112. };
  3113. /**
  3114. * Set a new size for the graph
  3115. * @param {string} width Width in pixels or percentage (for example '800px'
  3116. * or '50%')
  3117. * @param {string} height Height in pixels or percentage (for example '400px'
  3118. * or '30%')
  3119. */
  3120. Graph3d.prototype.setSize = function(width, height) {
  3121. this.frame.style.width = width;
  3122. this.frame.style.height = height;
  3123. this._resizeCanvas();
  3124. };
  3125. /**
  3126. * Resize the canvas to the current size of the frame
  3127. */
  3128. Graph3d.prototype._resizeCanvas = function() {
  3129. this.frame.canvas.style.width = '100%';
  3130. this.frame.canvas.style.height = '100%';
  3131. this.frame.canvas.width = this.frame.canvas.clientWidth;
  3132. this.frame.canvas.height = this.frame.canvas.clientHeight;
  3133. // adjust with for margin
  3134. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  3135. };
  3136. /**
  3137. * Start animation
  3138. */
  3139. Graph3d.prototype.animationStart = function() {
  3140. if (!this.frame.filter || !this.frame.filter.slider)
  3141. throw 'No animation available';
  3142. this.frame.filter.slider.play();
  3143. };
  3144. /**
  3145. * Stop animation
  3146. */
  3147. Graph3d.prototype.animationStop = function() {
  3148. if (!this.frame.filter || !this.frame.filter.slider) return;
  3149. this.frame.filter.slider.stop();
  3150. };
  3151. /**
  3152. * Resize the center position based on the current values in this.defaultXCenter
  3153. * and this.defaultYCenter (which are strings with a percentage or a value
  3154. * in pixels). The center positions are the variables this.xCenter
  3155. * and this.yCenter
  3156. */
  3157. Graph3d.prototype._resizeCenter = function() {
  3158. // calculate the horizontal center position
  3159. if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') {
  3160. this.xcenter =
  3161. parseFloat(this.defaultXCenter) / 100 *
  3162. this.frame.canvas.clientWidth;
  3163. }
  3164. else {
  3165. this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
  3166. }
  3167. // calculate the vertical center position
  3168. if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') {
  3169. this.ycenter =
  3170. parseFloat(this.defaultYCenter) / 100 *
  3171. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  3172. }
  3173. else {
  3174. this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
  3175. }
  3176. };
  3177. /**
  3178. * Set the rotation and distance of the camera
  3179. * @param {Object} pos An object with the camera position. The object
  3180. * contains three parameters:
  3181. * - horizontal {Number}
  3182. * The horizontal rotation, between 0 and 2*PI.
  3183. * Optional, can be left undefined.
  3184. * - vertical {Number}
  3185. * The vertical rotation, between 0 and 0.5*PI
  3186. * if vertical=0.5*PI, the graph is shown from the
  3187. * top. Optional, can be left undefined.
  3188. * - distance {Number}
  3189. * The (normalized) distance of the camera to the
  3190. * center of the graph, a value between 0.71 and 5.0.
  3191. * Optional, can be left undefined.
  3192. */
  3193. Graph3d.prototype.setCameraPosition = function(pos) {
  3194. if (pos === undefined) {
  3195. return;
  3196. }
  3197. if (pos.horizontal !== undefined && pos.vertical !== undefined) {
  3198. this.camera.setArmRotation(pos.horizontal, pos.vertical);
  3199. }
  3200. if (pos.distance !== undefined) {
  3201. this.camera.setArmLength(pos.distance);
  3202. }
  3203. this.redraw();
  3204. };
  3205. /**
  3206. * Retrieve the current camera rotation
  3207. * @return {object} An object with parameters horizontal, vertical, and
  3208. * distance
  3209. */
  3210. Graph3d.prototype.getCameraPosition = function() {
  3211. var pos = this.camera.getArmRotation();
  3212. pos.distance = this.camera.getArmLength();
  3213. return pos;
  3214. };
  3215. /**
  3216. * Load data into the 3D Graph
  3217. */
  3218. Graph3d.prototype._readData = function(data) {
  3219. // read the data
  3220. this._dataInitialize(data, this.style);
  3221. if (this.dataFilter) {
  3222. // apply filtering
  3223. this.dataPoints = this.dataFilter._getDataPoints();
  3224. }
  3225. else {
  3226. // no filtering. load all data
  3227. this.dataPoints = this._getDataPoints(this.dataTable);
  3228. }
  3229. // draw the filter
  3230. this._redrawFilter();
  3231. };
  3232. /**
  3233. * Replace the dataset of the Graph3d
  3234. * @param {Array | DataSet | DataView} data
  3235. */
  3236. Graph3d.prototype.setData = function (data) {
  3237. this._readData(data);
  3238. this.redraw();
  3239. // start animation when option is true
  3240. if (this.animationAutoStart && this.dataFilter) {
  3241. this.animationStart();
  3242. }
  3243. };
  3244. /**
  3245. * Update the options. Options will be merged with current options
  3246. * @param {Object} options
  3247. */
  3248. Graph3d.prototype.setOptions = function (options) {
  3249. var cameraPosition = undefined;
  3250. this.animationStop();
  3251. if (options !== undefined) {
  3252. // retrieve parameter values
  3253. if (options.width !== undefined) this.width = options.width;
  3254. if (options.height !== undefined) this.height = options.height;
  3255. if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
  3256. if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
  3257. if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
  3258. if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
  3259. if (options.xLabel !== undefined) this.xLabel = options.xLabel;
  3260. if (options.yLabel !== undefined) this.yLabel = options.yLabel;
  3261. if (options.zLabel !== undefined) this.zLabel = options.zLabel;
  3262. if (options.style !== undefined) {
  3263. var styleNumber = this._getStyleNumber(options.style);
  3264. if (styleNumber !== -1) {
  3265. this.style = styleNumber;
  3266. }
  3267. }
  3268. if (options.showGrid !== undefined) this.showGrid = options.showGrid;
  3269. if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
  3270. if (options.showShadow !== undefined) this.showShadow = options.showShadow;
  3271. if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
  3272. if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
  3273. if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
  3274. if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
  3275. if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
  3276. if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
  3277. if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart;
  3278. if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
  3279. if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
  3280. if (options.xMin !== undefined) this.defaultXMin = options.xMin;
  3281. if (options.xStep !== undefined) this.defaultXStep = options.xStep;
  3282. if (options.xMax !== undefined) this.defaultXMax = options.xMax;
  3283. if (options.yMin !== undefined) this.defaultYMin = options.yMin;
  3284. if (options.yStep !== undefined) this.defaultYStep = options.yStep;
  3285. if (options.yMax !== undefined) this.defaultYMax = options.yMax;
  3286. if (options.zMin !== undefined) this.defaultZMin = options.zMin;
  3287. if (options.zStep !== undefined) this.defaultZStep = options.zStep;
  3288. if (options.zMax !== undefined) this.defaultZMax = options.zMax;
  3289. if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
  3290. if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
  3291. if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
  3292. if (cameraPosition !== undefined) {
  3293. this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
  3294. this.camera.setArmLength(cameraPosition.distance);
  3295. }
  3296. else {
  3297. this.camera.setArmRotation(1.0, 0.5);
  3298. this.camera.setArmLength(1.7);
  3299. }
  3300. }
  3301. this._setBackgroundColor(options && options.backgroundColor);
  3302. this.setSize(this.width, this.height);
  3303. // re-load the data
  3304. if (this.dataTable) {
  3305. this.setData(this.dataTable);
  3306. }
  3307. // start animation when option is true
  3308. if (this.animationAutoStart && this.dataFilter) {
  3309. this.animationStart();
  3310. }
  3311. };
  3312. /**
  3313. * Redraw the Graph.
  3314. */
  3315. Graph3d.prototype.redraw = function() {
  3316. if (this.dataPoints === undefined) {
  3317. throw 'Error: graph data not initialized';
  3318. }
  3319. this._resizeCanvas();
  3320. this._resizeCenter();
  3321. this._redrawSlider();
  3322. this._redrawClear();
  3323. this._redrawAxis();
  3324. if (this.style === Graph3d.STYLE.GRID ||
  3325. this.style === Graph3d.STYLE.SURFACE) {
  3326. this._redrawDataGrid();
  3327. }
  3328. else if (this.style === Graph3d.STYLE.LINE) {
  3329. this._redrawDataLine();
  3330. }
  3331. else if (this.style === Graph3d.STYLE.BAR ||
  3332. this.style === Graph3d.STYLE.BARCOLOR ||
  3333. this.style === Graph3d.STYLE.BARSIZE) {
  3334. this._redrawDataBar();
  3335. }
  3336. else {
  3337. // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
  3338. this._redrawDataDot();
  3339. }
  3340. this._redrawInfo();
  3341. this._redrawLegend();
  3342. };
  3343. /**
  3344. * Clear the canvas before redrawing
  3345. */
  3346. Graph3d.prototype._redrawClear = function() {
  3347. var canvas = this.frame.canvas;
  3348. var ctx = canvas.getContext('2d');
  3349. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3350. };
  3351. /**
  3352. * Redraw the legend showing the colors
  3353. */
  3354. Graph3d.prototype._redrawLegend = function() {
  3355. var y;
  3356. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3357. this.style === Graph3d.STYLE.DOTSIZE) {
  3358. var dotSize = this.frame.clientWidth * 0.02;
  3359. var widthMin, widthMax;
  3360. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3361. widthMin = dotSize / 2; // px
  3362. widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
  3363. }
  3364. else {
  3365. widthMin = 20; // px
  3366. widthMax = 20; // px
  3367. }
  3368. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  3369. var top = this.margin;
  3370. var right = this.frame.clientWidth - this.margin;
  3371. var left = right - widthMax;
  3372. var bottom = top + height;
  3373. }
  3374. var canvas = this.frame.canvas;
  3375. var ctx = canvas.getContext('2d');
  3376. ctx.lineWidth = 1;
  3377. ctx.font = '14px arial'; // TODO: put in options
  3378. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  3379. // draw the color bar
  3380. var ymin = 0;
  3381. var ymax = height; // Todo: make height customizable
  3382. for (y = ymin; y < ymax; y++) {
  3383. var f = (y - ymin) / (ymax - ymin);
  3384. //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
  3385. var hue = f * 240;
  3386. var color = this._hsv2rgb(hue, 1, 1);
  3387. ctx.strokeStyle = color;
  3388. ctx.beginPath();
  3389. ctx.moveTo(left, top + y);
  3390. ctx.lineTo(right, top + y);
  3391. ctx.stroke();
  3392. }
  3393. ctx.strokeStyle = this.colorAxis;
  3394. ctx.strokeRect(left, top, widthMax, height);
  3395. }
  3396. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3397. // draw border around color bar
  3398. ctx.strokeStyle = this.colorAxis;
  3399. ctx.fillStyle = this.colorDot;
  3400. ctx.beginPath();
  3401. ctx.moveTo(left, top);
  3402. ctx.lineTo(right, top);
  3403. ctx.lineTo(right - widthMax + widthMin, bottom);
  3404. ctx.lineTo(left, bottom);
  3405. ctx.closePath();
  3406. ctx.fill();
  3407. ctx.stroke();
  3408. }
  3409. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3410. this.style === Graph3d.STYLE.DOTSIZE) {
  3411. // print values along the color bar
  3412. var gridLineLen = 5; // px
  3413. var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true);
  3414. step.start();
  3415. if (step.getCurrent() < this.valueMin) {
  3416. step.next();
  3417. }
  3418. while (!step.end()) {
  3419. y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
  3420. ctx.beginPath();
  3421. ctx.moveTo(left - gridLineLen, y);
  3422. ctx.lineTo(left, y);
  3423. ctx.stroke();
  3424. ctx.textAlign = 'right';
  3425. ctx.textBaseline = 'middle';
  3426. ctx.fillStyle = this.colorAxis;
  3427. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  3428. step.next();
  3429. }
  3430. ctx.textAlign = 'right';
  3431. ctx.textBaseline = 'top';
  3432. var label = this.legendLabel;
  3433. ctx.fillText(label, right, bottom + this.margin);
  3434. }
  3435. };
  3436. /**
  3437. * Redraw the filter
  3438. */
  3439. Graph3d.prototype._redrawFilter = function() {
  3440. this.frame.filter.innerHTML = '';
  3441. if (this.dataFilter) {
  3442. var options = {
  3443. 'visible': this.showAnimationControls
  3444. };
  3445. var slider = new Slider(this.frame.filter, options);
  3446. this.frame.filter.slider = slider;
  3447. // TODO: css here is not nice here...
  3448. this.frame.filter.style.padding = '10px';
  3449. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  3450. slider.setValues(this.dataFilter.values);
  3451. slider.setPlayInterval(this.animationInterval);
  3452. // create an event handler
  3453. var me = this;
  3454. var onchange = function () {
  3455. var index = slider.getIndex();
  3456. me.dataFilter.selectValue(index);
  3457. me.dataPoints = me.dataFilter._getDataPoints();
  3458. me.redraw();
  3459. };
  3460. slider.setOnChangeCallback(onchange);
  3461. }
  3462. else {
  3463. this.frame.filter.slider = undefined;
  3464. }
  3465. };
  3466. /**
  3467. * Redraw the slider
  3468. */
  3469. Graph3d.prototype._redrawSlider = function() {
  3470. if ( this.frame.filter.slider !== undefined) {
  3471. this.frame.filter.slider.redraw();
  3472. }
  3473. };
  3474. /**
  3475. * Redraw common information
  3476. */
  3477. Graph3d.prototype._redrawInfo = function() {
  3478. if (this.dataFilter) {
  3479. var canvas = this.frame.canvas;
  3480. var ctx = canvas.getContext('2d');
  3481. ctx.font = '14px arial'; // TODO: put in options
  3482. ctx.lineStyle = 'gray';
  3483. ctx.fillStyle = 'gray';
  3484. ctx.textAlign = 'left';
  3485. ctx.textBaseline = 'top';
  3486. var x = this.margin;
  3487. var y = this.margin;
  3488. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  3489. }
  3490. };
  3491. /**
  3492. * Redraw the axis
  3493. */
  3494. Graph3d.prototype._redrawAxis = function() {
  3495. var canvas = this.frame.canvas,
  3496. ctx = canvas.getContext('2d'),
  3497. from, to, step, prettyStep,
  3498. text, xText, yText, zText,
  3499. offset, xOffset, yOffset,
  3500. xMin2d, xMax2d;
  3501. // TODO: get the actual rendered style of the containerElement
  3502. //ctx.font = this.containerElement.style.font;
  3503. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  3504. // calculate the length for the short grid lines
  3505. var gridLenX = 0.025 / this.scale.x;
  3506. var gridLenY = 0.025 / this.scale.y;
  3507. var textMargin = 5 / this.camera.getArmLength(); // px
  3508. var armAngle = this.camera.getArmRotation().horizontal;
  3509. // draw x-grid lines
  3510. ctx.lineWidth = 1;
  3511. prettyStep = (this.defaultXStep === undefined);
  3512. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  3513. step.start();
  3514. if (step.getCurrent() < this.xMin) {
  3515. step.next();
  3516. }
  3517. while (!step.end()) {
  3518. var x = step.getCurrent();
  3519. if (this.showGrid) {
  3520. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  3521. to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  3522. ctx.strokeStyle = this.colorGrid;
  3523. ctx.beginPath();
  3524. ctx.moveTo(from.x, from.y);
  3525. ctx.lineTo(to.x, to.y);
  3526. ctx.stroke();
  3527. }
  3528. else {
  3529. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  3530. to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin));
  3531. ctx.strokeStyle = this.colorAxis;
  3532. ctx.beginPath();
  3533. ctx.moveTo(from.x, from.y);
  3534. ctx.lineTo(to.x, to.y);
  3535. ctx.stroke();
  3536. from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  3537. to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin));
  3538. ctx.strokeStyle = this.colorAxis;
  3539. ctx.beginPath();
  3540. ctx.moveTo(from.x, from.y);
  3541. ctx.lineTo(to.x, to.y);
  3542. ctx.stroke();
  3543. }
  3544. yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax;
  3545. text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
  3546. if (Math.cos(armAngle * 2) > 0) {
  3547. ctx.textAlign = 'center';
  3548. ctx.textBaseline = 'top';
  3549. text.y += textMargin;
  3550. }
  3551. else if (Math.sin(armAngle * 2) < 0){
  3552. ctx.textAlign = 'right';
  3553. ctx.textBaseline = 'middle';
  3554. }
  3555. else {
  3556. ctx.textAlign = 'left';
  3557. ctx.textBaseline = 'middle';
  3558. }
  3559. ctx.fillStyle = this.colorAxis;
  3560. ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y);
  3561. step.next();
  3562. }
  3563. // draw y-grid lines
  3564. ctx.lineWidth = 1;
  3565. prettyStep = (this.defaultYStep === undefined);
  3566. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  3567. step.start();
  3568. if (step.getCurrent() < this.yMin) {
  3569. step.next();
  3570. }
  3571. while (!step.end()) {
  3572. if (this.showGrid) {
  3573. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  3574. to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  3575. ctx.strokeStyle = this.colorGrid;
  3576. ctx.beginPath();
  3577. ctx.moveTo(from.x, from.y);
  3578. ctx.lineTo(to.x, to.y);
  3579. ctx.stroke();
  3580. }
  3581. else {
  3582. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  3583. to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin));
  3584. ctx.strokeStyle = this.colorAxis;
  3585. ctx.beginPath();
  3586. ctx.moveTo(from.x, from.y);
  3587. ctx.lineTo(to.x, to.y);
  3588. ctx.stroke();
  3589. from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  3590. to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin));
  3591. ctx.strokeStyle = this.colorAxis;
  3592. ctx.beginPath();
  3593. ctx.moveTo(from.x, from.y);
  3594. ctx.lineTo(to.x, to.y);
  3595. ctx.stroke();
  3596. }
  3597. xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax;
  3598. text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
  3599. if (Math.cos(armAngle * 2) < 0) {
  3600. ctx.textAlign = 'center';
  3601. ctx.textBaseline = 'top';
  3602. text.y += textMargin;
  3603. }
  3604. else if (Math.sin(armAngle * 2) > 0){
  3605. ctx.textAlign = 'right';
  3606. ctx.textBaseline = 'middle';
  3607. }
  3608. else {
  3609. ctx.textAlign = 'left';
  3610. ctx.textBaseline = 'middle';
  3611. }
  3612. ctx.fillStyle = this.colorAxis;
  3613. ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y);
  3614. step.next();
  3615. }
  3616. // draw z-grid lines and axis
  3617. ctx.lineWidth = 1;
  3618. prettyStep = (this.defaultZStep === undefined);
  3619. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  3620. step.start();
  3621. if (step.getCurrent() < this.zMin) {
  3622. step.next();
  3623. }
  3624. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  3625. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  3626. while (!step.end()) {
  3627. // TODO: make z-grid lines really 3d?
  3628. from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
  3629. ctx.strokeStyle = this.colorAxis;
  3630. ctx.beginPath();
  3631. ctx.moveTo(from.x, from.y);
  3632. ctx.lineTo(from.x - textMargin, from.y);
  3633. ctx.stroke();
  3634. ctx.textAlign = 'right';
  3635. ctx.textBaseline = 'middle';
  3636. ctx.fillStyle = this.colorAxis;
  3637. ctx.fillText(step.getCurrent() + ' ', from.x - 5, from.y);
  3638. step.next();
  3639. }
  3640. ctx.lineWidth = 1;
  3641. from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  3642. to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
  3643. ctx.strokeStyle = this.colorAxis;
  3644. ctx.beginPath();
  3645. ctx.moveTo(from.x, from.y);
  3646. ctx.lineTo(to.x, to.y);
  3647. ctx.stroke();
  3648. // draw x-axis
  3649. ctx.lineWidth = 1;
  3650. // line at yMin
  3651. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  3652. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  3653. ctx.strokeStyle = this.colorAxis;
  3654. ctx.beginPath();
  3655. ctx.moveTo(xMin2d.x, xMin2d.y);
  3656. ctx.lineTo(xMax2d.x, xMax2d.y);
  3657. ctx.stroke();
  3658. // line at ymax
  3659. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  3660. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  3661. ctx.strokeStyle = this.colorAxis;
  3662. ctx.beginPath();
  3663. ctx.moveTo(xMin2d.x, xMin2d.y);
  3664. ctx.lineTo(xMax2d.x, xMax2d.y);
  3665. ctx.stroke();
  3666. // draw y-axis
  3667. ctx.lineWidth = 1;
  3668. // line at xMin
  3669. from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  3670. to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  3671. ctx.strokeStyle = this.colorAxis;
  3672. ctx.beginPath();
  3673. ctx.moveTo(from.x, from.y);
  3674. ctx.lineTo(to.x, to.y);
  3675. ctx.stroke();
  3676. // line at xMax
  3677. from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  3678. to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  3679. ctx.strokeStyle = this.colorAxis;
  3680. ctx.beginPath();
  3681. ctx.moveTo(from.x, from.y);
  3682. ctx.lineTo(to.x, to.y);
  3683. ctx.stroke();
  3684. // draw x-label
  3685. var xLabel = this.xLabel;
  3686. if (xLabel.length > 0) {
  3687. yOffset = 0.1 / this.scale.y;
  3688. xText = (this.xMin + this.xMax) / 2;
  3689. yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset;
  3690. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  3691. if (Math.cos(armAngle * 2) > 0) {
  3692. ctx.textAlign = 'center';
  3693. ctx.textBaseline = 'top';
  3694. }
  3695. else if (Math.sin(armAngle * 2) < 0){
  3696. ctx.textAlign = 'right';
  3697. ctx.textBaseline = 'middle';
  3698. }
  3699. else {
  3700. ctx.textAlign = 'left';
  3701. ctx.textBaseline = 'middle';
  3702. }
  3703. ctx.fillStyle = this.colorAxis;
  3704. ctx.fillText(xLabel, text.x, text.y);
  3705. }
  3706. // draw y-label
  3707. var yLabel = this.yLabel;
  3708. if (yLabel.length > 0) {
  3709. xOffset = 0.1 / this.scale.x;
  3710. xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset;
  3711. yText = (this.yMin + this.yMax) / 2;
  3712. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  3713. if (Math.cos(armAngle * 2) < 0) {
  3714. ctx.textAlign = 'center';
  3715. ctx.textBaseline = 'top';
  3716. }
  3717. else if (Math.sin(armAngle * 2) > 0){
  3718. ctx.textAlign = 'right';
  3719. ctx.textBaseline = 'middle';
  3720. }
  3721. else {
  3722. ctx.textAlign = 'left';
  3723. ctx.textBaseline = 'middle';
  3724. }
  3725. ctx.fillStyle = this.colorAxis;
  3726. ctx.fillText(yLabel, text.x, text.y);
  3727. }
  3728. // draw z-label
  3729. var zLabel = this.zLabel;
  3730. if (zLabel.length > 0) {
  3731. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  3732. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  3733. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  3734. zText = (this.zMin + this.zMax) / 2;
  3735. text = this._convert3Dto2D(new Point3d(xText, yText, zText));
  3736. ctx.textAlign = 'right';
  3737. ctx.textBaseline = 'middle';
  3738. ctx.fillStyle = this.colorAxis;
  3739. ctx.fillText(zLabel, text.x - offset, text.y);
  3740. }
  3741. };
  3742. /**
  3743. * Calculate the color based on the given value.
  3744. * @param {Number} H Hue, a value be between 0 and 360
  3745. * @param {Number} S Saturation, a value between 0 and 1
  3746. * @param {Number} V Value, a value between 0 and 1
  3747. */
  3748. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  3749. var R, G, B, C, Hi, X;
  3750. C = V * S;
  3751. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  3752. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  3753. switch (Hi) {
  3754. case 0: R = C; G = X; B = 0; break;
  3755. case 1: R = X; G = C; B = 0; break;
  3756. case 2: R = 0; G = C; B = X; break;
  3757. case 3: R = 0; G = X; B = C; break;
  3758. case 4: R = X; G = 0; B = C; break;
  3759. case 5: R = C; G = 0; B = X; break;
  3760. default: R = 0; G = 0; B = 0; break;
  3761. }
  3762. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  3763. };
  3764. /**
  3765. * Draw all datapoints as a grid
  3766. * This function can be used when the style is 'grid'
  3767. */
  3768. Graph3d.prototype._redrawDataGrid = function() {
  3769. var canvas = this.frame.canvas,
  3770. ctx = canvas.getContext('2d'),
  3771. point, right, top, cross,
  3772. i,
  3773. topSideVisible, fillStyle, strokeStyle, lineWidth,
  3774. h, s, v, zAvg;
  3775. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  3776. return; // TODO: throw exception?
  3777. // calculate the translations and screen position of all points
  3778. for (i = 0; i < this.dataPoints.length; i++) {
  3779. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  3780. var screen = this._convertTranslationToScreen(trans);
  3781. this.dataPoints[i].trans = trans;
  3782. this.dataPoints[i].screen = screen;
  3783. // calculate the translation of the point at the bottom (needed for sorting)
  3784. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  3785. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  3786. }
  3787. // sort the points on depth of their (x,y) position (not on z)
  3788. var sortDepth = function (a, b) {
  3789. return b.dist - a.dist;
  3790. };
  3791. this.dataPoints.sort(sortDepth);
  3792. if (this.style === Graph3d.STYLE.SURFACE) {
  3793. for (i = 0; i < this.dataPoints.length; i++) {
  3794. point = this.dataPoints[i];
  3795. right = this.dataPoints[i].pointRight;
  3796. top = this.dataPoints[i].pointTop;
  3797. cross = this.dataPoints[i].pointCross;
  3798. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  3799. if (this.showGrayBottom || this.showShadow) {
  3800. // calculate the cross product of the two vectors from center
  3801. // to left and right, in order to know whether we are looking at the
  3802. // bottom or at the top side. We can also use the cross product
  3803. // for calculating light intensity
  3804. var aDiff = Point3d.subtract(cross.trans, point.trans);
  3805. var bDiff = Point3d.subtract(top.trans, right.trans);
  3806. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  3807. var len = crossproduct.length();
  3808. // FIXME: there is a bug with determining the surface side (shadow or colored)
  3809. topSideVisible = (crossproduct.z > 0);
  3810. }
  3811. else {
  3812. topSideVisible = true;
  3813. }
  3814. if (topSideVisible) {
  3815. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  3816. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  3817. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  3818. s = 1; // saturation
  3819. if (this.showShadow) {
  3820. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  3821. fillStyle = this._hsv2rgb(h, s, v);
  3822. strokeStyle = fillStyle;
  3823. }
  3824. else {
  3825. v = 1;
  3826. fillStyle = this._hsv2rgb(h, s, v);
  3827. strokeStyle = this.colorAxis;
  3828. }
  3829. }
  3830. else {
  3831. fillStyle = 'gray';
  3832. strokeStyle = this.colorAxis;
  3833. }
  3834. lineWidth = 0.5;
  3835. ctx.lineWidth = lineWidth;
  3836. ctx.fillStyle = fillStyle;
  3837. ctx.strokeStyle = strokeStyle;
  3838. ctx.beginPath();
  3839. ctx.moveTo(point.screen.x, point.screen.y);
  3840. ctx.lineTo(right.screen.x, right.screen.y);
  3841. ctx.lineTo(cross.screen.x, cross.screen.y);
  3842. ctx.lineTo(top.screen.x, top.screen.y);
  3843. ctx.closePath();
  3844. ctx.fill();
  3845. ctx.stroke();
  3846. }
  3847. }
  3848. }
  3849. else { // grid style
  3850. for (i = 0; i < this.dataPoints.length; i++) {
  3851. point = this.dataPoints[i];
  3852. right = this.dataPoints[i].pointRight;
  3853. top = this.dataPoints[i].pointTop;
  3854. if (point !== undefined) {
  3855. if (this.showPerspective) {
  3856. lineWidth = 2 / -point.trans.z;
  3857. }
  3858. else {
  3859. lineWidth = 2 * -(this.eye.z / this.camera.getArmLength());
  3860. }
  3861. }
  3862. if (point !== undefined && right !== undefined) {
  3863. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  3864. zAvg = (point.point.z + right.point.z) / 2;
  3865. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  3866. ctx.lineWidth = lineWidth;
  3867. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  3868. ctx.beginPath();
  3869. ctx.moveTo(point.screen.x, point.screen.y);
  3870. ctx.lineTo(right.screen.x, right.screen.y);
  3871. ctx.stroke();
  3872. }
  3873. if (point !== undefined && top !== undefined) {
  3874. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  3875. zAvg = (point.point.z + top.point.z) / 2;
  3876. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  3877. ctx.lineWidth = lineWidth;
  3878. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  3879. ctx.beginPath();
  3880. ctx.moveTo(point.screen.x, point.screen.y);
  3881. ctx.lineTo(top.screen.x, top.screen.y);
  3882. ctx.stroke();
  3883. }
  3884. }
  3885. }
  3886. };
  3887. /**
  3888. * Draw all datapoints as dots.
  3889. * This function can be used when the style is 'dot' or 'dot-line'
  3890. */
  3891. Graph3d.prototype._redrawDataDot = function() {
  3892. var canvas = this.frame.canvas;
  3893. var ctx = canvas.getContext('2d');
  3894. var i;
  3895. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  3896. return; // TODO: throw exception?
  3897. // calculate the translations of all points
  3898. for (i = 0; i < this.dataPoints.length; i++) {
  3899. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  3900. var screen = this._convertTranslationToScreen(trans);
  3901. this.dataPoints[i].trans = trans;
  3902. this.dataPoints[i].screen = screen;
  3903. // calculate the distance from the point at the bottom to the camera
  3904. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  3905. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  3906. }
  3907. // order the translated points by depth
  3908. var sortDepth = function (a, b) {
  3909. return b.dist - a.dist;
  3910. };
  3911. this.dataPoints.sort(sortDepth);
  3912. // draw the datapoints as colored circles
  3913. var dotSize = this.frame.clientWidth * 0.02; // px
  3914. for (i = 0; i < this.dataPoints.length; i++) {
  3915. var point = this.dataPoints[i];
  3916. if (this.style === Graph3d.STYLE.DOTLINE) {
  3917. // draw a vertical line from the bottom to the graph value
  3918. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  3919. var from = this._convert3Dto2D(point.bottom);
  3920. ctx.lineWidth = 1;
  3921. ctx.strokeStyle = this.colorGrid;
  3922. ctx.beginPath();
  3923. ctx.moveTo(from.x, from.y);
  3924. ctx.lineTo(point.screen.x, point.screen.y);
  3925. ctx.stroke();
  3926. }
  3927. // calculate radius for the circle
  3928. var size;
  3929. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3930. size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  3931. }
  3932. else {
  3933. size = dotSize;
  3934. }
  3935. var radius;
  3936. if (this.showPerspective) {
  3937. radius = size / -point.trans.z;
  3938. }
  3939. else {
  3940. radius = size * -(this.eye.z / this.camera.getArmLength());
  3941. }
  3942. if (radius < 0) {
  3943. radius = 0;
  3944. }
  3945. var hue, color, borderColor;
  3946. if (this.style === Graph3d.STYLE.DOTCOLOR ) {
  3947. // calculate the color based on the value
  3948. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  3949. color = this._hsv2rgb(hue, 1, 1);
  3950. borderColor = this._hsv2rgb(hue, 1, 0.8);
  3951. }
  3952. else if (this.style === Graph3d.STYLE.DOTSIZE) {
  3953. color = this.colorDot;
  3954. borderColor = this.colorDotBorder;
  3955. }
  3956. else {
  3957. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  3958. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  3959. color = this._hsv2rgb(hue, 1, 1);
  3960. borderColor = this._hsv2rgb(hue, 1, 0.8);
  3961. }
  3962. // draw the circle
  3963. ctx.lineWidth = 1.0;
  3964. ctx.strokeStyle = borderColor;
  3965. ctx.fillStyle = color;
  3966. ctx.beginPath();
  3967. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  3968. ctx.fill();
  3969. ctx.stroke();
  3970. }
  3971. };
  3972. /**
  3973. * Draw all datapoints as bars.
  3974. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  3975. */
  3976. Graph3d.prototype._redrawDataBar = function() {
  3977. var canvas = this.frame.canvas;
  3978. var ctx = canvas.getContext('2d');
  3979. var i, j, surface, corners;
  3980. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  3981. return; // TODO: throw exception?
  3982. // calculate the translations of all points
  3983. for (i = 0; i < this.dataPoints.length; i++) {
  3984. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  3985. var screen = this._convertTranslationToScreen(trans);
  3986. this.dataPoints[i].trans = trans;
  3987. this.dataPoints[i].screen = screen;
  3988. // calculate the distance from the point at the bottom to the camera
  3989. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  3990. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  3991. }
  3992. // order the translated points by depth
  3993. var sortDepth = function (a, b) {
  3994. return b.dist - a.dist;
  3995. };
  3996. this.dataPoints.sort(sortDepth);
  3997. // draw the datapoints as bars
  3998. var xWidth = this.xBarWidth / 2;
  3999. var yWidth = this.yBarWidth / 2;
  4000. for (i = 0; i < this.dataPoints.length; i++) {
  4001. var point = this.dataPoints[i];
  4002. // determine color
  4003. var hue, color, borderColor;
  4004. if (this.style === Graph3d.STYLE.BARCOLOR ) {
  4005. // calculate the color based on the value
  4006. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  4007. color = this._hsv2rgb(hue, 1, 1);
  4008. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4009. }
  4010. else if (this.style === Graph3d.STYLE.BARSIZE) {
  4011. color = this.colorDot;
  4012. borderColor = this.colorDotBorder;
  4013. }
  4014. else {
  4015. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4016. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4017. color = this._hsv2rgb(hue, 1, 1);
  4018. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4019. }
  4020. // calculate size for the bar
  4021. if (this.style === Graph3d.STYLE.BARSIZE) {
  4022. xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  4023. yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  4024. }
  4025. // calculate all corner points
  4026. var me = this;
  4027. var point3d = point.point;
  4028. var top = [
  4029. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  4030. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  4031. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  4032. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  4033. ];
  4034. var bottom = [
  4035. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)},
  4036. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)},
  4037. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
  4038. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
  4039. ];
  4040. // calculate screen location of the points
  4041. top.forEach(function (obj) {
  4042. obj.screen = me._convert3Dto2D(obj.point);
  4043. });
  4044. bottom.forEach(function (obj) {
  4045. obj.screen = me._convert3Dto2D(obj.point);
  4046. });
  4047. // create five sides, calculate both corner points and center points
  4048. var surfaces = [
  4049. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  4050. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  4051. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  4052. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  4053. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  4054. ];
  4055. point.surfaces = surfaces;
  4056. // calculate the distance of each of the surface centers to the camera
  4057. for (j = 0; j < surfaces.length; j++) {
  4058. surface = surfaces[j];
  4059. var transCenter = this._convertPointToTranslation(surface.center);
  4060. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  4061. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  4062. // but the current solution is fast/simple and works in 99.9% of all cases
  4063. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  4064. }
  4065. // order the surfaces by their (translated) depth
  4066. surfaces.sort(function (a, b) {
  4067. var diff = b.dist - a.dist;
  4068. if (diff) return diff;
  4069. // if equal depth, sort the top surface last
  4070. if (a.corners === top) return 1;
  4071. if (b.corners === top) return -1;
  4072. // both are equal
  4073. return 0;
  4074. });
  4075. // draw the ordered surfaces
  4076. ctx.lineWidth = 1;
  4077. ctx.strokeStyle = borderColor;
  4078. ctx.fillStyle = color;
  4079. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  4080. for (j = 2; j < surfaces.length; j++) {
  4081. surface = surfaces[j];
  4082. corners = surface.corners;
  4083. ctx.beginPath();
  4084. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  4085. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  4086. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  4087. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  4088. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  4089. ctx.fill();
  4090. ctx.stroke();
  4091. }
  4092. }
  4093. };
  4094. /**
  4095. * Draw a line through all datapoints.
  4096. * This function can be used when the style is 'line'
  4097. */
  4098. Graph3d.prototype._redrawDataLine = function() {
  4099. var canvas = this.frame.canvas,
  4100. ctx = canvas.getContext('2d'),
  4101. point, i;
  4102. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4103. return; // TODO: throw exception?
  4104. // calculate the translations of all points
  4105. for (i = 0; i < this.dataPoints.length; i++) {
  4106. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4107. var screen = this._convertTranslationToScreen(trans);
  4108. this.dataPoints[i].trans = trans;
  4109. this.dataPoints[i].screen = screen;
  4110. }
  4111. // start the line
  4112. if (this.dataPoints.length > 0) {
  4113. point = this.dataPoints[0];
  4114. ctx.lineWidth = 1; // TODO: make customizable
  4115. ctx.strokeStyle = 'blue'; // TODO: make customizable
  4116. ctx.beginPath();
  4117. ctx.moveTo(point.screen.x, point.screen.y);
  4118. }
  4119. // draw the datapoints as colored circles
  4120. for (i = 1; i < this.dataPoints.length; i++) {
  4121. point = this.dataPoints[i];
  4122. ctx.lineTo(point.screen.x, point.screen.y);
  4123. }
  4124. // finish the line
  4125. if (this.dataPoints.length > 0) {
  4126. ctx.stroke();
  4127. }
  4128. };
  4129. /**
  4130. * Start a moving operation inside the provided parent element
  4131. * @param {Event} event The event that occurred (required for
  4132. * retrieving the mouse position)
  4133. */
  4134. Graph3d.prototype._onMouseDown = function(event) {
  4135. event = event || window.event;
  4136. // check if mouse is still down (may be up when focus is lost for example
  4137. // in an iframe)
  4138. if (this.leftButtonDown) {
  4139. this._onMouseUp(event);
  4140. }
  4141. // only react on left mouse button down
  4142. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  4143. if (!this.leftButtonDown && !this.touchDown) return;
  4144. // get mouse position (different code for IE and all other browsers)
  4145. this.startMouseX = getMouseX(event);
  4146. this.startMouseY = getMouseY(event);
  4147. this.startStart = new Date(this.start);
  4148. this.startEnd = new Date(this.end);
  4149. this.startArmRotation = this.camera.getArmRotation();
  4150. this.frame.style.cursor = 'move';
  4151. // add event listeners to handle moving the contents
  4152. // we store the function onmousemove and onmouseup in the graph, so we can
  4153. // remove the eventlisteners lateron in the function mouseUp()
  4154. var me = this;
  4155. this.onmousemove = function (event) {me._onMouseMove(event);};
  4156. this.onmouseup = function (event) {me._onMouseUp(event);};
  4157. util.addEventListener(document, 'mousemove', me.onmousemove);
  4158. util.addEventListener(document, 'mouseup', me.onmouseup);
  4159. util.preventDefault(event);
  4160. };
  4161. /**
  4162. * Perform moving operating.
  4163. * This function activated from within the funcion Graph.mouseDown().
  4164. * @param {Event} event Well, eehh, the event
  4165. */
  4166. Graph3d.prototype._onMouseMove = function (event) {
  4167. event = event || window.event;
  4168. // calculate change in mouse position
  4169. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  4170. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  4171. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  4172. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  4173. var snapAngle = 4; // degrees
  4174. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  4175. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  4176. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  4177. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  4178. horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
  4179. }
  4180. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  4181. horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
  4182. }
  4183. // snap vertically to nice angles
  4184. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  4185. verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
  4186. }
  4187. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  4188. verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
  4189. }
  4190. this.camera.setArmRotation(horizontalNew, verticalNew);
  4191. this.redraw();
  4192. // fire a cameraPositionChange event
  4193. var parameters = this.getCameraPosition();
  4194. this.emit('cameraPositionChange', parameters);
  4195. util.preventDefault(event);
  4196. };
  4197. /**
  4198. * Stop moving operating.
  4199. * This function activated from within the funcion Graph.mouseDown().
  4200. * @param {event} event The event
  4201. */
  4202. Graph3d.prototype._onMouseUp = function (event) {
  4203. this.frame.style.cursor = 'auto';
  4204. this.leftButtonDown = false;
  4205. // remove event listeners here
  4206. util.removeEventListener(document, 'mousemove', this.onmousemove);
  4207. util.removeEventListener(document, 'mouseup', this.onmouseup);
  4208. util.preventDefault(event);
  4209. };
  4210. /**
  4211. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  4212. * @param {Event} event A mouse move event
  4213. */
  4214. Graph3d.prototype._onTooltip = function (event) {
  4215. var delay = 300; // ms
  4216. var mouseX = getMouseX(event) - util.getAbsoluteLeft(this.frame);
  4217. var mouseY = getMouseY(event) - util.getAbsoluteTop(this.frame);
  4218. if (!this.showTooltip) {
  4219. return;
  4220. }
  4221. if (this.tooltipTimeout) {
  4222. clearTimeout(this.tooltipTimeout);
  4223. }
  4224. // (delayed) display of a tooltip only if no mouse button is down
  4225. if (this.leftButtonDown) {
  4226. this._hideTooltip();
  4227. return;
  4228. }
  4229. if (this.tooltip && this.tooltip.dataPoint) {
  4230. // tooltip is currently visible
  4231. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  4232. if (dataPoint !== this.tooltip.dataPoint) {
  4233. // datapoint changed
  4234. if (dataPoint) {
  4235. this._showTooltip(dataPoint);
  4236. }
  4237. else {
  4238. this._hideTooltip();
  4239. }
  4240. }
  4241. }
  4242. else {
  4243. // tooltip is currently not visible
  4244. var me = this;
  4245. this.tooltipTimeout = setTimeout(function () {
  4246. me.tooltipTimeout = null;
  4247. // show a tooltip if we have a data point
  4248. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  4249. if (dataPoint) {
  4250. me._showTooltip(dataPoint);
  4251. }
  4252. }, delay);
  4253. }
  4254. };
  4255. /**
  4256. * Event handler for touchstart event on mobile devices
  4257. */
  4258. Graph3d.prototype._onTouchStart = function(event) {
  4259. this.touchDown = true;
  4260. var me = this;
  4261. this.ontouchmove = function (event) {me._onTouchMove(event);};
  4262. this.ontouchend = function (event) {me._onTouchEnd(event);};
  4263. util.addEventListener(document, 'touchmove', me.ontouchmove);
  4264. util.addEventListener(document, 'touchend', me.ontouchend);
  4265. this._onMouseDown(event);
  4266. };
  4267. /**
  4268. * Event handler for touchmove event on mobile devices
  4269. */
  4270. Graph3d.prototype._onTouchMove = function(event) {
  4271. this._onMouseMove(event);
  4272. };
  4273. /**
  4274. * Event handler for touchend event on mobile devices
  4275. */
  4276. Graph3d.prototype._onTouchEnd = function(event) {
  4277. this.touchDown = false;
  4278. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  4279. util.removeEventListener(document, 'touchend', this.ontouchend);
  4280. this._onMouseUp(event);
  4281. };
  4282. /**
  4283. * Event handler for mouse wheel event, used to zoom the graph
  4284. * Code from http://adomas.org/javascript-mouse-wheel/
  4285. * @param {event} event The event
  4286. */
  4287. Graph3d.prototype._onWheel = function(event) {
  4288. if (!event) /* For IE. */
  4289. event = window.event;
  4290. // retrieve delta
  4291. var delta = 0;
  4292. if (event.wheelDelta) { /* IE/Opera. */
  4293. delta = event.wheelDelta/120;
  4294. } else if (event.detail) { /* Mozilla case. */
  4295. // In Mozilla, sign of delta is different than in IE.
  4296. // Also, delta is multiple of 3.
  4297. delta = -event.detail/3;
  4298. }
  4299. // If delta is nonzero, handle it.
  4300. // Basically, delta is now positive if wheel was scrolled up,
  4301. // and negative, if wheel was scrolled down.
  4302. if (delta) {
  4303. var oldLength = this.camera.getArmLength();
  4304. var newLength = oldLength * (1 - delta / 10);
  4305. this.camera.setArmLength(newLength);
  4306. this.redraw();
  4307. this._hideTooltip();
  4308. }
  4309. // fire a cameraPositionChange event
  4310. var parameters = this.getCameraPosition();
  4311. this.emit('cameraPositionChange', parameters);
  4312. // Prevent default actions caused by mouse wheel.
  4313. // That might be ugly, but we handle scrolls somehow
  4314. // anyway, so don't bother here..
  4315. util.preventDefault(event);
  4316. };
  4317. /**
  4318. * Test whether a point lies inside given 2D triangle
  4319. * @param {Point2d} point
  4320. * @param {Point2d[]} triangle
  4321. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  4322. * @private
  4323. */
  4324. Graph3d.prototype._insideTriangle = function (point, triangle) {
  4325. var a = triangle[0],
  4326. b = triangle[1],
  4327. c = triangle[2];
  4328. function sign (x) {
  4329. return x > 0 ? 1 : x < 0 ? -1 : 0;
  4330. }
  4331. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  4332. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  4333. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  4334. // each of the three signs must be either equal to each other or zero
  4335. return (as == 0 || bs == 0 || as == bs) &&
  4336. (bs == 0 || cs == 0 || bs == cs) &&
  4337. (as == 0 || cs == 0 || as == cs);
  4338. };
  4339. /**
  4340. * Find a data point close to given screen position (x, y)
  4341. * @param {Number} x
  4342. * @param {Number} y
  4343. * @return {Object | null} The closest data point or null if not close to any data point
  4344. * @private
  4345. */
  4346. Graph3d.prototype._dataPointFromXY = function (x, y) {
  4347. var i,
  4348. distMax = 100, // px
  4349. dataPoint = null,
  4350. closestDataPoint = null,
  4351. closestDist = null,
  4352. center = new Point2d(x, y);
  4353. if (this.style === Graph3d.STYLE.BAR ||
  4354. this.style === Graph3d.STYLE.BARCOLOR ||
  4355. this.style === Graph3d.STYLE.BARSIZE) {
  4356. // the data points are ordered from far away to closest
  4357. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  4358. dataPoint = this.dataPoints[i];
  4359. var surfaces = dataPoint.surfaces;
  4360. if (surfaces) {
  4361. for (var s = surfaces.length - 1; s >= 0; s--) {
  4362. // split each surface in two triangles, and see if the center point is inside one of these
  4363. var surface = surfaces[s];
  4364. var corners = surface.corners;
  4365. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  4366. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  4367. if (this._insideTriangle(center, triangle1) ||
  4368. this._insideTriangle(center, triangle2)) {
  4369. // return immediately at the first hit
  4370. return dataPoint;
  4371. }
  4372. }
  4373. }
  4374. }
  4375. }
  4376. else {
  4377. // find the closest data point, using distance to the center of the point on 2d screen
  4378. for (i = 0; i < this.dataPoints.length; i++) {
  4379. dataPoint = this.dataPoints[i];
  4380. var point = dataPoint.screen;
  4381. if (point) {
  4382. var distX = Math.abs(x - point.x);
  4383. var distY = Math.abs(y - point.y);
  4384. var dist = Math.sqrt(distX * distX + distY * distY);
  4385. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  4386. closestDist = dist;
  4387. closestDataPoint = dataPoint;
  4388. }
  4389. }
  4390. }
  4391. }
  4392. return closestDataPoint;
  4393. };
  4394. /**
  4395. * Display a tooltip for given data point
  4396. * @param {Object} dataPoint
  4397. * @private
  4398. */
  4399. Graph3d.prototype._showTooltip = function (dataPoint) {
  4400. var content, line, dot;
  4401. if (!this.tooltip) {
  4402. content = document.createElement('div');
  4403. content.style.position = 'absolute';
  4404. content.style.padding = '10px';
  4405. content.style.border = '1px solid #4d4d4d';
  4406. content.style.color = '#1a1a1a';
  4407. content.style.background = 'rgba(255,255,255,0.7)';
  4408. content.style.borderRadius = '2px';
  4409. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  4410. line = document.createElement('div');
  4411. line.style.position = 'absolute';
  4412. line.style.height = '40px';
  4413. line.style.width = '0';
  4414. line.style.borderLeft = '1px solid #4d4d4d';
  4415. dot = document.createElement('div');
  4416. dot.style.position = 'absolute';
  4417. dot.style.height = '0';
  4418. dot.style.width = '0';
  4419. dot.style.border = '5px solid #4d4d4d';
  4420. dot.style.borderRadius = '5px';
  4421. this.tooltip = {
  4422. dataPoint: null,
  4423. dom: {
  4424. content: content,
  4425. line: line,
  4426. dot: dot
  4427. }
  4428. };
  4429. }
  4430. else {
  4431. content = this.tooltip.dom.content;
  4432. line = this.tooltip.dom.line;
  4433. dot = this.tooltip.dom.dot;
  4434. }
  4435. this._hideTooltip();
  4436. this.tooltip.dataPoint = dataPoint;
  4437. if (typeof this.showTooltip === 'function') {
  4438. content.innerHTML = this.showTooltip(dataPoint.point);
  4439. }
  4440. else {
  4441. content.innerHTML = '<table>' +
  4442. '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' +
  4443. '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' +
  4444. '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' +
  4445. '</table>';
  4446. }
  4447. content.style.left = '0';
  4448. content.style.top = '0';
  4449. this.frame.appendChild(content);
  4450. this.frame.appendChild(line);
  4451. this.frame.appendChild(dot);
  4452. // calculate sizes
  4453. var contentWidth = content.offsetWidth;
  4454. var contentHeight = content.offsetHeight;
  4455. var lineHeight = line.offsetHeight;
  4456. var dotWidth = dot.offsetWidth;
  4457. var dotHeight = dot.offsetHeight;
  4458. var left = dataPoint.screen.x - contentWidth / 2;
  4459. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  4460. line.style.left = dataPoint.screen.x + 'px';
  4461. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  4462. content.style.left = left + 'px';
  4463. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  4464. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  4465. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  4466. };
  4467. /**
  4468. * Hide the tooltip when displayed
  4469. * @private
  4470. */
  4471. Graph3d.prototype._hideTooltip = function () {
  4472. if (this.tooltip) {
  4473. this.tooltip.dataPoint = null;
  4474. for (var prop in this.tooltip.dom) {
  4475. if (this.tooltip.dom.hasOwnProperty(prop)) {
  4476. var elem = this.tooltip.dom[prop];
  4477. if (elem && elem.parentNode) {
  4478. elem.parentNode.removeChild(elem);
  4479. }
  4480. }
  4481. }
  4482. }
  4483. };
  4484. /**--------------------------------------------------------------------------**/
  4485. /**
  4486. * Get the horizontal mouse position from a mouse event
  4487. * @param {Event} event
  4488. * @return {Number} mouse x
  4489. */
  4490. getMouseX = function(event) {
  4491. if ('clientX' in event) return event.clientX;
  4492. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  4493. };
  4494. /**
  4495. * Get the vertical mouse position from a mouse event
  4496. * @param {Event} event
  4497. * @return {Number} mouse y
  4498. */
  4499. getMouseY = function(event) {
  4500. if ('clientY' in event) return event.clientY;
  4501. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  4502. };
  4503. module.exports = Graph3d;
  4504. /***/ },
  4505. /* 6 */
  4506. /***/ function(module, exports, __webpack_require__) {
  4507. var Point3d = __webpack_require__(9);
  4508. /**
  4509. * @class Camera
  4510. * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
  4511. * The camera is always looking in the direction of the origin of the arm.
  4512. * This way, the camera always rotates around one fixed point, the location
  4513. * of the camera arm.
  4514. *
  4515. * Documentation:
  4516. * http://en.wikipedia.org/wiki/3D_projection
  4517. */
  4518. Camera = function () {
  4519. this.armLocation = new Point3d();
  4520. this.armRotation = {};
  4521. this.armRotation.horizontal = 0;
  4522. this.armRotation.vertical = 0;
  4523. this.armLength = 1.7;
  4524. this.cameraLocation = new Point3d();
  4525. this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0);
  4526. this.calculateCameraOrientation();
  4527. };
  4528. /**
  4529. * Set the location (origin) of the arm
  4530. * @param {Number} x Normalized value of x
  4531. * @param {Number} y Normalized value of y
  4532. * @param {Number} z Normalized value of z
  4533. */
  4534. Camera.prototype.setArmLocation = function(x, y, z) {
  4535. this.armLocation.x = x;
  4536. this.armLocation.y = y;
  4537. this.armLocation.z = z;
  4538. this.calculateCameraOrientation();
  4539. };
  4540. /**
  4541. * Set the rotation of the camera arm
  4542. * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
  4543. * Optional, can be left undefined.
  4544. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
  4545. * if vertical=0.5*PI, the graph is shown from the
  4546. * top. Optional, can be left undefined.
  4547. */
  4548. Camera.prototype.setArmRotation = function(horizontal, vertical) {
  4549. if (horizontal !== undefined) {
  4550. this.armRotation.horizontal = horizontal;
  4551. }
  4552. if (vertical !== undefined) {
  4553. this.armRotation.vertical = vertical;
  4554. if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
  4555. if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI;
  4556. }
  4557. if (horizontal !== undefined || vertical !== undefined) {
  4558. this.calculateCameraOrientation();
  4559. }
  4560. };
  4561. /**
  4562. * Retrieve the current arm rotation
  4563. * @return {object} An object with parameters horizontal and vertical
  4564. */
  4565. Camera.prototype.getArmRotation = function() {
  4566. var rot = {};
  4567. rot.horizontal = this.armRotation.horizontal;
  4568. rot.vertical = this.armRotation.vertical;
  4569. return rot;
  4570. };
  4571. /**
  4572. * Set the (normalized) length of the camera arm.
  4573. * @param {Number} length A length between 0.71 and 5.0
  4574. */
  4575. Camera.prototype.setArmLength = function(length) {
  4576. if (length === undefined)
  4577. return;
  4578. this.armLength = length;
  4579. // Radius must be larger than the corner of the graph,
  4580. // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
  4581. // graph
  4582. if (this.armLength < 0.71) this.armLength = 0.71;
  4583. if (this.armLength > 5.0) this.armLength = 5.0;
  4584. this.calculateCameraOrientation();
  4585. };
  4586. /**
  4587. * Retrieve the arm length
  4588. * @return {Number} length
  4589. */
  4590. Camera.prototype.getArmLength = function() {
  4591. return this.armLength;
  4592. };
  4593. /**
  4594. * Retrieve the camera location
  4595. * @return {Point3d} cameraLocation
  4596. */
  4597. Camera.prototype.getCameraLocation = function() {
  4598. return this.cameraLocation;
  4599. };
  4600. /**
  4601. * Retrieve the camera rotation
  4602. * @return {Point3d} cameraRotation
  4603. */
  4604. Camera.prototype.getCameraRotation = function() {
  4605. return this.cameraRotation;
  4606. };
  4607. /**
  4608. * Calculate the location and rotation of the camera based on the
  4609. * position and orientation of the camera arm
  4610. */
  4611. Camera.prototype.calculateCameraOrientation = function() {
  4612. // calculate location of the camera
  4613. this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  4614. this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  4615. this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
  4616. // calculate rotation of the camera
  4617. this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical;
  4618. this.cameraRotation.y = 0;
  4619. this.cameraRotation.z = -this.armRotation.horizontal;
  4620. };
  4621. module.exports = Camera;
  4622. /***/ },
  4623. /* 7 */
  4624. /***/ function(module, exports, __webpack_require__) {
  4625. var DataView = __webpack_require__(4);
  4626. /**
  4627. * @class Filter
  4628. *
  4629. * @param {DataSet} data The google data table
  4630. * @param {Number} column The index of the column to be filtered
  4631. * @param {Graph} graph The graph
  4632. */
  4633. function Filter (data, column, graph) {
  4634. this.data = data;
  4635. this.column = column;
  4636. this.graph = graph; // the parent graph
  4637. this.index = undefined;
  4638. this.value = undefined;
  4639. // read all distinct values and select the first one
  4640. this.values = graph.getDistinctValues(data.get(), this.column);
  4641. // sort both numeric and string values correctly
  4642. this.values.sort(function (a, b) {
  4643. return a > b ? 1 : a < b ? -1 : 0;
  4644. });
  4645. if (this.values.length > 0) {
  4646. this.selectValue(0);
  4647. }
  4648. // create an array with the filtered datapoints. this will be loaded afterwards
  4649. this.dataPoints = [];
  4650. this.loaded = false;
  4651. this.onLoadCallback = undefined;
  4652. if (graph.animationPreload) {
  4653. this.loaded = false;
  4654. this.loadInBackground();
  4655. }
  4656. else {
  4657. this.loaded = true;
  4658. }
  4659. };
  4660. /**
  4661. * Return the label
  4662. * @return {string} label
  4663. */
  4664. Filter.prototype.isLoaded = function() {
  4665. return this.loaded;
  4666. };
  4667. /**
  4668. * Return the loaded progress
  4669. * @return {Number} percentage between 0 and 100
  4670. */
  4671. Filter.prototype.getLoadedProgress = function() {
  4672. var len = this.values.length;
  4673. var i = 0;
  4674. while (this.dataPoints[i]) {
  4675. i++;
  4676. }
  4677. return Math.round(i / len * 100);
  4678. };
  4679. /**
  4680. * Return the label
  4681. * @return {string} label
  4682. */
  4683. Filter.prototype.getLabel = function() {
  4684. return this.graph.filterLabel;
  4685. };
  4686. /**
  4687. * Return the columnIndex of the filter
  4688. * @return {Number} columnIndex
  4689. */
  4690. Filter.prototype.getColumn = function() {
  4691. return this.column;
  4692. };
  4693. /**
  4694. * Return the currently selected value. Returns undefined if there is no selection
  4695. * @return {*} value
  4696. */
  4697. Filter.prototype.getSelectedValue = function() {
  4698. if (this.index === undefined)
  4699. return undefined;
  4700. return this.values[this.index];
  4701. };
  4702. /**
  4703. * Retrieve all values of the filter
  4704. * @return {Array} values
  4705. */
  4706. Filter.prototype.getValues = function() {
  4707. return this.values;
  4708. };
  4709. /**
  4710. * Retrieve one value of the filter
  4711. * @param {Number} index
  4712. * @return {*} value
  4713. */
  4714. Filter.prototype.getValue = function(index) {
  4715. if (index >= this.values.length)
  4716. throw 'Error: index out of range';
  4717. return this.values[index];
  4718. };
  4719. /**
  4720. * Retrieve the (filtered) dataPoints for the currently selected filter index
  4721. * @param {Number} [index] (optional)
  4722. * @return {Array} dataPoints
  4723. */
  4724. Filter.prototype._getDataPoints = function(index) {
  4725. if (index === undefined)
  4726. index = this.index;
  4727. if (index === undefined)
  4728. return [];
  4729. var dataPoints;
  4730. if (this.dataPoints[index]) {
  4731. dataPoints = this.dataPoints[index];
  4732. }
  4733. else {
  4734. var f = {};
  4735. f.column = this.column;
  4736. f.value = this.values[index];
  4737. var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get();
  4738. dataPoints = this.graph._getDataPoints(dataView);
  4739. this.dataPoints[index] = dataPoints;
  4740. }
  4741. return dataPoints;
  4742. };
  4743. /**
  4744. * Set a callback function when the filter is fully loaded.
  4745. */
  4746. Filter.prototype.setOnLoadCallback = function(callback) {
  4747. this.onLoadCallback = callback;
  4748. };
  4749. /**
  4750. * Add a value to the list with available values for this filter
  4751. * No double entries will be created.
  4752. * @param {Number} index
  4753. */
  4754. Filter.prototype.selectValue = function(index) {
  4755. if (index >= this.values.length)
  4756. throw 'Error: index out of range';
  4757. this.index = index;
  4758. this.value = this.values[index];
  4759. };
  4760. /**
  4761. * Load all filtered rows in the background one by one
  4762. * Start this method without providing an index!
  4763. */
  4764. Filter.prototype.loadInBackground = function(index) {
  4765. if (index === undefined)
  4766. index = 0;
  4767. var frame = this.graph.frame;
  4768. if (index < this.values.length) {
  4769. var dataPointsTemp = this._getDataPoints(index);
  4770. //this.graph.redrawInfo(); // TODO: not neat
  4771. // create a progress box
  4772. if (frame.progress === undefined) {
  4773. frame.progress = document.createElement('DIV');
  4774. frame.progress.style.position = 'absolute';
  4775. frame.progress.style.color = 'gray';
  4776. frame.appendChild(frame.progress);
  4777. }
  4778. var progress = this.getLoadedProgress();
  4779. frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
  4780. // TODO: this is no nice solution...
  4781. frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
  4782. frame.progress.style.left = 10 + 'px';
  4783. var me = this;
  4784. setTimeout(function() {me.loadInBackground(index+1);}, 10);
  4785. this.loaded = false;
  4786. }
  4787. else {
  4788. this.loaded = true;
  4789. // remove the progress box
  4790. if (frame.progress !== undefined) {
  4791. frame.removeChild(frame.progress);
  4792. frame.progress = undefined;
  4793. }
  4794. if (this.onLoadCallback)
  4795. this.onLoadCallback();
  4796. }
  4797. };
  4798. module.exports = Filter;
  4799. /***/ },
  4800. /* 8 */
  4801. /***/ function(module, exports, __webpack_require__) {
  4802. /**
  4803. * @prototype Point2d
  4804. * @param {Number} [x]
  4805. * @param {Number} [y]
  4806. */
  4807. Point2d = function (x, y) {
  4808. this.x = x !== undefined ? x : 0;
  4809. this.y = y !== undefined ? y : 0;
  4810. };
  4811. module.exports = Point2d;
  4812. /***/ },
  4813. /* 9 */
  4814. /***/ function(module, exports, __webpack_require__) {
  4815. /**
  4816. * @prototype Point3d
  4817. * @param {Number} [x]
  4818. * @param {Number} [y]
  4819. * @param {Number} [z]
  4820. */
  4821. function Point3d(x, y, z) {
  4822. this.x = x !== undefined ? x : 0;
  4823. this.y = y !== undefined ? y : 0;
  4824. this.z = z !== undefined ? z : 0;
  4825. };
  4826. /**
  4827. * Subtract the two provided points, returns a-b
  4828. * @param {Point3d} a
  4829. * @param {Point3d} b
  4830. * @return {Point3d} a-b
  4831. */
  4832. Point3d.subtract = function(a, b) {
  4833. var sub = new Point3d();
  4834. sub.x = a.x - b.x;
  4835. sub.y = a.y - b.y;
  4836. sub.z = a.z - b.z;
  4837. return sub;
  4838. };
  4839. /**
  4840. * Add the two provided points, returns a+b
  4841. * @param {Point3d} a
  4842. * @param {Point3d} b
  4843. * @return {Point3d} a+b
  4844. */
  4845. Point3d.add = function(a, b) {
  4846. var sum = new Point3d();
  4847. sum.x = a.x + b.x;
  4848. sum.y = a.y + b.y;
  4849. sum.z = a.z + b.z;
  4850. return sum;
  4851. };
  4852. /**
  4853. * Calculate the average of two 3d points
  4854. * @param {Point3d} a
  4855. * @param {Point3d} b
  4856. * @return {Point3d} The average, (a+b)/2
  4857. */
  4858. Point3d.avg = function(a, b) {
  4859. return new Point3d(
  4860. (a.x + b.x) / 2,
  4861. (a.y + b.y) / 2,
  4862. (a.z + b.z) / 2
  4863. );
  4864. };
  4865. /**
  4866. * Calculate the cross product of the two provided points, returns axb
  4867. * Documentation: http://en.wikipedia.org/wiki/Cross_product
  4868. * @param {Point3d} a
  4869. * @param {Point3d} b
  4870. * @return {Point3d} cross product axb
  4871. */
  4872. Point3d.crossProduct = function(a, b) {
  4873. var crossproduct = new Point3d();
  4874. crossproduct.x = a.y * b.z - a.z * b.y;
  4875. crossproduct.y = a.z * b.x - a.x * b.z;
  4876. crossproduct.z = a.x * b.y - a.y * b.x;
  4877. return crossproduct;
  4878. };
  4879. /**
  4880. * Rtrieve the length of the vector (or the distance from this point to the origin
  4881. * @return {Number} length
  4882. */
  4883. Point3d.prototype.length = function() {
  4884. return Math.sqrt(
  4885. this.x * this.x +
  4886. this.y * this.y +
  4887. this.z * this.z
  4888. );
  4889. };
  4890. module.exports = Point3d;
  4891. /***/ },
  4892. /* 10 */
  4893. /***/ function(module, exports, __webpack_require__) {
  4894. var util = __webpack_require__(1);
  4895. /**
  4896. * @constructor Slider
  4897. *
  4898. * An html slider control with start/stop/prev/next buttons
  4899. * @param {Element} container The element where the slider will be created
  4900. * @param {Object} options Available options:
  4901. * {boolean} visible If true (default) the
  4902. * slider is visible.
  4903. */
  4904. function Slider(container, options) {
  4905. if (container === undefined) {
  4906. throw 'Error: No container element defined';
  4907. }
  4908. this.container = container;
  4909. this.visible = (options && options.visible != undefined) ? options.visible : true;
  4910. if (this.visible) {
  4911. this.frame = document.createElement('DIV');
  4912. //this.frame.style.backgroundColor = '#E5E5E5';
  4913. this.frame.style.width = '100%';
  4914. this.frame.style.position = 'relative';
  4915. this.container.appendChild(this.frame);
  4916. this.frame.prev = document.createElement('INPUT');
  4917. this.frame.prev.type = 'BUTTON';
  4918. this.frame.prev.value = 'Prev';
  4919. this.frame.appendChild(this.frame.prev);
  4920. this.frame.play = document.createElement('INPUT');
  4921. this.frame.play.type = 'BUTTON';
  4922. this.frame.play.value = 'Play';
  4923. this.frame.appendChild(this.frame.play);
  4924. this.frame.next = document.createElement('INPUT');
  4925. this.frame.next.type = 'BUTTON';
  4926. this.frame.next.value = 'Next';
  4927. this.frame.appendChild(this.frame.next);
  4928. this.frame.bar = document.createElement('INPUT');
  4929. this.frame.bar.type = 'BUTTON';
  4930. this.frame.bar.style.position = 'absolute';
  4931. this.frame.bar.style.border = '1px solid red';
  4932. this.frame.bar.style.width = '100px';
  4933. this.frame.bar.style.height = '6px';
  4934. this.frame.bar.style.borderRadius = '2px';
  4935. this.frame.bar.style.MozBorderRadius = '2px';
  4936. this.frame.bar.style.border = '1px solid #7F7F7F';
  4937. this.frame.bar.style.backgroundColor = '#E5E5E5';
  4938. this.frame.appendChild(this.frame.bar);
  4939. this.frame.slide = document.createElement('INPUT');
  4940. this.frame.slide.type = 'BUTTON';
  4941. this.frame.slide.style.margin = '0px';
  4942. this.frame.slide.value = ' ';
  4943. this.frame.slide.style.position = 'relative';
  4944. this.frame.slide.style.left = '-100px';
  4945. this.frame.appendChild(this.frame.slide);
  4946. // create events
  4947. var me = this;
  4948. this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);};
  4949. this.frame.prev.onclick = function (event) {me.prev(event);};
  4950. this.frame.play.onclick = function (event) {me.togglePlay(event);};
  4951. this.frame.next.onclick = function (event) {me.next(event);};
  4952. }
  4953. this.onChangeCallback = undefined;
  4954. this.values = [];
  4955. this.index = undefined;
  4956. this.playTimeout = undefined;
  4957. this.playInterval = 1000; // milliseconds
  4958. this.playLoop = true;
  4959. }
  4960. /**
  4961. * Select the previous index
  4962. */
  4963. Slider.prototype.prev = function() {
  4964. var index = this.getIndex();
  4965. if (index > 0) {
  4966. index--;
  4967. this.setIndex(index);
  4968. }
  4969. };
  4970. /**
  4971. * Select the next index
  4972. */
  4973. Slider.prototype.next = function() {
  4974. var index = this.getIndex();
  4975. if (index < this.values.length - 1) {
  4976. index++;
  4977. this.setIndex(index);
  4978. }
  4979. };
  4980. /**
  4981. * Select the next index
  4982. */
  4983. Slider.prototype.playNext = function() {
  4984. var start = new Date();
  4985. var index = this.getIndex();
  4986. if (index < this.values.length - 1) {
  4987. index++;
  4988. this.setIndex(index);
  4989. }
  4990. else if (this.playLoop) {
  4991. // jump to the start
  4992. index = 0;
  4993. this.setIndex(index);
  4994. }
  4995. var end = new Date();
  4996. var diff = (end - start);
  4997. // calculate how much time it to to set the index and to execute the callback
  4998. // function.
  4999. var interval = Math.max(this.playInterval - diff, 0);
  5000. // document.title = diff // TODO: cleanup
  5001. var me = this;
  5002. this.playTimeout = setTimeout(function() {me.playNext();}, interval);
  5003. };
  5004. /**
  5005. * Toggle start or stop playing
  5006. */
  5007. Slider.prototype.togglePlay = function() {
  5008. if (this.playTimeout === undefined) {
  5009. this.play();
  5010. } else {
  5011. this.stop();
  5012. }
  5013. };
  5014. /**
  5015. * Start playing
  5016. */
  5017. Slider.prototype.play = function() {
  5018. // Test whether already playing
  5019. if (this.playTimeout) return;
  5020. this.playNext();
  5021. if (this.frame) {
  5022. this.frame.play.value = 'Stop';
  5023. }
  5024. };
  5025. /**
  5026. * Stop playing
  5027. */
  5028. Slider.prototype.stop = function() {
  5029. clearInterval(this.playTimeout);
  5030. this.playTimeout = undefined;
  5031. if (this.frame) {
  5032. this.frame.play.value = 'Play';
  5033. }
  5034. };
  5035. /**
  5036. * Set a callback function which will be triggered when the value of the
  5037. * slider bar has changed.
  5038. */
  5039. Slider.prototype.setOnChangeCallback = function(callback) {
  5040. this.onChangeCallback = callback;
  5041. };
  5042. /**
  5043. * Set the interval for playing the list
  5044. * @param {Number} interval The interval in milliseconds
  5045. */
  5046. Slider.prototype.setPlayInterval = function(interval) {
  5047. this.playInterval = interval;
  5048. };
  5049. /**
  5050. * Retrieve the current play interval
  5051. * @return {Number} interval The interval in milliseconds
  5052. */
  5053. Slider.prototype.getPlayInterval = function(interval) {
  5054. return this.playInterval;
  5055. };
  5056. /**
  5057. * Set looping on or off
  5058. * @pararm {boolean} doLoop If true, the slider will jump to the start when
  5059. * the end is passed, and will jump to the end
  5060. * when the start is passed.
  5061. */
  5062. Slider.prototype.setPlayLoop = function(doLoop) {
  5063. this.playLoop = doLoop;
  5064. };
  5065. /**
  5066. * Execute the onchange callback function
  5067. */
  5068. Slider.prototype.onChange = function() {
  5069. if (this.onChangeCallback !== undefined) {
  5070. this.onChangeCallback();
  5071. }
  5072. };
  5073. /**
  5074. * redraw the slider on the correct place
  5075. */
  5076. Slider.prototype.redraw = function() {
  5077. if (this.frame) {
  5078. // resize the bar
  5079. this.frame.bar.style.top = (this.frame.clientHeight/2 -
  5080. this.frame.bar.offsetHeight/2) + 'px';
  5081. this.frame.bar.style.width = (this.frame.clientWidth -
  5082. this.frame.prev.clientWidth -
  5083. this.frame.play.clientWidth -
  5084. this.frame.next.clientWidth - 30) + 'px';
  5085. // position the slider button
  5086. var left = this.indexToLeft(this.index);
  5087. this.frame.slide.style.left = (left) + 'px';
  5088. }
  5089. };
  5090. /**
  5091. * Set the list with values for the slider
  5092. * @param {Array} values A javascript array with values (any type)
  5093. */
  5094. Slider.prototype.setValues = function(values) {
  5095. this.values = values;
  5096. if (this.values.length > 0)
  5097. this.setIndex(0);
  5098. else
  5099. this.index = undefined;
  5100. };
  5101. /**
  5102. * Select a value by its index
  5103. * @param {Number} index
  5104. */
  5105. Slider.prototype.setIndex = function(index) {
  5106. if (index < this.values.length) {
  5107. this.index = index;
  5108. this.redraw();
  5109. this.onChange();
  5110. }
  5111. else {
  5112. throw 'Error: index out of range';
  5113. }
  5114. };
  5115. /**
  5116. * retrieve the index of the currently selected vaue
  5117. * @return {Number} index
  5118. */
  5119. Slider.prototype.getIndex = function() {
  5120. return this.index;
  5121. };
  5122. /**
  5123. * retrieve the currently selected value
  5124. * @return {*} value
  5125. */
  5126. Slider.prototype.get = function() {
  5127. return this.values[this.index];
  5128. };
  5129. Slider.prototype._onMouseDown = function(event) {
  5130. // only react on left mouse button down
  5131. var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  5132. if (!leftButtonDown) return;
  5133. this.startClientX = event.clientX;
  5134. this.startSlideX = parseFloat(this.frame.slide.style.left);
  5135. this.frame.style.cursor = 'move';
  5136. // add event listeners to handle moving the contents
  5137. // we store the function onmousemove and onmouseup in the graph, so we can
  5138. // remove the eventlisteners lateron in the function mouseUp()
  5139. var me = this;
  5140. this.onmousemove = function (event) {me._onMouseMove(event);};
  5141. this.onmouseup = function (event) {me._onMouseUp(event);};
  5142. util.addEventListener(document, 'mousemove', this.onmousemove);
  5143. util.addEventListener(document, 'mouseup', this.onmouseup);
  5144. util.preventDefault(event);
  5145. };
  5146. Slider.prototype.leftToIndex = function (left) {
  5147. var width = parseFloat(this.frame.bar.style.width) -
  5148. this.frame.slide.clientWidth - 10;
  5149. var x = left - 3;
  5150. var index = Math.round(x / width * (this.values.length-1));
  5151. if (index < 0) index = 0;
  5152. if (index > this.values.length-1) index = this.values.length-1;
  5153. return index;
  5154. };
  5155. Slider.prototype.indexToLeft = function (index) {
  5156. var width = parseFloat(this.frame.bar.style.width) -
  5157. this.frame.slide.clientWidth - 10;
  5158. var x = index / (this.values.length-1) * width;
  5159. var left = x + 3;
  5160. return left;
  5161. };
  5162. Slider.prototype._onMouseMove = function (event) {
  5163. var diff = event.clientX - this.startClientX;
  5164. var x = this.startSlideX + diff;
  5165. var index = this.leftToIndex(x);
  5166. this.setIndex(index);
  5167. util.preventDefault();
  5168. };
  5169. Slider.prototype._onMouseUp = function (event) {
  5170. this.frame.style.cursor = 'auto';
  5171. // remove event listeners
  5172. util.removeEventListener(document, 'mousemove', this.onmousemove);
  5173. util.removeEventListener(document, 'mouseup', this.onmouseup);
  5174. util.preventDefault();
  5175. };
  5176. module.exports = Slider;
  5177. /***/ },
  5178. /* 11 */
  5179. /***/ function(module, exports, __webpack_require__) {
  5180. /**
  5181. * @prototype StepNumber
  5182. * The class StepNumber is an iterator for Numbers. You provide a start and end
  5183. * value, and a best step size. StepNumber itself rounds to fixed values and
  5184. * a finds the step that best fits the provided step.
  5185. *
  5186. * If prettyStep is true, the step size is chosen as close as possible to the
  5187. * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
  5188. *
  5189. * Example usage:
  5190. * var step = new StepNumber(0, 10, 2.5, true);
  5191. * step.start();
  5192. * while (!step.end()) {
  5193. * alert(step.getCurrent());
  5194. * step.next();
  5195. * }
  5196. *
  5197. * Version: 1.0
  5198. *
  5199. * @param {Number} start The start value
  5200. * @param {Number} end The end value
  5201. * @param {Number} step Optional. Step size. Must be a positive value.
  5202. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  5203. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5204. */
  5205. function StepNumber(start, end, step, prettyStep) {
  5206. // set default values
  5207. this._start = 0;
  5208. this._end = 0;
  5209. this._step = 1;
  5210. this.prettyStep = true;
  5211. this.precision = 5;
  5212. this._current = 0;
  5213. this.setRange(start, end, step, prettyStep);
  5214. };
  5215. /**
  5216. * Set a new range: start, end and step.
  5217. *
  5218. * @param {Number} start The start value
  5219. * @param {Number} end The end value
  5220. * @param {Number} step Optional. Step size. Must be a positive value.
  5221. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  5222. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5223. */
  5224. StepNumber.prototype.setRange = function(start, end, step, prettyStep) {
  5225. this._start = start ? start : 0;
  5226. this._end = end ? end : 0;
  5227. this.setStep(step, prettyStep);
  5228. };
  5229. /**
  5230. * Set a new step size
  5231. * @param {Number} step New step size. Must be a positive value
  5232. * @param {boolean} prettyStep Optional. If true, the provided step is rounded
  5233. * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5234. */
  5235. StepNumber.prototype.setStep = function(step, prettyStep) {
  5236. if (step === undefined || step <= 0)
  5237. return;
  5238. if (prettyStep !== undefined)
  5239. this.prettyStep = prettyStep;
  5240. if (this.prettyStep === true)
  5241. this._step = StepNumber.calculatePrettyStep(step);
  5242. else
  5243. this._step = step;
  5244. };
  5245. /**
  5246. * Calculate a nice step size, closest to the desired step size.
  5247. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
  5248. * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
  5249. * @param {Number} step Desired step size
  5250. * @return {Number} Nice step size
  5251. */
  5252. StepNumber.calculatePrettyStep = function (step) {
  5253. var log10 = function (x) {return Math.log(x) / Math.LN10;};
  5254. // try three steps (multiple of 1, 2, or 5
  5255. var step1 = Math.pow(10, Math.round(log10(step))),
  5256. step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
  5257. step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
  5258. // choose the best step (closest to minimum step)
  5259. var prettyStep = step1;
  5260. if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
  5261. if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
  5262. // for safety
  5263. if (prettyStep <= 0) {
  5264. prettyStep = 1;
  5265. }
  5266. return prettyStep;
  5267. };
  5268. /**
  5269. * returns the current value of the step
  5270. * @return {Number} current value
  5271. */
  5272. StepNumber.prototype.getCurrent = function () {
  5273. return parseFloat(this._current.toPrecision(this.precision));
  5274. };
  5275. /**
  5276. * returns the current step size
  5277. * @return {Number} current step size
  5278. */
  5279. StepNumber.prototype.getStep = function () {
  5280. return this._step;
  5281. };
  5282. /**
  5283. * Set the current value to the largest value smaller than start, which
  5284. * is a multiple of the step size
  5285. */
  5286. StepNumber.prototype.start = function() {
  5287. this._current = this._start - this._start % this._step;
  5288. };
  5289. /**
  5290. * Do a step, add the step size to the current value
  5291. */
  5292. StepNumber.prototype.next = function () {
  5293. this._current += this._step;
  5294. };
  5295. /**
  5296. * Returns true whether the end is reached
  5297. * @return {boolean} True if the current value has passed the end value.
  5298. */
  5299. StepNumber.prototype.end = function () {
  5300. return (this._current > this._end);
  5301. };
  5302. module.exports = StepNumber;
  5303. /***/ },
  5304. /* 12 */
  5305. /***/ function(module, exports, __webpack_require__) {
  5306. var Emitter = __webpack_require__(46);
  5307. var Hammer = __webpack_require__(41);
  5308. var util = __webpack_require__(1);
  5309. var DataSet = __webpack_require__(3);
  5310. var DataView = __webpack_require__(4);
  5311. var Range = __webpack_require__(15);
  5312. var Core = __webpack_require__(42);
  5313. var TimeAxis = __webpack_require__(27);
  5314. var CurrentTime = __webpack_require__(19);
  5315. var CustomTime = __webpack_require__(20);
  5316. var ItemSet = __webpack_require__(24);
  5317. /**
  5318. * Create a timeline visualization
  5319. * @param {HTMLElement} container
  5320. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  5321. * @param {Object} [options] See Timeline.setOptions for the available options.
  5322. * @constructor
  5323. */
  5324. function Timeline (container, items, options) {
  5325. // mix the core properties in here
  5326. for (var coreProp in Core.prototype) {
  5327. if (Core.prototype.hasOwnProperty(coreProp) && !Timeline.prototype.hasOwnProperty(coreProp)) {
  5328. Timeline.prototype[coreProp] = Core.prototype[coreProp];
  5329. }
  5330. }
  5331. if (!(this instanceof Timeline)) {
  5332. throw new SyntaxError('Constructor must be called with the new operator');
  5333. }
  5334. var me = this;
  5335. this.defaultOptions = {
  5336. start: null,
  5337. end: null,
  5338. autoResize: true,
  5339. orientation: 'bottom',
  5340. width: null,
  5341. height: null,
  5342. maxHeight: null,
  5343. minHeight: null
  5344. };
  5345. this.options = util.deepExtend({}, this.defaultOptions);
  5346. // Create the DOM, props, and emitter
  5347. this._create(container);
  5348. // all components listed here will be repainted automatically
  5349. this.components = [];
  5350. this.body = {
  5351. dom: this.dom,
  5352. domProps: this.props,
  5353. emitter: {
  5354. on: this.on.bind(this),
  5355. off: this.off.bind(this),
  5356. emit: this.emit.bind(this)
  5357. },
  5358. util: {
  5359. snap: null, // will be specified after TimeAxis is created
  5360. toScreen: me._toScreen.bind(me),
  5361. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  5362. toTime: me._toTime.bind(me),
  5363. toGlobalTime : me._toGlobalTime.bind(me)
  5364. }
  5365. };
  5366. // range
  5367. this.range = new Range(this.body);
  5368. this.components.push(this.range);
  5369. this.body.range = this.range;
  5370. // time axis
  5371. this.timeAxis = new TimeAxis(this.body);
  5372. this.components.push(this.timeAxis);
  5373. this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  5374. // current time bar
  5375. this.currentTime = new CurrentTime(this.body);
  5376. this.components.push(this.currentTime);
  5377. // custom time bar
  5378. // Note: time bar will be attached in this.setOptions when selected
  5379. this.customTime = new CustomTime(this.body);
  5380. this.components.push(this.customTime);
  5381. // item set
  5382. this.itemSet = new ItemSet(this.body);
  5383. this.components.push(this.itemSet);
  5384. this.itemsData = null; // DataSet
  5385. this.groupsData = null; // DataSet
  5386. // apply options
  5387. if (options) {
  5388. this.setOptions(options);
  5389. }
  5390. // create itemset
  5391. if (items) {
  5392. this.setItems(items);
  5393. }
  5394. else {
  5395. this.redraw();
  5396. }
  5397. }
  5398. /**
  5399. * Set options. Options will be passed to all components loaded in the Timeline.
  5400. * @param {Object} [options]
  5401. * {String} orientation
  5402. * Vertical orientation for the Timeline,
  5403. * can be 'bottom' (default) or 'top'.
  5404. * {String | Number} width
  5405. * Width for the timeline, a number in pixels or
  5406. * a css string like '1000px' or '75%'. '100%' by default.
  5407. * {String | Number} height
  5408. * Fixed height for the Timeline, a number in pixels or
  5409. * a css string like '400px' or '75%'. If undefined,
  5410. * The Timeline will automatically size such that
  5411. * its contents fit.
  5412. * {String | Number} minHeight
  5413. * Minimum height for the Timeline, a number in pixels or
  5414. * a css string like '400px' or '75%'.
  5415. * {String | Number} maxHeight
  5416. * Maximum height for the Timeline, a number in pixels or
  5417. * a css string like '400px' or '75%'.
  5418. * {Number | Date | String} start
  5419. * Start date for the visible window
  5420. * {Number | Date | String} end
  5421. * End date for the visible window
  5422. */
  5423. Timeline.prototype.setOptions = function (options) {
  5424. if (options) {
  5425. // copy the known options
  5426. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation'];
  5427. util.selectiveExtend(fields, this.options, options);
  5428. // enable/disable autoResize
  5429. this._initAutoResize();
  5430. }
  5431. // propagate options to all components
  5432. this.components.forEach(function (component) {
  5433. component.setOptions(options);
  5434. });
  5435. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  5436. if (options && options.order) {
  5437. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  5438. }
  5439. // redraw everything
  5440. this.redraw();
  5441. };
  5442. /**
  5443. * Set items
  5444. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  5445. */
  5446. Timeline.prototype.setItems = function(items) {
  5447. var initialLoad = (this.itemsData == null);
  5448. // convert to type DataSet when needed
  5449. var newDataSet;
  5450. if (!items) {
  5451. newDataSet = null;
  5452. }
  5453. else if (items instanceof DataSet || items instanceof DataView) {
  5454. newDataSet = items;
  5455. }
  5456. else {
  5457. // turn an array into a dataset
  5458. newDataSet = new DataSet(items, {
  5459. type: {
  5460. start: 'Date',
  5461. end: 'Date'
  5462. }
  5463. });
  5464. }
  5465. // set items
  5466. this.itemsData = newDataSet;
  5467. this.itemSet && this.itemSet.setItems(newDataSet);
  5468. if (initialLoad && ('start' in this.options || 'end' in this.options)) {
  5469. this.fit();
  5470. var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null;
  5471. var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null;
  5472. this.setWindow(start, end);
  5473. }
  5474. };
  5475. /**
  5476. * Set groups
  5477. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  5478. */
  5479. Timeline.prototype.setGroups = function(groups) {
  5480. // convert to type DataSet when needed
  5481. var newDataSet;
  5482. if (!groups) {
  5483. newDataSet = null;
  5484. }
  5485. else if (groups instanceof DataSet || groups instanceof DataView) {
  5486. newDataSet = groups;
  5487. }
  5488. else {
  5489. // turn an array into a dataset
  5490. newDataSet = new DataSet(groups);
  5491. }
  5492. this.groupsData = newDataSet;
  5493. this.itemSet.setGroups(newDataSet);
  5494. };
  5495. /**
  5496. * Set selected items by their id. Replaces the current selection
  5497. * Unknown id's are silently ignored.
  5498. * @param {Array} [ids] An array with zero or more id's of the items to be
  5499. * selected. If ids is an empty array, all items will be
  5500. * unselected.
  5501. */
  5502. Timeline.prototype.setSelection = function(ids) {
  5503. this.itemSet && this.itemSet.setSelection(ids);
  5504. };
  5505. /**
  5506. * Get the selected items by their id
  5507. * @return {Array} ids The ids of the selected items
  5508. */
  5509. Timeline.prototype.getSelection = function() {
  5510. return this.itemSet && this.itemSet.getSelection() || [];
  5511. };
  5512. /**
  5513. * Get the data range of the item set.
  5514. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  5515. * When no minimum is found, min==null
  5516. * When no maximum is found, max==null
  5517. */
  5518. Timeline.prototype.getItemRange = function() {
  5519. // calculate min from start filed
  5520. var dataset = this.itemsData.getDataSet(),
  5521. min = null,
  5522. max = null;
  5523. if (dataset) {
  5524. // calculate the minimum value of the field 'start'
  5525. var minItem = dataset.min('start');
  5526. min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
  5527. // Note: we convert first to Date and then to number because else
  5528. // a conversion from ISODate to Number will fail
  5529. // calculate maximum value of fields 'start' and 'end'
  5530. var maxStartItem = dataset.max('start');
  5531. if (maxStartItem) {
  5532. max = util.convert(maxStartItem.start, 'Date').valueOf();
  5533. }
  5534. var maxEndItem = dataset.max('end');
  5535. if (maxEndItem) {
  5536. if (max == null) {
  5537. max = util.convert(maxEndItem.end, 'Date').valueOf();
  5538. }
  5539. else {
  5540. max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
  5541. }
  5542. }
  5543. }
  5544. return {
  5545. min: (min != null) ? new Date(min) : null,
  5546. max: (max != null) ? new Date(max) : null
  5547. };
  5548. };
  5549. module.exports = Timeline;
  5550. /***/ },
  5551. /* 13 */
  5552. /***/ function(module, exports, __webpack_require__) {
  5553. var Emitter = __webpack_require__(46);
  5554. var Hammer = __webpack_require__(41);
  5555. var util = __webpack_require__(1);
  5556. var DataSet = __webpack_require__(3);
  5557. var DataView = __webpack_require__(4);
  5558. var Range = __webpack_require__(15);
  5559. var Core = __webpack_require__(42);
  5560. var TimeAxis = __webpack_require__(27);
  5561. var CurrentTime = __webpack_require__(19);
  5562. var CustomTime = __webpack_require__(20);
  5563. var LineGraph = __webpack_require__(26);
  5564. /**
  5565. * Create a timeline visualization
  5566. * @param {HTMLElement} container
  5567. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  5568. * @param {Object} [options] See Graph2d.setOptions for the available options.
  5569. * @constructor
  5570. */
  5571. function Graph2d (container, items, options, groups) {
  5572. for (var coreProp in Core.prototype) {
  5573. if (Core.prototype.hasOwnProperty(coreProp) && !Graph2d.prototype.hasOwnProperty(coreProp)) {
  5574. Graph2d.prototype[coreProp] = Core.prototype[coreProp];
  5575. }
  5576. }
  5577. var me = this;
  5578. this.defaultOptions = {
  5579. start: null,
  5580. end: null,
  5581. autoResize: true,
  5582. orientation: 'bottom',
  5583. width: null,
  5584. height: null,
  5585. maxHeight: null,
  5586. minHeight: null
  5587. };
  5588. this.options = util.deepExtend({}, this.defaultOptions);
  5589. // Create the DOM, props, and emitter
  5590. this._create(container);
  5591. // all components listed here will be repainted automatically
  5592. this.components = [];
  5593. this.body = {
  5594. dom: this.dom,
  5595. domProps: this.props,
  5596. emitter: {
  5597. on: this.on.bind(this),
  5598. off: this.off.bind(this),
  5599. emit: this.emit.bind(this)
  5600. },
  5601. util: {
  5602. snap: null, // will be specified after TimeAxis is created
  5603. toScreen: me._toScreen.bind(me),
  5604. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  5605. toTime: me._toTime.bind(me),
  5606. toGlobalTime : me._toGlobalTime.bind(me)
  5607. }
  5608. };
  5609. // range
  5610. this.range = new Range(this.body);
  5611. this.components.push(this.range);
  5612. this.body.range = this.range;
  5613. // time axis
  5614. this.timeAxis = new TimeAxis(this.body);
  5615. this.components.push(this.timeAxis);
  5616. this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  5617. // current time bar
  5618. this.currentTime = new CurrentTime(this.body);
  5619. this.components.push(this.currentTime);
  5620. // custom time bar
  5621. // Note: time bar will be attached in this.setOptions when selected
  5622. this.customTime = new CustomTime(this.body);
  5623. this.components.push(this.customTime);
  5624. // item set
  5625. this.linegraph = new LineGraph(this.body);
  5626. this.components.push(this.linegraph);
  5627. this.itemsData = null; // DataSet
  5628. this.groupsData = null; // DataSet
  5629. // apply options
  5630. if (options) {
  5631. this.setOptions(options);
  5632. }
  5633. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  5634. if (groups) {
  5635. this.setGroups(groups);
  5636. }
  5637. // create itemset
  5638. if (items) {
  5639. this.setItems(items);
  5640. }
  5641. else {
  5642. this.redraw();
  5643. }
  5644. }
  5645. /**
  5646. * Set options. Options will be passed to all components loaded in the Graph2d.
  5647. * @param {Object} [options]
  5648. * {String} orientation
  5649. * Vertical orientation for the Graph2d,
  5650. * can be 'bottom' (default) or 'top'.
  5651. * {String | Number} width
  5652. * Width for the timeline, a number in pixels or
  5653. * a css string like '1000px' or '75%'. '100%' by default.
  5654. * {String | Number} height
  5655. * Fixed height for the Graph2d, a number in pixels or
  5656. * a css string like '400px' or '75%'. If undefined,
  5657. * The Graph2d will automatically size such that
  5658. * its contents fit.
  5659. * {String | Number} minHeight
  5660. * Minimum height for the Graph2d, a number in pixels or
  5661. * a css string like '400px' or '75%'.
  5662. * {String | Number} maxHeight
  5663. * Maximum height for the Graph2d, a number in pixels or
  5664. * a css string like '400px' or '75%'.
  5665. * {Number | Date | String} start
  5666. * Start date for the visible window
  5667. * {Number | Date | String} end
  5668. * End date for the visible window
  5669. */
  5670. Graph2d.prototype.setOptions = function (options) {
  5671. if (options) {
  5672. // copy the known options
  5673. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation'];
  5674. util.selectiveExtend(fields, this.options, options);
  5675. // enable/disable autoResize
  5676. this._initAutoResize();
  5677. }
  5678. // propagate options to all components
  5679. this.components.forEach(function (component) {
  5680. component.setOptions(options);
  5681. });
  5682. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  5683. if (options && options.order) {
  5684. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  5685. }
  5686. // redraw everything
  5687. this.redraw();
  5688. };
  5689. /**
  5690. * Set items
  5691. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  5692. */
  5693. Graph2d.prototype.setItems = function(items) {
  5694. var initialLoad = (this.itemsData == null);
  5695. // convert to type DataSet when needed
  5696. var newDataSet;
  5697. if (!items) {
  5698. newDataSet = null;
  5699. }
  5700. else if (items instanceof DataSet || items instanceof DataView) {
  5701. newDataSet = items;
  5702. }
  5703. else {
  5704. // turn an array into a dataset
  5705. newDataSet = new DataSet(items, {
  5706. type: {
  5707. start: 'Date',
  5708. end: 'Date'
  5709. }
  5710. });
  5711. }
  5712. // set items
  5713. this.itemsData = newDataSet;
  5714. this.linegraph && this.linegraph.setItems(newDataSet);
  5715. if (initialLoad && ('start' in this.options || 'end' in this.options)) {
  5716. this.fit();
  5717. var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null;
  5718. var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null;
  5719. this.setWindow(start, end);
  5720. }
  5721. };
  5722. /**
  5723. * Set groups
  5724. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  5725. */
  5726. Graph2d.prototype.setGroups = function(groups) {
  5727. // convert to type DataSet when needed
  5728. var newDataSet;
  5729. if (!groups) {
  5730. newDataSet = null;
  5731. }
  5732. else if (groups instanceof DataSet || groups instanceof DataView) {
  5733. newDataSet = groups;
  5734. }
  5735. else {
  5736. // turn an array into a dataset
  5737. newDataSet = new DataSet(groups);
  5738. }
  5739. this.groupsData = newDataSet;
  5740. this.linegraph.setGroups(newDataSet);
  5741. };
  5742. /**
  5743. * 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).
  5744. * @param groupId
  5745. * @param width
  5746. * @param height
  5747. */
  5748. Graph2d.prototype.getLegend = function(groupId, width, height) {
  5749. if (width === undefined) {width = 15;}
  5750. if (height === undefined) {height = 15;}
  5751. if (this.linegraph.groups[groupId] !== undefined) {
  5752. return this.linegraph.groups[groupId].getLegend(width,height);
  5753. }
  5754. else {
  5755. return "cannot find group:" + groupId;
  5756. }
  5757. }
  5758. /**
  5759. * This checks if the visible option of the supplied group (by ID) is true or false.
  5760. * @param groupId
  5761. * @returns {*}
  5762. */
  5763. Graph2d.prototype.isGroupVisible = function(groupId) {
  5764. if (this.linegraph.groups[groupId] !== undefined) {
  5765. return this.linegraph.groups[groupId].visible;
  5766. }
  5767. else {
  5768. return false;
  5769. }
  5770. }
  5771. /**
  5772. * Get the data range of the item set.
  5773. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  5774. * When no minimum is found, min==null
  5775. * When no maximum is found, max==null
  5776. */
  5777. Graph2d.prototype.getItemRange = function() {
  5778. var min = null;
  5779. var max = null;
  5780. // calculate min from start filed
  5781. for (var groupId in this.linegraph.groups) {
  5782. if (this.linegraph.groups.hasOwnProperty(groupId)) {
  5783. if (this.linegraph.groups[groupId].visible == true) {
  5784. for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
  5785. var item = this.linegraph.groups[groupId].itemsData[i];
  5786. var value = util.convert(item.x, 'Date').valueOf();
  5787. min = min == null ? value : min > value ? value : min;
  5788. max = max == null ? value : max < value ? value : max;
  5789. }
  5790. }
  5791. }
  5792. }
  5793. return {
  5794. min: (min != null) ? new Date(min) : null,
  5795. max: (max != null) ? new Date(max) : null
  5796. };
  5797. };
  5798. module.exports = Graph2d;
  5799. /***/ },
  5800. /* 14 */
  5801. /***/ function(module, exports, __webpack_require__) {
  5802. /**
  5803. * @constructor DataStep
  5804. * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
  5805. * end data point. The class itself determines the best scale (step size) based on the
  5806. * provided start Date, end Date, and minimumStep.
  5807. *
  5808. * If minimumStep is provided, the step size is chosen as close as possible
  5809. * to the minimumStep but larger than minimumStep. If minimumStep is not
  5810. * provided, the scale is set to 1 DAY.
  5811. * The minimumStep should correspond with the onscreen size of about 6 characters
  5812. *
  5813. * Alternatively, you can set a scale by hand.
  5814. * After creation, you can initialize the class by executing first(). Then you
  5815. * can iterate from the start date to the end date via next(). You can check if
  5816. * the end date is reached with the function hasNext(). After each step, you can
  5817. * retrieve the current date via getCurrent().
  5818. * The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
  5819. * days, to years.
  5820. *
  5821. * Version: 1.2
  5822. *
  5823. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  5824. * or new Date(2010, 9, 21, 23, 45, 00)
  5825. * @param {Date} [end] The end date
  5826. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  5827. */
  5828. function DataStep(start, end, minimumStep, containerHeight, forcedStepSize) {
  5829. // variables
  5830. this.current = 0;
  5831. this.autoScale = true;
  5832. this.stepIndex = 0;
  5833. this.step = 1;
  5834. this.scale = 1;
  5835. this.marginStart;
  5836. this.marginEnd;
  5837. this.majorSteps = [1, 2, 5, 10];
  5838. this.minorSteps = [0.25, 0.5, 1, 2];
  5839. this.setRange(start, end, minimumStep, containerHeight, forcedStepSize);
  5840. }
  5841. /**
  5842. * Set a new range
  5843. * If minimumStep is provided, the step size is chosen as close as possible
  5844. * to the minimumStep but larger than minimumStep. If minimumStep is not
  5845. * provided, the scale is set to 1 DAY.
  5846. * The minimumStep should correspond with the onscreen size of about 6 characters
  5847. * @param {Number} [start] The start date and time.
  5848. * @param {Number} [end] The end date and time.
  5849. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  5850. */
  5851. DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, forcedStepSize) {
  5852. this._start = start;
  5853. this._end = end;
  5854. if (start == end) {
  5855. this._start = start - 0.75;
  5856. this._end = end + 1;
  5857. }
  5858. if (this.autoScale) {
  5859. this.setMinimumStep(minimumStep, containerHeight, forcedStepSize);
  5860. }
  5861. this.setFirst();
  5862. };
  5863. /**
  5864. * Automatically determine the scale that bests fits the provided minimum step
  5865. * @param {Number} [minimumStep] The minimum step size in milliseconds
  5866. */
  5867. DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
  5868. // round to floor
  5869. var size = this._end - this._start;
  5870. var safeSize = size * 1.1;
  5871. var minimumStepValue = minimumStep * (safeSize / containerHeight);
  5872. var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
  5873. var minorStepIdx = -1;
  5874. var magnitudefactor = Math.pow(10,orderOfMagnitude);
  5875. var start = 0;
  5876. if (orderOfMagnitude < 0) {
  5877. start = orderOfMagnitude;
  5878. }
  5879. var solutionFound = false;
  5880. for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) {
  5881. magnitudefactor = Math.pow(10,i);
  5882. for (var j = 0; j < this.minorSteps.length; j++) {
  5883. var stepSize = magnitudefactor * this.minorSteps[j];
  5884. if (stepSize >= minimumStepValue) {
  5885. solutionFound = true;
  5886. minorStepIdx = j;
  5887. break;
  5888. }
  5889. }
  5890. if (solutionFound == true) {
  5891. break;
  5892. }
  5893. }
  5894. this.stepIndex = minorStepIdx;
  5895. this.scale = magnitudefactor;
  5896. this.step = magnitudefactor * this.minorSteps[minorStepIdx];
  5897. };
  5898. /**
  5899. * Set the range iterator to the start date.
  5900. */
  5901. DataStep.prototype.first = function() {
  5902. this.setFirst();
  5903. };
  5904. /**
  5905. * Round the current date to the first minor date value
  5906. * This must be executed once when the current date is set to start Date
  5907. */
  5908. DataStep.prototype.setFirst = function() {
  5909. var niceStart = this._start - (this.scale * this.minorSteps[this.stepIndex]);
  5910. var niceEnd = this._end + (this.scale * this.minorSteps[this.stepIndex]);
  5911. this.marginEnd = this.roundToMinor(niceEnd);
  5912. this.marginStart = this.roundToMinor(niceStart);
  5913. this.marginRange = this.marginEnd - this.marginStart;
  5914. this.current = this.marginEnd;
  5915. };
  5916. DataStep.prototype.roundToMinor = function(value) {
  5917. var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
  5918. if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
  5919. return rounded + (this.scale * this.minorSteps[this.stepIndex]);
  5920. }
  5921. else {
  5922. return rounded;
  5923. }
  5924. }
  5925. /**
  5926. * Check if the there is a next step
  5927. * @return {boolean} true if the current date has not passed the end date
  5928. */
  5929. DataStep.prototype.hasNext = function () {
  5930. return (this.current >= this.marginStart);
  5931. };
  5932. /**
  5933. * Do the next step
  5934. */
  5935. DataStep.prototype.next = function() {
  5936. var prev = this.current;
  5937. this.current -= this.step;
  5938. // safety mechanism: if current time is still unchanged, move to the end
  5939. if (this.current == prev) {
  5940. this.current = this._end;
  5941. }
  5942. };
  5943. /**
  5944. * Do the next step
  5945. */
  5946. DataStep.prototype.previous = function() {
  5947. this.current += this.step;
  5948. this.marginEnd += this.step;
  5949. this.marginRange = this.marginEnd - this.marginStart;
  5950. };
  5951. /**
  5952. * Get the current datetime
  5953. * @return {String} current The current date
  5954. */
  5955. DataStep.prototype.getCurrent = function() {
  5956. var toPrecision = '' + Number(this.current).toPrecision(5);
  5957. for (var i = toPrecision.length-1; i > 0; i--) {
  5958. if (toPrecision[i] == "0") {
  5959. toPrecision = toPrecision.slice(0,i);
  5960. }
  5961. else if (toPrecision[i] == "." || toPrecision[i] == ",") {
  5962. toPrecision = toPrecision.slice(0,i);
  5963. break;
  5964. }
  5965. else{
  5966. break;
  5967. }
  5968. }
  5969. return toPrecision;
  5970. };
  5971. /**
  5972. * Snap a date to a rounded value.
  5973. * The snap intervals are dependent on the current scale and step.
  5974. * @param {Date} date the date to be snapped.
  5975. * @return {Date} snappedDate
  5976. */
  5977. DataStep.prototype.snap = function(date) {
  5978. };
  5979. /**
  5980. * Check if the current value is a major value (for example when the step
  5981. * is DAY, a major value is each first day of the MONTH)
  5982. * @return {boolean} true if current date is major, else false.
  5983. */
  5984. DataStep.prototype.isMajor = function() {
  5985. return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
  5986. };
  5987. module.exports = DataStep;
  5988. /***/ },
  5989. /* 15 */
  5990. /***/ function(module, exports, __webpack_require__) {
  5991. var util = __webpack_require__(1);
  5992. var hammerUtil = __webpack_require__(43);
  5993. var moment = __webpack_require__(40);
  5994. var Component = __webpack_require__(18);
  5995. /**
  5996. * @constructor Range
  5997. * A Range controls a numeric range with a start and end value.
  5998. * The Range adjusts the range based on mouse events or programmatic changes,
  5999. * and triggers events when the range is changing or has been changed.
  6000. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  6001. * @param {Object} [options] See description at Range.setOptions
  6002. */
  6003. function Range(body, options) {
  6004. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6005. this.start = now.clone().add('days', -3).valueOf(); // Number
  6006. this.end = now.clone().add('days', 4).valueOf(); // Number
  6007. this.body = body;
  6008. // default options
  6009. this.defaultOptions = {
  6010. start: null,
  6011. end: null,
  6012. direction: 'horizontal', // 'horizontal' or 'vertical'
  6013. moveable: true,
  6014. zoomable: true,
  6015. min: null,
  6016. max: null,
  6017. zoomMin: 10, // milliseconds
  6018. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
  6019. };
  6020. this.options = util.extend({}, this.defaultOptions);
  6021. this.props = {
  6022. touch: {}
  6023. };
  6024. // drag listeners for dragging
  6025. this.body.emitter.on('dragstart', this._onDragStart.bind(this));
  6026. this.body.emitter.on('drag', this._onDrag.bind(this));
  6027. this.body.emitter.on('dragend', this._onDragEnd.bind(this));
  6028. // ignore dragging when holding
  6029. this.body.emitter.on('hold', this._onHold.bind(this));
  6030. // mouse wheel for zooming
  6031. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  6032. this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  6033. // pinch to zoom
  6034. this.body.emitter.on('touch', this._onTouch.bind(this));
  6035. this.body.emitter.on('pinch', this._onPinch.bind(this));
  6036. this.setOptions(options);
  6037. }
  6038. Range.prototype = new Component();
  6039. /**
  6040. * Set options for the range controller
  6041. * @param {Object} options Available options:
  6042. * {Number | Date | String} start Start date for the range
  6043. * {Number | Date | String} end End date for the range
  6044. * {Number} min Minimum value for start
  6045. * {Number} max Maximum value for end
  6046. * {Number} zoomMin Set a minimum value for
  6047. * (end - start).
  6048. * {Number} zoomMax Set a maximum value for
  6049. * (end - start).
  6050. * {Boolean} moveable Enable moving of the range
  6051. * by dragging. True by default
  6052. * {Boolean} zoomable Enable zooming of the range
  6053. * by pinching/scrolling. True by default
  6054. */
  6055. Range.prototype.setOptions = function (options) {
  6056. if (options) {
  6057. // copy the options that we know
  6058. var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable'];
  6059. util.selectiveExtend(fields, this.options, options);
  6060. if ('start' in options || 'end' in options) {
  6061. // apply a new range. both start and end are optional
  6062. this.setRange(options.start, options.end);
  6063. }
  6064. }
  6065. };
  6066. /**
  6067. * Test whether direction has a valid value
  6068. * @param {String} direction 'horizontal' or 'vertical'
  6069. */
  6070. function validateDirection (direction) {
  6071. if (direction != 'horizontal' && direction != 'vertical') {
  6072. throw new TypeError('Unknown direction "' + direction + '". ' +
  6073. 'Choose "horizontal" or "vertical".');
  6074. }
  6075. }
  6076. /**
  6077. * Set a new start and end range
  6078. * @param {Number} [start]
  6079. * @param {Number} [end]
  6080. */
  6081. Range.prototype.setRange = function(start, end) {
  6082. var changed = this._applyRange(start, end);
  6083. if (changed) {
  6084. var params = {
  6085. start: new Date(this.start),
  6086. end: new Date(this.end)
  6087. };
  6088. this.body.emitter.emit('rangechange', params);
  6089. this.body.emitter.emit('rangechanged', params);
  6090. }
  6091. };
  6092. /**
  6093. * Set a new start and end range. This method is the same as setRange, but
  6094. * does not trigger a range change and range changed event, and it returns
  6095. * true when the range is changed
  6096. * @param {Number} [start]
  6097. * @param {Number} [end]
  6098. * @return {Boolean} changed
  6099. * @private
  6100. */
  6101. Range.prototype._applyRange = function(start, end) {
  6102. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  6103. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  6104. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  6105. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  6106. diff;
  6107. // check for valid number
  6108. if (isNaN(newStart) || newStart === null) {
  6109. throw new Error('Invalid start "' + start + '"');
  6110. }
  6111. if (isNaN(newEnd) || newEnd === null) {
  6112. throw new Error('Invalid end "' + end + '"');
  6113. }
  6114. // prevent start < end
  6115. if (newEnd < newStart) {
  6116. newEnd = newStart;
  6117. }
  6118. // prevent start < min
  6119. if (min !== null) {
  6120. if (newStart < min) {
  6121. diff = (min - newStart);
  6122. newStart += diff;
  6123. newEnd += diff;
  6124. // prevent end > max
  6125. if (max != null) {
  6126. if (newEnd > max) {
  6127. newEnd = max;
  6128. }
  6129. }
  6130. }
  6131. }
  6132. // prevent end > max
  6133. if (max !== null) {
  6134. if (newEnd > max) {
  6135. diff = (newEnd - max);
  6136. newStart -= diff;
  6137. newEnd -= diff;
  6138. // prevent start < min
  6139. if (min != null) {
  6140. if (newStart < min) {
  6141. newStart = min;
  6142. }
  6143. }
  6144. }
  6145. }
  6146. // prevent (end-start) < zoomMin
  6147. if (this.options.zoomMin !== null) {
  6148. var zoomMin = parseFloat(this.options.zoomMin);
  6149. if (zoomMin < 0) {
  6150. zoomMin = 0;
  6151. }
  6152. if ((newEnd - newStart) < zoomMin) {
  6153. if ((this.end - this.start) === zoomMin) {
  6154. // ignore this action, we are already zoomed to the minimum
  6155. newStart = this.start;
  6156. newEnd = this.end;
  6157. }
  6158. else {
  6159. // zoom to the minimum
  6160. diff = (zoomMin - (newEnd - newStart));
  6161. newStart -= diff / 2;
  6162. newEnd += diff / 2;
  6163. }
  6164. }
  6165. }
  6166. // prevent (end-start) > zoomMax
  6167. if (this.options.zoomMax !== null) {
  6168. var zoomMax = parseFloat(this.options.zoomMax);
  6169. if (zoomMax < 0) {
  6170. zoomMax = 0;
  6171. }
  6172. if ((newEnd - newStart) > zoomMax) {
  6173. if ((this.end - this.start) === zoomMax) {
  6174. // ignore this action, we are already zoomed to the maximum
  6175. newStart = this.start;
  6176. newEnd = this.end;
  6177. }
  6178. else {
  6179. // zoom to the maximum
  6180. diff = ((newEnd - newStart) - zoomMax);
  6181. newStart += diff / 2;
  6182. newEnd -= diff / 2;
  6183. }
  6184. }
  6185. }
  6186. var changed = (this.start != newStart || this.end != newEnd);
  6187. this.start = newStart;
  6188. this.end = newEnd;
  6189. return changed;
  6190. };
  6191. /**
  6192. * Retrieve the current range.
  6193. * @return {Object} An object with start and end properties
  6194. */
  6195. Range.prototype.getRange = function() {
  6196. return {
  6197. start: this.start,
  6198. end: this.end
  6199. };
  6200. };
  6201. /**
  6202. * Calculate the conversion offset and scale for current range, based on
  6203. * the provided width
  6204. * @param {Number} width
  6205. * @returns {{offset: number, scale: number}} conversion
  6206. */
  6207. Range.prototype.conversion = function (width) {
  6208. return Range.conversion(this.start, this.end, width);
  6209. };
  6210. /**
  6211. * Static method to calculate the conversion offset and scale for a range,
  6212. * based on the provided start, end, and width
  6213. * @param {Number} start
  6214. * @param {Number} end
  6215. * @param {Number} width
  6216. * @returns {{offset: number, scale: number}} conversion
  6217. */
  6218. Range.conversion = function (start, end, width) {
  6219. if (width != 0 && (end - start != 0)) {
  6220. return {
  6221. offset: start,
  6222. scale: width / (end - start)
  6223. }
  6224. }
  6225. else {
  6226. return {
  6227. offset: 0,
  6228. scale: 1
  6229. };
  6230. }
  6231. };
  6232. /**
  6233. * Start dragging horizontally or vertically
  6234. * @param {Event} event
  6235. * @private
  6236. */
  6237. Range.prototype._onDragStart = function(event) {
  6238. // only allow dragging when configured as movable
  6239. if (!this.options.moveable) return;
  6240. // refuse to drag when we where pinching to prevent the timeline make a jump
  6241. // when releasing the fingers in opposite order from the touch screen
  6242. if (!this.props.touch.allowDragging) return;
  6243. this.props.touch.start = this.start;
  6244. this.props.touch.end = this.end;
  6245. if (this.body.dom.root) {
  6246. this.body.dom.root.style.cursor = 'move';
  6247. }
  6248. };
  6249. /**
  6250. * Perform dragging operation
  6251. * @param {Event} event
  6252. * @private
  6253. */
  6254. Range.prototype._onDrag = function (event) {
  6255. // only allow dragging when configured as movable
  6256. if (!this.options.moveable) return;
  6257. var direction = this.options.direction;
  6258. validateDirection(direction);
  6259. // refuse to drag when we where pinching to prevent the timeline make a jump
  6260. // when releasing the fingers in opposite order from the touch screen
  6261. if (!this.props.touch.allowDragging) return;
  6262. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  6263. interval = (this.props.touch.end - this.props.touch.start),
  6264. width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height,
  6265. diffRange = -delta / width * interval;
  6266. this._applyRange(this.props.touch.start + diffRange, this.props.touch.end + diffRange);
  6267. this.body.emitter.emit('rangechange', {
  6268. start: new Date(this.start),
  6269. end: new Date(this.end)
  6270. });
  6271. };
  6272. /**
  6273. * Stop dragging operation
  6274. * @param {event} event
  6275. * @private
  6276. */
  6277. Range.prototype._onDragEnd = function (event) {
  6278. // only allow dragging when configured as movable
  6279. if (!this.options.moveable) return;
  6280. // refuse to drag when we where pinching to prevent the timeline make a jump
  6281. // when releasing the fingers in opposite order from the touch screen
  6282. if (!this.props.touch.allowDragging) return;
  6283. if (this.body.dom.root) {
  6284. this.body.dom.root.style.cursor = 'auto';
  6285. }
  6286. // fire a rangechanged event
  6287. this.body.emitter.emit('rangechanged', {
  6288. start: new Date(this.start),
  6289. end: new Date(this.end)
  6290. });
  6291. };
  6292. /**
  6293. * Event handler for mouse wheel event, used to zoom
  6294. * Code from http://adomas.org/javascript-mouse-wheel/
  6295. * @param {Event} event
  6296. * @private
  6297. */
  6298. Range.prototype._onMouseWheel = function(event) {
  6299. // only allow zooming when configured as zoomable and moveable
  6300. if (!(this.options.zoomable && this.options.moveable)) return;
  6301. // retrieve delta
  6302. var delta = 0;
  6303. if (event.wheelDelta) { /* IE/Opera. */
  6304. delta = event.wheelDelta / 120;
  6305. } else if (event.detail) { /* Mozilla case. */
  6306. // In Mozilla, sign of delta is different than in IE.
  6307. // Also, delta is multiple of 3.
  6308. delta = -event.detail / 3;
  6309. }
  6310. // If delta is nonzero, handle it.
  6311. // Basically, delta is now positive if wheel was scrolled up,
  6312. // and negative, if wheel was scrolled down.
  6313. if (delta) {
  6314. // perform the zoom action. Delta is normally 1 or -1
  6315. // adjust a negative delta such that zooming in with delta 0.1
  6316. // equals zooming out with a delta -0.1
  6317. var scale;
  6318. if (delta < 0) {
  6319. scale = 1 - (delta / 5);
  6320. }
  6321. else {
  6322. scale = 1 / (1 + (delta / 5)) ;
  6323. }
  6324. // calculate center, the date to zoom around
  6325. var gesture = hammerUtil.fakeGesture(this, event),
  6326. pointer = getPointer(gesture.center, this.body.dom.center),
  6327. pointerDate = this._pointerToDate(pointer);
  6328. this.zoom(scale, pointerDate);
  6329. }
  6330. // Prevent default actions caused by mouse wheel
  6331. // (else the page and timeline both zoom and scroll)
  6332. event.preventDefault();
  6333. };
  6334. /**
  6335. * Start of a touch gesture
  6336. * @private
  6337. */
  6338. Range.prototype._onTouch = function (event) {
  6339. this.props.touch.start = this.start;
  6340. this.props.touch.end = this.end;
  6341. this.props.touch.allowDragging = true;
  6342. this.props.touch.center = null;
  6343. };
  6344. /**
  6345. * On start of a hold gesture
  6346. * @private
  6347. */
  6348. Range.prototype._onHold = function () {
  6349. this.props.touch.allowDragging = false;
  6350. };
  6351. /**
  6352. * Handle pinch event
  6353. * @param {Event} event
  6354. * @private
  6355. */
  6356. Range.prototype._onPinch = function (event) {
  6357. // only allow zooming when configured as zoomable and moveable
  6358. if (!(this.options.zoomable && this.options.moveable)) return;
  6359. this.props.touch.allowDragging = false;
  6360. if (event.gesture.touches.length > 1) {
  6361. if (!this.props.touch.center) {
  6362. this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center);
  6363. }
  6364. var scale = 1 / event.gesture.scale,
  6365. initDate = this._pointerToDate(this.props.touch.center);
  6366. // calculate new start and end
  6367. var newStart = parseInt(initDate + (this.props.touch.start - initDate) * scale);
  6368. var newEnd = parseInt(initDate + (this.props.touch.end - initDate) * scale);
  6369. // apply new range
  6370. this.setRange(newStart, newEnd);
  6371. }
  6372. };
  6373. /**
  6374. * Helper function to calculate the center date for zooming
  6375. * @param {{x: Number, y: Number}} pointer
  6376. * @return {number} date
  6377. * @private
  6378. */
  6379. Range.prototype._pointerToDate = function (pointer) {
  6380. var conversion;
  6381. var direction = this.options.direction;
  6382. validateDirection(direction);
  6383. if (direction == 'horizontal') {
  6384. var width = this.body.domProps.center.width;
  6385. conversion = this.conversion(width);
  6386. return pointer.x / conversion.scale + conversion.offset;
  6387. }
  6388. else {
  6389. var height = this.body.domProps.center.height;
  6390. conversion = this.conversion(height);
  6391. return pointer.y / conversion.scale + conversion.offset;
  6392. }
  6393. };
  6394. /**
  6395. * Get the pointer location relative to the location of the dom element
  6396. * @param {{pageX: Number, pageY: Number}} touch
  6397. * @param {Element} element HTML DOM element
  6398. * @return {{x: Number, y: Number}} pointer
  6399. * @private
  6400. */
  6401. function getPointer (touch, element) {
  6402. return {
  6403. x: touch.pageX - util.getAbsoluteLeft(element),
  6404. y: touch.pageY - util.getAbsoluteTop(element)
  6405. };
  6406. }
  6407. /**
  6408. * Zoom the range the given scale in or out. Start and end date will
  6409. * be adjusted, and the timeline will be redrawn. You can optionally give a
  6410. * date around which to zoom.
  6411. * For example, try scale = 0.9 or 1.1
  6412. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  6413. * values below 1 will zoom in.
  6414. * @param {Number} [center] Value representing a date around which will
  6415. * be zoomed.
  6416. */
  6417. Range.prototype.zoom = function(scale, center) {
  6418. // if centerDate is not provided, take it half between start Date and end Date
  6419. if (center == null) {
  6420. center = (this.start + this.end) / 2;
  6421. }
  6422. // calculate new start and end
  6423. var newStart = center + (this.start - center) * scale;
  6424. var newEnd = center + (this.end - center) * scale;
  6425. this.setRange(newStart, newEnd);
  6426. };
  6427. /**
  6428. * Move the range with a given delta to the left or right. Start and end
  6429. * value will be adjusted. For example, try delta = 0.1 or -0.1
  6430. * @param {Number} delta Moving amount. Positive value will move right,
  6431. * negative value will move left
  6432. */
  6433. Range.prototype.move = function(delta) {
  6434. // zoom start Date and end Date relative to the centerDate
  6435. var diff = (this.end - this.start);
  6436. // apply new values
  6437. var newStart = this.start + diff * delta;
  6438. var newEnd = this.end + diff * delta;
  6439. // TODO: reckon with min and max range
  6440. this.start = newStart;
  6441. this.end = newEnd;
  6442. };
  6443. /**
  6444. * Move the range to a new center point
  6445. * @param {Number} moveTo New center point of the range
  6446. */
  6447. Range.prototype.moveTo = function(moveTo) {
  6448. var center = (this.start + this.end) / 2;
  6449. var diff = center - moveTo;
  6450. // calculate new start and end
  6451. var newStart = this.start - diff;
  6452. var newEnd = this.end - diff;
  6453. this.setRange(newStart, newEnd);
  6454. };
  6455. module.exports = Range;
  6456. /***/ },
  6457. /* 16 */
  6458. /***/ function(module, exports, __webpack_require__) {
  6459. // Utility functions for ordering and stacking of items
  6460. var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
  6461. /**
  6462. * Order items by their start data
  6463. * @param {Item[]} items
  6464. */
  6465. exports.orderByStart = function(items) {
  6466. items.sort(function (a, b) {
  6467. return a.data.start - b.data.start;
  6468. });
  6469. };
  6470. /**
  6471. * Order items by their end date. If they have no end date, their start date
  6472. * is used.
  6473. * @param {Item[]} items
  6474. */
  6475. exports.orderByEnd = function(items) {
  6476. items.sort(function (a, b) {
  6477. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  6478. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  6479. return aTime - bTime;
  6480. });
  6481. };
  6482. /**
  6483. * Adjust vertical positions of the items such that they don't overlap each
  6484. * other.
  6485. * @param {Item[]} items
  6486. * All visible items
  6487. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  6488. * Margins between items and between items and the axis.
  6489. * @param {boolean} [force=false]
  6490. * If true, all items will be repositioned. If false (default), only
  6491. * items having a top===null will be re-stacked
  6492. */
  6493. exports.stack = function(items, margin, force) {
  6494. var i, iMax;
  6495. if (force) {
  6496. // reset top position of all items
  6497. for (i = 0, iMax = items.length; i < iMax; i++) {
  6498. items[i].top = null;
  6499. }
  6500. }
  6501. // calculate new, non-overlapping positions
  6502. for (i = 0, iMax = items.length; i < iMax; i++) {
  6503. var item = items[i];
  6504. if (item.top === null) {
  6505. // initialize top position
  6506. item.top = margin.axis;
  6507. do {
  6508. // TODO: optimize checking for overlap. when there is a gap without items,
  6509. // you only need to check for items from the next item on, not from zero
  6510. var collidingItem = null;
  6511. for (var j = 0, jj = items.length; j < jj; j++) {
  6512. var other = items[j];
  6513. if (other.top !== null && other !== item && exports.collision(item, other, margin.item)) {
  6514. collidingItem = other;
  6515. break;
  6516. }
  6517. }
  6518. if (collidingItem != null) {
  6519. // There is a collision. Reposition the items above the colliding element
  6520. item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
  6521. }
  6522. } while (collidingItem);
  6523. }
  6524. }
  6525. };
  6526. /**
  6527. * Adjust vertical positions of the items without stacking them
  6528. * @param {Item[]} items
  6529. * All visible items
  6530. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  6531. * Margins between items and between items and the axis.
  6532. */
  6533. exports.nostack = function(items, margin) {
  6534. var i, iMax;
  6535. // reset top position of all items
  6536. for (i = 0, iMax = items.length; i < iMax; i++) {
  6537. items[i].top = margin.axis;
  6538. }
  6539. };
  6540. /**
  6541. * Test if the two provided items collide
  6542. * The items must have parameters left, width, top, and height.
  6543. * @param {Item} a The first item
  6544. * @param {Item} b The second item
  6545. * @param {{horizontal: number, vertical: number}} margin
  6546. * An object containing a horizontal and vertical
  6547. * minimum required margin.
  6548. * @return {boolean} true if a and b collide, else false
  6549. */
  6550. exports.collision = function(a, b, margin) {
  6551. return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) &&
  6552. (a.left + a.width + margin.horizontal - EPSILON) > b.left &&
  6553. (a.top - margin.vertical + EPSILON) < (b.top + b.height) &&
  6554. (a.top + a.height + margin.vertical - EPSILON) > b.top);
  6555. };
  6556. /***/ },
  6557. /* 17 */
  6558. /***/ function(module, exports, __webpack_require__) {
  6559. var moment = __webpack_require__(40);
  6560. /**
  6561. * @constructor TimeStep
  6562. * The class TimeStep is an iterator for dates. You provide a start date and an
  6563. * end date. The class itself determines the best scale (step size) based on the
  6564. * provided start Date, end Date, and minimumStep.
  6565. *
  6566. * If minimumStep is provided, the step size is chosen as close as possible
  6567. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6568. * provided, the scale is set to 1 DAY.
  6569. * The minimumStep should correspond with the onscreen size of about 6 characters
  6570. *
  6571. * Alternatively, you can set a scale by hand.
  6572. * After creation, you can initialize the class by executing first(). Then you
  6573. * can iterate from the start date to the end date via next(). You can check if
  6574. * the end date is reached with the function hasNext(). After each step, you can
  6575. * retrieve the current date via getCurrent().
  6576. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  6577. * days, to years.
  6578. *
  6579. * Version: 1.2
  6580. *
  6581. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  6582. * or new Date(2010, 9, 21, 23, 45, 00)
  6583. * @param {Date} [end] The end date
  6584. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6585. */
  6586. function TimeStep(start, end, minimumStep) {
  6587. // variables
  6588. this.current = new Date();
  6589. this._start = new Date();
  6590. this._end = new Date();
  6591. this.autoScale = true;
  6592. this.scale = TimeStep.SCALE.DAY;
  6593. this.step = 1;
  6594. // initialize the range
  6595. this.setRange(start, end, minimumStep);
  6596. }
  6597. /// enum scale
  6598. TimeStep.SCALE = {
  6599. MILLISECOND: 1,
  6600. SECOND: 2,
  6601. MINUTE: 3,
  6602. HOUR: 4,
  6603. DAY: 5,
  6604. WEEKDAY: 6,
  6605. MONTH: 7,
  6606. YEAR: 8
  6607. };
  6608. /**
  6609. * Set a new range
  6610. * If minimumStep is provided, the step size is chosen as close as possible
  6611. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6612. * provided, the scale is set to 1 DAY.
  6613. * The minimumStep should correspond with the onscreen size of about 6 characters
  6614. * @param {Date} [start] The start date and time.
  6615. * @param {Date} [end] The end date and time.
  6616. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  6617. */
  6618. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  6619. if (!(start instanceof Date) || !(end instanceof Date)) {
  6620. throw "No legal start or end date in method setRange";
  6621. }
  6622. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  6623. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  6624. if (this.autoScale) {
  6625. this.setMinimumStep(minimumStep);
  6626. }
  6627. };
  6628. /**
  6629. * Set the range iterator to the start date.
  6630. */
  6631. TimeStep.prototype.first = function() {
  6632. this.current = new Date(this._start.valueOf());
  6633. this.roundToMinor();
  6634. };
  6635. /**
  6636. * Round the current date to the first minor date value
  6637. * This must be executed once when the current date is set to start Date
  6638. */
  6639. TimeStep.prototype.roundToMinor = function() {
  6640. // round to floor
  6641. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  6642. //noinspection FallthroughInSwitchStatementJS
  6643. switch (this.scale) {
  6644. case TimeStep.SCALE.YEAR:
  6645. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  6646. this.current.setMonth(0);
  6647. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  6648. case TimeStep.SCALE.DAY: // intentional fall through
  6649. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  6650. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  6651. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  6652. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  6653. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  6654. }
  6655. if (this.step != 1) {
  6656. // round down to the first minor value that is a multiple of the current step size
  6657. switch (this.scale) {
  6658. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  6659. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  6660. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  6661. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  6662. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6663. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  6664. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  6665. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  6666. default: break;
  6667. }
  6668. }
  6669. };
  6670. /**
  6671. * Check if the there is a next step
  6672. * @return {boolean} true if the current date has not passed the end date
  6673. */
  6674. TimeStep.prototype.hasNext = function () {
  6675. return (this.current.valueOf() <= this._end.valueOf());
  6676. };
  6677. /**
  6678. * Do the next step
  6679. */
  6680. TimeStep.prototype.next = function() {
  6681. var prev = this.current.valueOf();
  6682. // Two cases, needed to prevent issues with switching daylight savings
  6683. // (end of March and end of October)
  6684. if (this.current.getMonth() < 6) {
  6685. switch (this.scale) {
  6686. case TimeStep.SCALE.MILLISECOND:
  6687. this.current = new Date(this.current.valueOf() + this.step); break;
  6688. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  6689. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  6690. case TimeStep.SCALE.HOUR:
  6691. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  6692. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  6693. var h = this.current.getHours();
  6694. this.current.setHours(h - (h % this.step));
  6695. break;
  6696. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6697. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  6698. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  6699. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  6700. default: break;
  6701. }
  6702. }
  6703. else {
  6704. switch (this.scale) {
  6705. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  6706. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  6707. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  6708. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  6709. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6710. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  6711. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  6712. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  6713. default: break;
  6714. }
  6715. }
  6716. if (this.step != 1) {
  6717. // round down to the correct major value
  6718. switch (this.scale) {
  6719. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  6720. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  6721. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  6722. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  6723. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6724. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  6725. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  6726. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  6727. default: break;
  6728. }
  6729. }
  6730. // safety mechanism: if current time is still unchanged, move to the end
  6731. if (this.current.valueOf() == prev) {
  6732. this.current = new Date(this._end.valueOf());
  6733. }
  6734. };
  6735. /**
  6736. * Get the current datetime
  6737. * @return {Date} current The current date
  6738. */
  6739. TimeStep.prototype.getCurrent = function() {
  6740. return this.current;
  6741. };
  6742. /**
  6743. * Set a custom scale. Autoscaling will be disabled.
  6744. * For example setScale(SCALE.MINUTES, 5) will result
  6745. * in minor steps of 5 minutes, and major steps of an hour.
  6746. *
  6747. * @param {TimeStep.SCALE} newScale
  6748. * A scale. Choose from SCALE.MILLISECOND,
  6749. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  6750. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  6751. * SCALE.YEAR.
  6752. * @param {Number} newStep A step size, by default 1. Choose for
  6753. * example 1, 2, 5, or 10.
  6754. */
  6755. TimeStep.prototype.setScale = function(newScale, newStep) {
  6756. this.scale = newScale;
  6757. if (newStep > 0) {
  6758. this.step = newStep;
  6759. }
  6760. this.autoScale = false;
  6761. };
  6762. /**
  6763. * Enable or disable autoscaling
  6764. * @param {boolean} enable If true, autoascaling is set true
  6765. */
  6766. TimeStep.prototype.setAutoScale = function (enable) {
  6767. this.autoScale = enable;
  6768. };
  6769. /**
  6770. * Automatically determine the scale that bests fits the provided minimum step
  6771. * @param {Number} [minimumStep] The minimum step size in milliseconds
  6772. */
  6773. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  6774. if (minimumStep == undefined) {
  6775. return;
  6776. }
  6777. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  6778. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  6779. var stepDay = (1000 * 60 * 60 * 24);
  6780. var stepHour = (1000 * 60 * 60);
  6781. var stepMinute = (1000 * 60);
  6782. var stepSecond = (1000);
  6783. var stepMillisecond= (1);
  6784. // find the smallest step that is larger than the provided minimumStep
  6785. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  6786. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  6787. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  6788. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  6789. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  6790. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  6791. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  6792. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  6793. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  6794. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  6795. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  6796. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  6797. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  6798. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  6799. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  6800. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  6801. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  6802. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  6803. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  6804. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  6805. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  6806. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  6807. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  6808. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  6809. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  6810. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  6811. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  6812. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  6813. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  6814. };
  6815. /**
  6816. * Snap a date to a rounded value.
  6817. * The snap intervals are dependent on the current scale and step.
  6818. * @param {Date} date the date to be snapped.
  6819. * @return {Date} snappedDate
  6820. */
  6821. TimeStep.prototype.snap = function(date) {
  6822. var clone = new Date(date.valueOf());
  6823. if (this.scale == TimeStep.SCALE.YEAR) {
  6824. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  6825. clone.setFullYear(Math.round(year / this.step) * this.step);
  6826. clone.setMonth(0);
  6827. clone.setDate(0);
  6828. clone.setHours(0);
  6829. clone.setMinutes(0);
  6830. clone.setSeconds(0);
  6831. clone.setMilliseconds(0);
  6832. }
  6833. else if (this.scale == TimeStep.SCALE.MONTH) {
  6834. if (clone.getDate() > 15) {
  6835. clone.setDate(1);
  6836. clone.setMonth(clone.getMonth() + 1);
  6837. // important: first set Date to 1, after that change the month.
  6838. }
  6839. else {
  6840. clone.setDate(1);
  6841. }
  6842. clone.setHours(0);
  6843. clone.setMinutes(0);
  6844. clone.setSeconds(0);
  6845. clone.setMilliseconds(0);
  6846. }
  6847. else if (this.scale == TimeStep.SCALE.DAY) {
  6848. //noinspection FallthroughInSwitchStatementJS
  6849. switch (this.step) {
  6850. case 5:
  6851. case 2:
  6852. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  6853. default:
  6854. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  6855. }
  6856. clone.setMinutes(0);
  6857. clone.setSeconds(0);
  6858. clone.setMilliseconds(0);
  6859. }
  6860. else if (this.scale == TimeStep.SCALE.WEEKDAY) {
  6861. //noinspection FallthroughInSwitchStatementJS
  6862. switch (this.step) {
  6863. case 5:
  6864. case 2:
  6865. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  6866. default:
  6867. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  6868. }
  6869. clone.setMinutes(0);
  6870. clone.setSeconds(0);
  6871. clone.setMilliseconds(0);
  6872. }
  6873. else if (this.scale == TimeStep.SCALE.HOUR) {
  6874. switch (this.step) {
  6875. case 4:
  6876. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  6877. default:
  6878. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  6879. }
  6880. clone.setSeconds(0);
  6881. clone.setMilliseconds(0);
  6882. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  6883. //noinspection FallthroughInSwitchStatementJS
  6884. switch (this.step) {
  6885. case 15:
  6886. case 10:
  6887. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  6888. clone.setSeconds(0);
  6889. break;
  6890. case 5:
  6891. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  6892. default:
  6893. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  6894. }
  6895. clone.setMilliseconds(0);
  6896. }
  6897. else if (this.scale == TimeStep.SCALE.SECOND) {
  6898. //noinspection FallthroughInSwitchStatementJS
  6899. switch (this.step) {
  6900. case 15:
  6901. case 10:
  6902. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  6903. clone.setMilliseconds(0);
  6904. break;
  6905. case 5:
  6906. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  6907. default:
  6908. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  6909. }
  6910. }
  6911. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  6912. var step = this.step > 5 ? this.step / 2 : 1;
  6913. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  6914. }
  6915. return clone;
  6916. };
  6917. /**
  6918. * Check if the current value is a major value (for example when the step
  6919. * is DAY, a major value is each first day of the MONTH)
  6920. * @return {boolean} true if current date is major, else false.
  6921. */
  6922. TimeStep.prototype.isMajor = function() {
  6923. switch (this.scale) {
  6924. case TimeStep.SCALE.MILLISECOND:
  6925. return (this.current.getMilliseconds() == 0);
  6926. case TimeStep.SCALE.SECOND:
  6927. return (this.current.getSeconds() == 0);
  6928. case TimeStep.SCALE.MINUTE:
  6929. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  6930. // Note: this is no bug. Major label is equal for both minute and hour scale
  6931. case TimeStep.SCALE.HOUR:
  6932. return (this.current.getHours() == 0);
  6933. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6934. case TimeStep.SCALE.DAY:
  6935. return (this.current.getDate() == 1);
  6936. case TimeStep.SCALE.MONTH:
  6937. return (this.current.getMonth() == 0);
  6938. case TimeStep.SCALE.YEAR:
  6939. return false;
  6940. default:
  6941. return false;
  6942. }
  6943. };
  6944. /**
  6945. * Returns formatted text for the minor axislabel, depending on the current
  6946. * date and the scale. For example when scale is MINUTE, the current time is
  6947. * formatted as "hh:mm".
  6948. * @param {Date} [date] custom date. if not provided, current date is taken
  6949. */
  6950. TimeStep.prototype.getLabelMinor = function(date) {
  6951. if (date == undefined) {
  6952. date = this.current;
  6953. }
  6954. switch (this.scale) {
  6955. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  6956. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  6957. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  6958. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  6959. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  6960. case TimeStep.SCALE.DAY: return moment(date).format('D');
  6961. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  6962. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  6963. default: return '';
  6964. }
  6965. };
  6966. /**
  6967. * Returns formatted text for the major axis label, depending on the current
  6968. * date and the scale. For example when scale is MINUTE, the major scale is
  6969. * hours, and the hour will be formatted as "hh".
  6970. * @param {Date} [date] custom date. if not provided, current date is taken
  6971. */
  6972. TimeStep.prototype.getLabelMajor = function(date) {
  6973. if (date == undefined) {
  6974. date = this.current;
  6975. }
  6976. //noinspection FallthroughInSwitchStatementJS
  6977. switch (this.scale) {
  6978. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  6979. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  6980. case TimeStep.SCALE.MINUTE:
  6981. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  6982. case TimeStep.SCALE.WEEKDAY:
  6983. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  6984. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  6985. case TimeStep.SCALE.YEAR: return '';
  6986. default: return '';
  6987. }
  6988. };
  6989. module.exports = TimeStep;
  6990. /***/ },
  6991. /* 18 */
  6992. /***/ function(module, exports, __webpack_require__) {
  6993. /**
  6994. * Prototype for visual components
  6995. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
  6996. * @param {Object} [options]
  6997. */
  6998. function Component (body, options) {
  6999. this.options = null;
  7000. this.props = null;
  7001. }
  7002. /**
  7003. * Set options for the component. The new options will be merged into the
  7004. * current options.
  7005. * @param {Object} options
  7006. */
  7007. Component.prototype.setOptions = function(options) {
  7008. if (options) {
  7009. util.extend(this.options, options);
  7010. }
  7011. };
  7012. /**
  7013. * Repaint the component
  7014. * @return {boolean} Returns true if the component is resized
  7015. */
  7016. Component.prototype.redraw = function() {
  7017. // should be implemented by the component
  7018. return false;
  7019. };
  7020. /**
  7021. * Destroy the component. Cleanup DOM and event listeners
  7022. */
  7023. Component.prototype.destroy = function() {
  7024. // should be implemented by the component
  7025. };
  7026. /**
  7027. * Test whether the component is resized since the last time _isResized() was
  7028. * called.
  7029. * @return {Boolean} Returns true if the component is resized
  7030. * @protected
  7031. */
  7032. Component.prototype._isResized = function() {
  7033. var resized = (this.props._previousWidth !== this.props.width ||
  7034. this.props._previousHeight !== this.props.height);
  7035. this.props._previousWidth = this.props.width;
  7036. this.props._previousHeight = this.props.height;
  7037. return resized;
  7038. };
  7039. module.exports = Component;
  7040. /***/ },
  7041. /* 19 */
  7042. /***/ function(module, exports, __webpack_require__) {
  7043. var util = __webpack_require__(1);
  7044. var Component = __webpack_require__(18);
  7045. /**
  7046. * A current time bar
  7047. * @param {{range: Range, dom: Object, domProps: Object}} body
  7048. * @param {Object} [options] Available parameters:
  7049. * {Boolean} [showCurrentTime]
  7050. * @constructor CurrentTime
  7051. * @extends Component
  7052. */
  7053. function CurrentTime (body, options) {
  7054. this.body = body;
  7055. // default options
  7056. this.defaultOptions = {
  7057. showCurrentTime: true
  7058. };
  7059. this.options = util.extend({}, this.defaultOptions);
  7060. this._create();
  7061. this.setOptions(options);
  7062. }
  7063. CurrentTime.prototype = new Component();
  7064. /**
  7065. * Create the HTML DOM for the current time bar
  7066. * @private
  7067. */
  7068. CurrentTime.prototype._create = function() {
  7069. var bar = document.createElement('div');
  7070. bar.className = 'currenttime';
  7071. bar.style.position = 'absolute';
  7072. bar.style.top = '0px';
  7073. bar.style.height = '100%';
  7074. this.bar = bar;
  7075. };
  7076. /**
  7077. * Destroy the CurrentTime bar
  7078. */
  7079. CurrentTime.prototype.destroy = function () {
  7080. this.options.showCurrentTime = false;
  7081. this.redraw(); // will remove the bar from the DOM and stop refreshing
  7082. this.body = null;
  7083. };
  7084. /**
  7085. * Set options for the component. Options will be merged in current options.
  7086. * @param {Object} options Available parameters:
  7087. * {boolean} [showCurrentTime]
  7088. */
  7089. CurrentTime.prototype.setOptions = function(options) {
  7090. if (options) {
  7091. // copy all options that we know
  7092. util.selectiveExtend(['showCurrentTime'], this.options, options);
  7093. }
  7094. };
  7095. /**
  7096. * Repaint the component
  7097. * @return {boolean} Returns true if the component is resized
  7098. */
  7099. CurrentTime.prototype.redraw = function() {
  7100. if (this.options.showCurrentTime) {
  7101. var parent = this.body.dom.backgroundVertical;
  7102. if (this.bar.parentNode != parent) {
  7103. // attach to the dom
  7104. if (this.bar.parentNode) {
  7105. this.bar.parentNode.removeChild(this.bar);
  7106. }
  7107. parent.appendChild(this.bar);
  7108. this.start();
  7109. }
  7110. var now = new Date();
  7111. var x = this.body.util.toScreen(now);
  7112. this.bar.style.left = x + 'px';
  7113. this.bar.title = 'Current time: ' + now;
  7114. }
  7115. else {
  7116. // remove the line from the DOM
  7117. if (this.bar.parentNode) {
  7118. this.bar.parentNode.removeChild(this.bar);
  7119. }
  7120. this.stop();
  7121. }
  7122. return false;
  7123. };
  7124. /**
  7125. * Start auto refreshing the current time bar
  7126. */
  7127. CurrentTime.prototype.start = function() {
  7128. var me = this;
  7129. function update () {
  7130. me.stop();
  7131. // determine interval to refresh
  7132. var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
  7133. var interval = 1 / scale / 10;
  7134. if (interval < 30) interval = 30;
  7135. if (interval > 1000) interval = 1000;
  7136. me.redraw();
  7137. // start a timer to adjust for the new time
  7138. me.currentTimeTimer = setTimeout(update, interval);
  7139. }
  7140. update();
  7141. };
  7142. /**
  7143. * Stop auto refreshing the current time bar
  7144. */
  7145. CurrentTime.prototype.stop = function() {
  7146. if (this.currentTimeTimer !== undefined) {
  7147. clearTimeout(this.currentTimeTimer);
  7148. delete this.currentTimeTimer;
  7149. }
  7150. };
  7151. module.exports = CurrentTime;
  7152. /***/ },
  7153. /* 20 */
  7154. /***/ function(module, exports, __webpack_require__) {
  7155. var Hammer = __webpack_require__(41);
  7156. var util = __webpack_require__(1);
  7157. var Component = __webpack_require__(18);
  7158. /**
  7159. * A custom time bar
  7160. * @param {{range: Range, dom: Object}} body
  7161. * @param {Object} [options] Available parameters:
  7162. * {Boolean} [showCustomTime]
  7163. * @constructor CustomTime
  7164. * @extends Component
  7165. */
  7166. function CustomTime (body, options) {
  7167. this.body = body;
  7168. // default options
  7169. this.defaultOptions = {
  7170. showCustomTime: false
  7171. };
  7172. this.options = util.extend({}, this.defaultOptions);
  7173. this.customTime = new Date();
  7174. this.eventParams = {}; // stores state parameters while dragging the bar
  7175. // create the DOM
  7176. this._create();
  7177. this.setOptions(options);
  7178. }
  7179. CustomTime.prototype = new Component();
  7180. /**
  7181. * Set options for the component. Options will be merged in current options.
  7182. * @param {Object} options Available parameters:
  7183. * {boolean} [showCustomTime]
  7184. */
  7185. CustomTime.prototype.setOptions = function(options) {
  7186. if (options) {
  7187. // copy all options that we know
  7188. util.selectiveExtend(['showCustomTime'], this.options, options);
  7189. }
  7190. };
  7191. /**
  7192. * Create the DOM for the custom time
  7193. * @private
  7194. */
  7195. CustomTime.prototype._create = function() {
  7196. var bar = document.createElement('div');
  7197. bar.className = 'customtime';
  7198. bar.style.position = 'absolute';
  7199. bar.style.top = '0px';
  7200. bar.style.height = '100%';
  7201. this.bar = bar;
  7202. var drag = document.createElement('div');
  7203. drag.style.position = 'relative';
  7204. drag.style.top = '0px';
  7205. drag.style.left = '-10px';
  7206. drag.style.height = '100%';
  7207. drag.style.width = '20px';
  7208. bar.appendChild(drag);
  7209. // attach event listeners
  7210. this.hammer = Hammer(bar, {
  7211. prevent_default: true
  7212. });
  7213. this.hammer.on('dragstart', this._onDragStart.bind(this));
  7214. this.hammer.on('drag', this._onDrag.bind(this));
  7215. this.hammer.on('dragend', this._onDragEnd.bind(this));
  7216. };
  7217. /**
  7218. * Destroy the CustomTime bar
  7219. */
  7220. CustomTime.prototype.destroy = function () {
  7221. this.options.showCustomTime = false;
  7222. this.redraw(); // will remove the bar from the DOM
  7223. this.hammer.enable(false);
  7224. this.hammer = null;
  7225. this.body = null;
  7226. };
  7227. /**
  7228. * Repaint the component
  7229. * @return {boolean} Returns true if the component is resized
  7230. */
  7231. CustomTime.prototype.redraw = function () {
  7232. if (this.options.showCustomTime) {
  7233. var parent = this.body.dom.backgroundVertical;
  7234. if (this.bar.parentNode != parent) {
  7235. // attach to the dom
  7236. if (this.bar.parentNode) {
  7237. this.bar.parentNode.removeChild(this.bar);
  7238. }
  7239. parent.appendChild(this.bar);
  7240. }
  7241. var x = this.body.util.toScreen(this.customTime);
  7242. this.bar.style.left = x + 'px';
  7243. this.bar.title = 'Time: ' + this.customTime;
  7244. }
  7245. else {
  7246. // remove the line from the DOM
  7247. if (this.bar.parentNode) {
  7248. this.bar.parentNode.removeChild(this.bar);
  7249. }
  7250. }
  7251. return false;
  7252. };
  7253. /**
  7254. * Set custom time.
  7255. * @param {Date} time
  7256. */
  7257. CustomTime.prototype.setCustomTime = function(time) {
  7258. this.customTime = new Date(time.valueOf());
  7259. this.redraw();
  7260. };
  7261. /**
  7262. * Retrieve the current custom time.
  7263. * @return {Date} customTime
  7264. */
  7265. CustomTime.prototype.getCustomTime = function() {
  7266. return new Date(this.customTime.valueOf());
  7267. };
  7268. /**
  7269. * Start moving horizontally
  7270. * @param {Event} event
  7271. * @private
  7272. */
  7273. CustomTime.prototype._onDragStart = function(event) {
  7274. this.eventParams.dragging = true;
  7275. this.eventParams.customTime = this.customTime;
  7276. event.stopPropagation();
  7277. event.preventDefault();
  7278. };
  7279. /**
  7280. * Perform moving operating.
  7281. * @param {Event} event
  7282. * @private
  7283. */
  7284. CustomTime.prototype._onDrag = function (event) {
  7285. if (!this.eventParams.dragging) return;
  7286. var deltaX = event.gesture.deltaX,
  7287. x = this.body.util.toScreen(this.eventParams.customTime) + deltaX,
  7288. time = this.body.util.toTime(x);
  7289. this.setCustomTime(time);
  7290. // fire a timechange event
  7291. this.body.emitter.emit('timechange', {
  7292. time: new Date(this.customTime.valueOf())
  7293. });
  7294. event.stopPropagation();
  7295. event.preventDefault();
  7296. };
  7297. /**
  7298. * Stop moving operating.
  7299. * @param {event} event
  7300. * @private
  7301. */
  7302. CustomTime.prototype._onDragEnd = function (event) {
  7303. if (!this.eventParams.dragging) return;
  7304. // fire a timechanged event
  7305. this.body.emitter.emit('timechanged', {
  7306. time: new Date(this.customTime.valueOf())
  7307. });
  7308. event.stopPropagation();
  7309. event.preventDefault();
  7310. };
  7311. module.exports = CustomTime;
  7312. /***/ },
  7313. /* 21 */
  7314. /***/ function(module, exports, __webpack_require__) {
  7315. var util = __webpack_require__(1);
  7316. var DOMutil = __webpack_require__(2);
  7317. var Component = __webpack_require__(18);
  7318. var DataStep = __webpack_require__(14);
  7319. /**
  7320. * A horizontal time axis
  7321. * @param {Object} [options] See DataAxis.setOptions for the available
  7322. * options.
  7323. * @constructor DataAxis
  7324. * @extends Component
  7325. * @param body
  7326. */
  7327. function DataAxis (body, options, svg) {
  7328. this.id = util.randomUUID();
  7329. this.body = body;
  7330. this.defaultOptions = {
  7331. orientation: 'left', // supported: 'left', 'right'
  7332. showMinorLabels: true,
  7333. showMajorLabels: true,
  7334. icons: true,
  7335. majorLinesOffset: 7,
  7336. minorLinesOffset: 4,
  7337. labelOffsetX: 10,
  7338. labelOffsetY: 2,
  7339. iconWidth: 20,
  7340. width: '40px',
  7341. visible: true
  7342. };
  7343. this.linegraphSVG = svg;
  7344. this.props = {};
  7345. this.DOMelements = { // dynamic elements
  7346. lines: {},
  7347. labels: {}
  7348. };
  7349. this.dom = {};
  7350. this.range = {start:0, end:0};
  7351. this.options = util.extend({}, this.defaultOptions);
  7352. this.conversionFactor = 1;
  7353. this.setOptions(options);
  7354. this.width = Number(('' + this.options.width).replace("px",""));
  7355. this.minWidth = this.width;
  7356. this.height = this.linegraphSVG.offsetHeight;
  7357. this.stepPixels = 25;
  7358. this.stepPixelsForced = 25;
  7359. this.lineOffset = 0;
  7360. this.master = true;
  7361. this.svgElements = {};
  7362. this.groups = {};
  7363. this.amountOfGroups = 0;
  7364. // create the HTML DOM
  7365. this._create();
  7366. }
  7367. DataAxis.prototype = new Component();
  7368. DataAxis.prototype.addGroup = function(label, graphOptions) {
  7369. if (!this.groups.hasOwnProperty(label)) {
  7370. this.groups[label] = graphOptions;
  7371. }
  7372. this.amountOfGroups += 1;
  7373. };
  7374. DataAxis.prototype.updateGroup = function(label, graphOptions) {
  7375. this.groups[label] = graphOptions;
  7376. };
  7377. DataAxis.prototype.removeGroup = function(label) {
  7378. if (this.groups.hasOwnProperty(label)) {
  7379. delete this.groups[label];
  7380. this.amountOfGroups -= 1;
  7381. }
  7382. };
  7383. DataAxis.prototype.setOptions = function (options) {
  7384. if (options) {
  7385. var redraw = false;
  7386. if (this.options.orientation != options.orientation && options.orientation !== undefined) {
  7387. redraw = true;
  7388. }
  7389. var fields = [
  7390. 'orientation',
  7391. 'showMinorLabels',
  7392. 'showMajorLabels',
  7393. 'icons',
  7394. 'majorLinesOffset',
  7395. 'minorLinesOffset',
  7396. 'labelOffsetX',
  7397. 'labelOffsetY',
  7398. 'iconWidth',
  7399. 'width',
  7400. 'visible'];
  7401. util.selectiveExtend(fields, this.options, options);
  7402. this.minWidth = Number(('' + this.options.width).replace("px",""));
  7403. if (redraw == true && this.dom.frame) {
  7404. this.hide();
  7405. this.show();
  7406. }
  7407. }
  7408. };
  7409. /**
  7410. * Create the HTML DOM for the DataAxis
  7411. */
  7412. DataAxis.prototype._create = function() {
  7413. this.dom.frame = document.createElement('div');
  7414. this.dom.frame.style.width = this.options.width;
  7415. this.dom.frame.style.height = this.height;
  7416. this.dom.lineContainer = document.createElement('div');
  7417. this.dom.lineContainer.style.width = '100%';
  7418. this.dom.lineContainer.style.height = this.height;
  7419. // create svg element for graph drawing.
  7420. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  7421. this.svg.style.position = "absolute";
  7422. this.svg.style.top = '0px';
  7423. this.svg.style.height = '100%';
  7424. this.svg.style.width = '100%';
  7425. this.svg.style.display = "block";
  7426. this.dom.frame.appendChild(this.svg);
  7427. };
  7428. DataAxis.prototype._redrawGroupIcons = function () {
  7429. DOMutil.prepareElements(this.svgElements);
  7430. var x;
  7431. var iconWidth = this.options.iconWidth;
  7432. var iconHeight = 15;
  7433. var iconOffset = 4;
  7434. var y = iconOffset + 0.5 * iconHeight;
  7435. if (this.options.orientation == 'left') {
  7436. x = iconOffset;
  7437. }
  7438. else {
  7439. x = this.width - iconWidth - iconOffset;
  7440. }
  7441. for (var groupId in this.groups) {
  7442. if (this.groups.hasOwnProperty(groupId)) {
  7443. if (this.groups[groupId].visible == true) {
  7444. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  7445. y += iconHeight + iconOffset;
  7446. }
  7447. }
  7448. }
  7449. DOMutil.cleanupElements(this.svgElements);
  7450. };
  7451. /**
  7452. * Create the HTML DOM for the DataAxis
  7453. */
  7454. DataAxis.prototype.show = function() {
  7455. if (!this.dom.frame.parentNode) {
  7456. if (this.options.orientation == 'left') {
  7457. this.body.dom.left.appendChild(this.dom.frame);
  7458. }
  7459. else {
  7460. this.body.dom.right.appendChild(this.dom.frame);
  7461. }
  7462. }
  7463. if (!this.dom.lineContainer.parentNode) {
  7464. this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
  7465. }
  7466. };
  7467. /**
  7468. * Create the HTML DOM for the DataAxis
  7469. */
  7470. DataAxis.prototype.hide = function() {
  7471. if (this.dom.frame.parentNode) {
  7472. this.dom.frame.parentNode.removeChild(this.dom.frame);
  7473. }
  7474. if (this.dom.lineContainer.parentNode) {
  7475. this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
  7476. }
  7477. };
  7478. /**
  7479. * Set a range (start and end)
  7480. * @param end
  7481. * @param start
  7482. * @param end
  7483. */
  7484. DataAxis.prototype.setRange = function (start, end) {
  7485. this.range.start = start;
  7486. this.range.end = end;
  7487. };
  7488. /**
  7489. * Repaint the component
  7490. * @return {boolean} Returns true if the component is resized
  7491. */
  7492. DataAxis.prototype.redraw = function () {
  7493. var changeCalled = false;
  7494. var activeGroups = 0;
  7495. for (var groupId in this.groups) {
  7496. if (this.groups.hasOwnProperty(groupId)) {
  7497. if (this.groups[groupId].visible == true) {
  7498. activeGroups++;
  7499. }
  7500. }
  7501. }
  7502. if (this.amountOfGroups == 0 || activeGroups == 0) {
  7503. this.hide();
  7504. }
  7505. else {
  7506. this.show();
  7507. this.height = Number(this.linegraphSVG.style.height.replace("px",""));
  7508. // svg offsetheight did not work in firefox and explorer...
  7509. this.dom.lineContainer.style.height = this.height + 'px';
  7510. this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0;
  7511. var props = this.props;
  7512. var frame = this.dom.frame;
  7513. // update classname
  7514. frame.className = 'dataaxis';
  7515. // calculate character width and height
  7516. this._calculateCharSize();
  7517. var orientation = this.options.orientation;
  7518. var showMinorLabels = this.options.showMinorLabels;
  7519. var showMajorLabels = this.options.showMajorLabels;
  7520. // determine the width and height of the elemens for the axis
  7521. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  7522. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  7523. props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
  7524. props.minorLineHeight = 1;
  7525. props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
  7526. props.majorLineHeight = 1;
  7527. // take frame offline while updating (is almost twice as fast)
  7528. if (orientation == 'left') {
  7529. frame.style.top = '0';
  7530. frame.style.left = '0';
  7531. frame.style.bottom = '';
  7532. frame.style.width = this.width + 'px';
  7533. frame.style.height = this.height + "px";
  7534. }
  7535. else { // right
  7536. frame.style.top = '';
  7537. frame.style.bottom = '0';
  7538. frame.style.left = '0';
  7539. frame.style.width = this.width + 'px';
  7540. frame.style.height = this.height + "px";
  7541. }
  7542. changeCalled = this._redrawLabels();
  7543. if (this.options.icons == true) {
  7544. this._redrawGroupIcons();
  7545. }
  7546. }
  7547. return changeCalled;
  7548. };
  7549. /**
  7550. * Repaint major and minor text labels and vertical grid lines
  7551. * @private
  7552. */
  7553. DataAxis.prototype._redrawLabels = function () {
  7554. DOMutil.prepareElements(this.DOMelements.lines);
  7555. DOMutil.prepareElements(this.DOMelements.labels);
  7556. var orientation = this.options['orientation'];
  7557. // calculate range and step (step such that we have space for 7 characters per label)
  7558. var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced;
  7559. var step = new DataStep(this.range.start, this.range.end, minimumStep, this.dom.frame.offsetHeight);
  7560. this.step = step;
  7561. step.first();
  7562. // get the distance in pixels for a step
  7563. var stepPixels = this.dom.frame.offsetHeight / ((step.marginRange / step.step) + 1);
  7564. this.stepPixels = stepPixels;
  7565. var amountOfSteps = this.height / stepPixels;
  7566. var stepDifference = 0;
  7567. if (this.master == false) {
  7568. stepPixels = this.stepPixelsForced;
  7569. stepDifference = Math.round((this.height / stepPixels) - amountOfSteps);
  7570. for (var i = 0; i < 0.5 * stepDifference; i++) {
  7571. step.previous();
  7572. }
  7573. amountOfSteps = this.height / stepPixels;
  7574. }
  7575. this.valueAtZero = step.marginEnd;
  7576. var marginStartPos = 0;
  7577. // do not draw the first label
  7578. var max = 1;
  7579. step.next();
  7580. this.maxLabelSize = 0;
  7581. var y = 0;
  7582. while (max < Math.round(amountOfSteps)) {
  7583. y = Math.round(max * stepPixels);
  7584. marginStartPos = max * stepPixels;
  7585. var isMajor = step.isMajor();
  7586. if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) {
  7587. this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis minor', this.props.minorCharHeight);
  7588. }
  7589. if (isMajor && this.options['showMajorLabels'] && this.master == true ||
  7590. this.options['showMinorLabels'] == false && this.master == false && isMajor == true) {
  7591. if (y >= 0) {
  7592. this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis major', this.props.majorCharHeight);
  7593. }
  7594. this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth);
  7595. }
  7596. else {
  7597. this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth);
  7598. }
  7599. step.next();
  7600. max++;
  7601. }
  7602. this.conversionFactor = marginStartPos/((amountOfSteps-1) * step.step);
  7603. var offset = this.options.icons == true ? this.options.iconWidth + this.options.labelOffsetX + 15 : this.options.labelOffsetX + 15;
  7604. // this will resize the yAxis to accomodate the labels.
  7605. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) {
  7606. this.width = this.maxLabelSize + offset;
  7607. this.options.width = this.width + "px";
  7608. DOMutil.cleanupElements(this.DOMelements.lines);
  7609. DOMutil.cleanupElements(this.DOMelements.labels);
  7610. this.redraw();
  7611. return true;
  7612. }
  7613. // this will resize the yAxis if it is too big for the labels.
  7614. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) {
  7615. this.width = Math.max(this.minWidth,this.maxLabelSize + offset);
  7616. this.options.width = this.width + "px";
  7617. DOMutil.cleanupElements(this.DOMelements.lines);
  7618. DOMutil.cleanupElements(this.DOMelements.labels);
  7619. this.redraw();
  7620. return true;
  7621. }
  7622. else {
  7623. DOMutil.cleanupElements(this.DOMelements.lines);
  7624. DOMutil.cleanupElements(this.DOMelements.labels);
  7625. return false;
  7626. }
  7627. };
  7628. /**
  7629. * Create a label for the axis at position x
  7630. * @private
  7631. * @param y
  7632. * @param text
  7633. * @param orientation
  7634. * @param className
  7635. * @param characterHeight
  7636. */
  7637. DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
  7638. // reuse redundant label
  7639. var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
  7640. label.className = className;
  7641. label.innerHTML = text;
  7642. if (orientation == 'left') {
  7643. label.style.left = '-' + this.options.labelOffsetX + 'px';
  7644. label.style.textAlign = "right";
  7645. }
  7646. else {
  7647. label.style.right = '-' + this.options.labelOffsetX + 'px';
  7648. label.style.textAlign = "left";
  7649. }
  7650. label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
  7651. text += '';
  7652. var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth);
  7653. if (this.maxLabelSize < text.length * largestWidth) {
  7654. this.maxLabelSize = text.length * largestWidth;
  7655. }
  7656. };
  7657. /**
  7658. * Create a minor line for the axis at position y
  7659. * @param y
  7660. * @param orientation
  7661. * @param className
  7662. * @param offset
  7663. * @param width
  7664. */
  7665. DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
  7666. if (this.master == true) {
  7667. var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift();
  7668. line.className = className;
  7669. line.innerHTML = '';
  7670. if (orientation == 'left') {
  7671. line.style.left = (this.width - offset) + 'px';
  7672. }
  7673. else {
  7674. line.style.right = (this.width - offset) + 'px';
  7675. }
  7676. line.style.width = width + 'px';
  7677. line.style.top = y + 'px';
  7678. }
  7679. };
  7680. DataAxis.prototype.convertValue = function (value) {
  7681. var invertedValue = this.valueAtZero - value;
  7682. var convertedValue = invertedValue * this.conversionFactor;
  7683. return convertedValue; // the -2 is to compensate for the borders
  7684. };
  7685. /**
  7686. * Determine the size of text on the axis (both major and minor axis).
  7687. * The size is calculated only once and then cached in this.props.
  7688. * @private
  7689. */
  7690. DataAxis.prototype._calculateCharSize = function () {
  7691. // determine the char width and height on the minor axis
  7692. if (!('minorCharHeight' in this.props)) {
  7693. var textMinor = document.createTextNode('0');
  7694. var measureCharMinor = document.createElement('DIV');
  7695. measureCharMinor.className = 'yAxis minor measure';
  7696. measureCharMinor.appendChild(textMinor);
  7697. this.dom.frame.appendChild(measureCharMinor);
  7698. this.props.minorCharHeight = measureCharMinor.clientHeight;
  7699. this.props.minorCharWidth = measureCharMinor.clientWidth;
  7700. this.dom.frame.removeChild(measureCharMinor);
  7701. }
  7702. if (!('majorCharHeight' in this.props)) {
  7703. var textMajor = document.createTextNode('0');
  7704. var measureCharMajor = document.createElement('DIV');
  7705. measureCharMajor.className = 'yAxis major measure';
  7706. measureCharMajor.appendChild(textMajor);
  7707. this.dom.frame.appendChild(measureCharMajor);
  7708. this.props.majorCharHeight = measureCharMajor.clientHeight;
  7709. this.props.majorCharWidth = measureCharMajor.clientWidth;
  7710. this.dom.frame.removeChild(measureCharMajor);
  7711. }
  7712. };
  7713. /**
  7714. * Snap a date to a rounded value.
  7715. * The snap intervals are dependent on the current scale and step.
  7716. * @param {Date} date the date to be snapped.
  7717. * @return {Date} snappedDate
  7718. */
  7719. DataAxis.prototype.snap = function(date) {
  7720. return this.step.snap(date);
  7721. };
  7722. module.exports = DataAxis;
  7723. /***/ },
  7724. /* 22 */
  7725. /***/ function(module, exports, __webpack_require__) {
  7726. var util = __webpack_require__(1);
  7727. var DOMutil = __webpack_require__(2);
  7728. /**
  7729. * @constructor Group
  7730. * @param {Number | String} groupId
  7731. * @param {Object} data
  7732. * @param {ItemSet} itemSet
  7733. */
  7734. function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) {
  7735. this.id = groupId;
  7736. var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom']
  7737. this.options = util.selectiveBridgeObject(fields,options);
  7738. this.usingDefaultStyle = group.className === undefined;
  7739. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  7740. this.zeroPosition = 0;
  7741. this.update(group);
  7742. if (this.usingDefaultStyle == true) {
  7743. this.groupsUsingDefaultStyles[0] += 1;
  7744. }
  7745. this.itemsData = [];
  7746. this.visible = group.visible === undefined ? true : group.visible;
  7747. }
  7748. GraphGroup.prototype.setItems = function(items) {
  7749. if (items != null) {
  7750. this.itemsData = items;
  7751. if (this.options.sort == true) {
  7752. this.itemsData.sort(function (a,b) {return a.x - b.x;})
  7753. }
  7754. }
  7755. else {
  7756. this.itemsData = [];
  7757. }
  7758. };
  7759. GraphGroup.prototype.setZeroPosition = function(pos) {
  7760. this.zeroPosition = pos;
  7761. };
  7762. GraphGroup.prototype.setOptions = function(options) {
  7763. if (options !== undefined) {
  7764. var fields = ['sampling','style','sort','yAxisOrientation','barChart'];
  7765. util.selectiveDeepExtend(fields, this.options, options);
  7766. util.mergeOptions(this.options, options,'catmullRom');
  7767. util.mergeOptions(this.options, options,'drawPoints');
  7768. util.mergeOptions(this.options, options,'shaded');
  7769. if (options.catmullRom) {
  7770. if (typeof options.catmullRom == 'object') {
  7771. if (options.catmullRom.parametrization) {
  7772. if (options.catmullRom.parametrization == 'uniform') {
  7773. this.options.catmullRom.alpha = 0;
  7774. }
  7775. else if (options.catmullRom.parametrization == 'chordal') {
  7776. this.options.catmullRom.alpha = 1.0;
  7777. }
  7778. else {
  7779. this.options.catmullRom.parametrization = 'centripetal';
  7780. this.options.catmullRom.alpha = 0.5;
  7781. }
  7782. }
  7783. }
  7784. }
  7785. }
  7786. };
  7787. GraphGroup.prototype.update = function(group) {
  7788. this.group = group;
  7789. this.content = group.content || 'graph';
  7790. this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10;
  7791. this.visible = group.visible === undefined ? true : group.visible;
  7792. this.setOptions(group.options);
  7793. };
  7794. GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) {
  7795. var fillHeight = iconHeight * 0.5;
  7796. var path, fillPath;
  7797. var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer);
  7798. outline.setAttributeNS(null, "x", x);
  7799. outline.setAttributeNS(null, "y", y - fillHeight);
  7800. outline.setAttributeNS(null, "width", iconWidth);
  7801. outline.setAttributeNS(null, "height", 2*fillHeight);
  7802. outline.setAttributeNS(null, "class", "outline");
  7803. if (this.options.style == 'line') {
  7804. path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  7805. path.setAttributeNS(null, "class", this.className);
  7806. path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+"");
  7807. if (this.options.shaded.enabled == true) {
  7808. fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  7809. if (this.options.shaded.orientation == 'top') {
  7810. fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) +
  7811. "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight));
  7812. }
  7813. else {
  7814. fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " +
  7815. "L"+x+"," + (y + fillHeight) + " " +
  7816. "L"+ (x + iconWidth) + "," + (y + fillHeight) +
  7817. "L"+ (x + iconWidth) + ","+y);
  7818. }
  7819. fillPath.setAttributeNS(null, "class", this.className + " iconFill");
  7820. }
  7821. if (this.options.drawPoints.enabled == true) {
  7822. DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer);
  7823. }
  7824. }
  7825. else {
  7826. var barWidth = Math.round(0.3 * iconWidth);
  7827. var bar1Height = Math.round(0.4 * iconHeight);
  7828. var bar2Height = Math.round(0.75 * iconHeight);
  7829. var offset = Math.round((iconWidth - (2 * barWidth))/3);
  7830. DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  7831. DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  7832. }
  7833. };
  7834. /**
  7835. *
  7836. * @param iconWidth
  7837. * @param iconHeight
  7838. * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
  7839. */
  7840. GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) {
  7841. var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  7842. this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight);
  7843. return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation};
  7844. }
  7845. module.exports = GraphGroup;
  7846. /***/ },
  7847. /* 23 */
  7848. /***/ function(module, exports, __webpack_require__) {
  7849. var util = __webpack_require__(1);
  7850. var stack = __webpack_require__(16);
  7851. var ItemRange = __webpack_require__(31);
  7852. /**
  7853. * @constructor Group
  7854. * @param {Number | String} groupId
  7855. * @param {Object} data
  7856. * @param {ItemSet} itemSet
  7857. */
  7858. function Group (groupId, data, itemSet) {
  7859. this.groupId = groupId;
  7860. this.itemSet = itemSet;
  7861. this.dom = {};
  7862. this.props = {
  7863. label: {
  7864. width: 0,
  7865. height: 0
  7866. }
  7867. };
  7868. this.className = null;
  7869. this.items = {}; // items filtered by groupId of this group
  7870. this.visibleItems = []; // items currently visible in window
  7871. this.orderedItems = { // items sorted by start and by end
  7872. byStart: [],
  7873. byEnd: []
  7874. };
  7875. this._create();
  7876. this.setData(data);
  7877. }
  7878. /**
  7879. * Create DOM elements for the group
  7880. * @private
  7881. */
  7882. Group.prototype._create = function() {
  7883. var label = document.createElement('div');
  7884. label.className = 'vlabel';
  7885. this.dom.label = label;
  7886. var inner = document.createElement('div');
  7887. inner.className = 'inner';
  7888. label.appendChild(inner);
  7889. this.dom.inner = inner;
  7890. var foreground = document.createElement('div');
  7891. foreground.className = 'group';
  7892. foreground['timeline-group'] = this;
  7893. this.dom.foreground = foreground;
  7894. this.dom.background = document.createElement('div');
  7895. this.dom.background.className = 'group';
  7896. this.dom.axis = document.createElement('div');
  7897. this.dom.axis.className = 'group';
  7898. // create a hidden marker to detect when the Timelines container is attached
  7899. // to the DOM, or the style of a parent of the Timeline is changed from
  7900. // display:none is changed to visible.
  7901. this.dom.marker = document.createElement('div');
  7902. this.dom.marker.style.visibility = 'hidden';
  7903. this.dom.marker.innerHTML = '?';
  7904. this.dom.background.appendChild(this.dom.marker);
  7905. };
  7906. /**
  7907. * Set the group data for this group
  7908. * @param {Object} data Group data, can contain properties content and className
  7909. */
  7910. Group.prototype.setData = function(data) {
  7911. // update contents
  7912. var content = data && data.content;
  7913. if (content instanceof Element) {
  7914. this.dom.inner.appendChild(content);
  7915. }
  7916. else if (content !== undefined && content !== null) {
  7917. this.dom.inner.innerHTML = content;
  7918. }
  7919. else {
  7920. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  7921. }
  7922. // update title
  7923. this.dom.label.title = data && data.title || '';
  7924. if (!this.dom.inner.firstChild) {
  7925. util.addClassName(this.dom.inner, 'hidden');
  7926. }
  7927. else {
  7928. util.removeClassName(this.dom.inner, 'hidden');
  7929. }
  7930. // update className
  7931. var className = data && data.className || null;
  7932. if (className != this.className) {
  7933. if (this.className) {
  7934. util.removeClassName(this.dom.label, className);
  7935. util.removeClassName(this.dom.foreground, className);
  7936. util.removeClassName(this.dom.background, className);
  7937. util.removeClassName(this.dom.axis, className);
  7938. }
  7939. util.addClassName(this.dom.label, className);
  7940. util.addClassName(this.dom.foreground, className);
  7941. util.addClassName(this.dom.background, className);
  7942. util.addClassName(this.dom.axis, className);
  7943. }
  7944. };
  7945. /**
  7946. * Get the width of the group label
  7947. * @return {number} width
  7948. */
  7949. Group.prototype.getLabelWidth = function() {
  7950. return this.props.label.width;
  7951. };
  7952. /**
  7953. * Repaint this group
  7954. * @param {{start: number, end: number}} range
  7955. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  7956. * @param {boolean} [restack=false] Force restacking of all items
  7957. * @return {boolean} Returns true if the group is resized
  7958. */
  7959. Group.prototype.redraw = function(range, margin, restack) {
  7960. var resized = false;
  7961. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  7962. // force recalculation of the height of the items when the marker height changed
  7963. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  7964. var markerHeight = this.dom.marker.clientHeight;
  7965. if (markerHeight != this.lastMarkerHeight) {
  7966. this.lastMarkerHeight = markerHeight;
  7967. util.forEach(this.items, function (item) {
  7968. item.dirty = true;
  7969. if (item.displayed) item.redraw();
  7970. });
  7971. restack = true;
  7972. }
  7973. // reposition visible items vertically
  7974. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  7975. stack.stack(this.visibleItems, margin, restack);
  7976. }
  7977. else { // no stacking
  7978. stack.nostack(this.visibleItems, margin);
  7979. }
  7980. // recalculate the height of the group
  7981. var height;
  7982. var visibleItems = this.visibleItems;
  7983. if (visibleItems.length) {
  7984. var min = visibleItems[0].top;
  7985. var max = visibleItems[0].top + visibleItems[0].height;
  7986. util.forEach(visibleItems, function (item) {
  7987. min = Math.min(min, item.top);
  7988. max = Math.max(max, (item.top + item.height));
  7989. });
  7990. if (min > margin.axis) {
  7991. // there is an empty gap between the lowest item and the axis
  7992. var offset = min - margin.axis;
  7993. max -= offset;
  7994. util.forEach(visibleItems, function (item) {
  7995. item.top -= offset;
  7996. });
  7997. }
  7998. height = max + margin.item.vertical / 2;
  7999. }
  8000. else {
  8001. height = margin.axis + margin.item.vertical;
  8002. }
  8003. height = Math.max(height, this.props.label.height);
  8004. // calculate actual size and position
  8005. var foreground = this.dom.foreground;
  8006. this.top = foreground.offsetTop;
  8007. this.left = foreground.offsetLeft;
  8008. this.width = foreground.offsetWidth;
  8009. resized = util.updateProperty(this, 'height', height) || resized;
  8010. // recalculate size of label
  8011. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  8012. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  8013. // apply new height
  8014. this.dom.background.style.height = height + 'px';
  8015. this.dom.foreground.style.height = height + 'px';
  8016. this.dom.label.style.height = height + 'px';
  8017. // update vertical position of items after they are re-stacked and the height of the group is calculated
  8018. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  8019. var item = this.visibleItems[i];
  8020. item.repositionY();
  8021. }
  8022. return resized;
  8023. };
  8024. /**
  8025. * Show this group: attach to the DOM
  8026. */
  8027. Group.prototype.show = function() {
  8028. if (!this.dom.label.parentNode) {
  8029. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  8030. }
  8031. if (!this.dom.foreground.parentNode) {
  8032. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  8033. }
  8034. if (!this.dom.background.parentNode) {
  8035. this.itemSet.dom.background.appendChild(this.dom.background);
  8036. }
  8037. if (!this.dom.axis.parentNode) {
  8038. this.itemSet.dom.axis.appendChild(this.dom.axis);
  8039. }
  8040. };
  8041. /**
  8042. * Hide this group: remove from the DOM
  8043. */
  8044. Group.prototype.hide = function() {
  8045. var label = this.dom.label;
  8046. if (label.parentNode) {
  8047. label.parentNode.removeChild(label);
  8048. }
  8049. var foreground = this.dom.foreground;
  8050. if (foreground.parentNode) {
  8051. foreground.parentNode.removeChild(foreground);
  8052. }
  8053. var background = this.dom.background;
  8054. if (background.parentNode) {
  8055. background.parentNode.removeChild(background);
  8056. }
  8057. var axis = this.dom.axis;
  8058. if (axis.parentNode) {
  8059. axis.parentNode.removeChild(axis);
  8060. }
  8061. };
  8062. /**
  8063. * Add an item to the group
  8064. * @param {Item} item
  8065. */
  8066. Group.prototype.add = function(item) {
  8067. this.items[item.id] = item;
  8068. item.setParent(this);
  8069. if (this.visibleItems.indexOf(item) == -1) {
  8070. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  8071. this._checkIfVisible(item, this.visibleItems, range);
  8072. }
  8073. };
  8074. /**
  8075. * Remove an item from the group
  8076. * @param {Item} item
  8077. */
  8078. Group.prototype.remove = function(item) {
  8079. delete this.items[item.id];
  8080. item.setParent(this.itemSet);
  8081. // remove from visible items
  8082. var index = this.visibleItems.indexOf(item);
  8083. if (index != -1) this.visibleItems.splice(index, 1);
  8084. // TODO: also remove from ordered items?
  8085. };
  8086. /**
  8087. * Remove an item from the corresponding DataSet
  8088. * @param {Item} item
  8089. */
  8090. Group.prototype.removeFromDataSet = function(item) {
  8091. this.itemSet.removeItem(item.id);
  8092. };
  8093. /**
  8094. * Reorder the items
  8095. */
  8096. Group.prototype.order = function() {
  8097. var array = util.toArray(this.items);
  8098. this.orderedItems.byStart = array;
  8099. this.orderedItems.byEnd = this._constructByEndArray(array);
  8100. stack.orderByStart(this.orderedItems.byStart);
  8101. stack.orderByEnd(this.orderedItems.byEnd);
  8102. };
  8103. /**
  8104. * Create an array containing all items being a range (having an end date)
  8105. * @param {Item[]} array
  8106. * @returns {ItemRange[]}
  8107. * @private
  8108. */
  8109. Group.prototype._constructByEndArray = function(array) {
  8110. var endArray = [];
  8111. for (var i = 0; i < array.length; i++) {
  8112. if (array[i] instanceof ItemRange) {
  8113. endArray.push(array[i]);
  8114. }
  8115. }
  8116. return endArray;
  8117. };
  8118. /**
  8119. * Update the visible items
  8120. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  8121. * @param {Item[]} visibleItems The previously visible items.
  8122. * @param {{start: number, end: number}} range Visible range
  8123. * @return {Item[]} visibleItems The new visible items.
  8124. * @private
  8125. */
  8126. Group.prototype._updateVisibleItems = function(orderedItems, visibleItems, range) {
  8127. var initialPosByStart,
  8128. newVisibleItems = [],
  8129. i;
  8130. // first check if the items that were in view previously are still in view.
  8131. // this handles the case for the ItemRange that is both before and after the current one.
  8132. if (visibleItems.length > 0) {
  8133. for (i = 0; i < visibleItems.length; i++) {
  8134. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  8135. }
  8136. }
  8137. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  8138. if (newVisibleItems.length == 0) {
  8139. initialPosByStart = util.binarySearch(orderedItems.byStart, range, 'data','start');
  8140. }
  8141. else {
  8142. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  8143. }
  8144. // use visible search to find a visible ItemRange (only based on endTime)
  8145. var initialPosByEnd = util.binarySearch(orderedItems.byEnd, range, 'data','end');
  8146. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  8147. if (initialPosByStart != -1) {
  8148. for (i = initialPosByStart; i >= 0; i--) {
  8149. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  8150. }
  8151. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  8152. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  8153. }
  8154. }
  8155. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  8156. if (initialPosByEnd != -1) {
  8157. for (i = initialPosByEnd; i >= 0; i--) {
  8158. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  8159. }
  8160. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  8161. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  8162. }
  8163. }
  8164. return newVisibleItems;
  8165. };
  8166. /**
  8167. * this function checks if an item is invisible. If it is NOT we make it visible
  8168. * and add it to the global visible items. If it is, return true.
  8169. *
  8170. * @param {Item} item
  8171. * @param {Item[]} visibleItems
  8172. * @param {{start:number, end:number}} range
  8173. * @returns {boolean}
  8174. * @private
  8175. */
  8176. Group.prototype._checkIfInvisible = function(item, visibleItems, range) {
  8177. if (item.isVisible(range)) {
  8178. if (!item.displayed) item.show();
  8179. item.repositionX();
  8180. if (visibleItems.indexOf(item) == -1) {
  8181. visibleItems.push(item);
  8182. }
  8183. return false;
  8184. }
  8185. else {
  8186. if (item.displayed) item.hide();
  8187. return true;
  8188. }
  8189. };
  8190. /**
  8191. * this function is very similar to the _checkIfInvisible() but it does not
  8192. * return booleans, hides the item if it should not be seen and always adds to
  8193. * the visibleItems.
  8194. * this one is for brute forcing and hiding.
  8195. *
  8196. * @param {Item} item
  8197. * @param {Array} visibleItems
  8198. * @param {{start:number, end:number}} range
  8199. * @private
  8200. */
  8201. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  8202. if (item.isVisible(range)) {
  8203. if (!item.displayed) item.show();
  8204. // reposition item horizontally
  8205. item.repositionX();
  8206. visibleItems.push(item);
  8207. }
  8208. else {
  8209. if (item.displayed) item.hide();
  8210. }
  8211. };
  8212. module.exports = Group;
  8213. /***/ },
  8214. /* 24 */
  8215. /***/ function(module, exports, __webpack_require__) {
  8216. var Hammer = __webpack_require__(41);
  8217. var util = __webpack_require__(1);
  8218. var DataSet = __webpack_require__(3);
  8219. var DataView = __webpack_require__(4);
  8220. var Component = __webpack_require__(18);
  8221. var Group = __webpack_require__(23);
  8222. var ItemBox = __webpack_require__(28);
  8223. var ItemPoint = __webpack_require__(30);
  8224. var ItemRange = __webpack_require__(31);
  8225. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  8226. /**
  8227. * An ItemSet holds a set of items and ranges which can be displayed in a
  8228. * range. The width is determined by the parent of the ItemSet, and the height
  8229. * is determined by the size of the items.
  8230. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  8231. * @param {Object} [options] See ItemSet.setOptions for the available options.
  8232. * @constructor ItemSet
  8233. * @extends Component
  8234. */
  8235. function ItemSet(body, options) {
  8236. this.body = body;
  8237. this.defaultOptions = {
  8238. type: null, // 'box', 'point', 'range'
  8239. orientation: 'bottom', // 'top' or 'bottom'
  8240. align: 'center', // alignment of box items
  8241. stack: true,
  8242. groupOrder: null,
  8243. selectable: true,
  8244. editable: {
  8245. updateTime: false,
  8246. updateGroup: false,
  8247. add: false,
  8248. remove: false
  8249. },
  8250. onAdd: function (item, callback) {
  8251. callback(item);
  8252. },
  8253. onUpdate: function (item, callback) {
  8254. callback(item);
  8255. },
  8256. onMove: function (item, callback) {
  8257. callback(item);
  8258. },
  8259. onRemove: function (item, callback) {
  8260. callback(item);
  8261. },
  8262. margin: {
  8263. item: {
  8264. horizontal: 10,
  8265. vertical: 10
  8266. },
  8267. axis: 20
  8268. },
  8269. padding: 5
  8270. };
  8271. // options is shared by this ItemSet and all its items
  8272. this.options = util.extend({}, this.defaultOptions);
  8273. // options for getting items from the DataSet with the correct type
  8274. this.itemOptions = {
  8275. type: {start: 'Date', end: 'Date'}
  8276. };
  8277. this.conversion = {
  8278. toScreen: body.util.toScreen,
  8279. toTime: body.util.toTime
  8280. };
  8281. this.dom = {};
  8282. this.props = {};
  8283. this.hammer = null;
  8284. var me = this;
  8285. this.itemsData = null; // DataSet
  8286. this.groupsData = null; // DataSet
  8287. // listeners for the DataSet of the items
  8288. this.itemListeners = {
  8289. 'add': function (event, params, senderId) {
  8290. me._onAdd(params.items);
  8291. },
  8292. 'update': function (event, params, senderId) {
  8293. me._onUpdate(params.items);
  8294. },
  8295. 'remove': function (event, params, senderId) {
  8296. me._onRemove(params.items);
  8297. }
  8298. };
  8299. // listeners for the DataSet of the groups
  8300. this.groupListeners = {
  8301. 'add': function (event, params, senderId) {
  8302. me._onAddGroups(params.items);
  8303. },
  8304. 'update': function (event, params, senderId) {
  8305. me._onUpdateGroups(params.items);
  8306. },
  8307. 'remove': function (event, params, senderId) {
  8308. me._onRemoveGroups(params.items);
  8309. }
  8310. };
  8311. this.items = {}; // object with an Item for every data item
  8312. this.groups = {}; // Group object for every group
  8313. this.groupIds = [];
  8314. this.selection = []; // list with the ids of all selected nodes
  8315. this.stackDirty = true; // if true, all items will be restacked on next redraw
  8316. this.touchParams = {}; // stores properties while dragging
  8317. // create the HTML DOM
  8318. this._create();
  8319. this.setOptions(options);
  8320. }
  8321. ItemSet.prototype = new Component();
  8322. // available item types will be registered here
  8323. ItemSet.types = {
  8324. box: ItemBox,
  8325. range: ItemRange,
  8326. point: ItemPoint
  8327. };
  8328. /**
  8329. * Create the HTML DOM for the ItemSet
  8330. */
  8331. ItemSet.prototype._create = function(){
  8332. var frame = document.createElement('div');
  8333. frame.className = 'itemset';
  8334. frame['timeline-itemset'] = this;
  8335. this.dom.frame = frame;
  8336. // create background panel
  8337. var background = document.createElement('div');
  8338. background.className = 'background';
  8339. frame.appendChild(background);
  8340. this.dom.background = background;
  8341. // create foreground panel
  8342. var foreground = document.createElement('div');
  8343. foreground.className = 'foreground';
  8344. frame.appendChild(foreground);
  8345. this.dom.foreground = foreground;
  8346. // create axis panel
  8347. var axis = document.createElement('div');
  8348. axis.className = 'axis';
  8349. this.dom.axis = axis;
  8350. // create labelset
  8351. var labelSet = document.createElement('div');
  8352. labelSet.className = 'labelset';
  8353. this.dom.labelSet = labelSet;
  8354. // create ungrouped Group
  8355. this._updateUngrouped();
  8356. // attach event listeners
  8357. // Note: we bind to the centerContainer for the case where the height
  8358. // of the center container is larger than of the ItemSet, so we
  8359. // can click in the empty area to create a new item or deselect an item.
  8360. this.hammer = Hammer(this.body.dom.centerContainer, {
  8361. prevent_default: true
  8362. });
  8363. // drag items when selected
  8364. this.hammer.on('touch', this._onTouch.bind(this));
  8365. this.hammer.on('dragstart', this._onDragStart.bind(this));
  8366. this.hammer.on('drag', this._onDrag.bind(this));
  8367. this.hammer.on('dragend', this._onDragEnd.bind(this));
  8368. // single select (or unselect) when tapping an item
  8369. this.hammer.on('tap', this._onSelectItem.bind(this));
  8370. // multi select when holding mouse/touch, or on ctrl+click
  8371. this.hammer.on('hold', this._onMultiSelectItem.bind(this));
  8372. // add item on doubletap
  8373. this.hammer.on('doubletap', this._onAddItem.bind(this));
  8374. // attach to the DOM
  8375. this.show();
  8376. };
  8377. /**
  8378. * Set options for the ItemSet. Existing options will be extended/overwritten.
  8379. * @param {Object} [options] The following options are available:
  8380. * {String} type
  8381. * Default type for the items. Choose from 'box'
  8382. * (default), 'point', or 'range'. The default
  8383. * Style can be overwritten by individual items.
  8384. * {String} align
  8385. * Alignment for the items, only applicable for
  8386. * ItemBox. Choose 'center' (default), 'left', or
  8387. * 'right'.
  8388. * {String} orientation
  8389. * Orientation of the item set. Choose 'top' or
  8390. * 'bottom' (default).
  8391. * {Function} groupOrder
  8392. * A sorting function for ordering groups
  8393. * {Boolean} stack
  8394. * If true (deafult), items will be stacked on
  8395. * top of each other.
  8396. * {Number} margin.axis
  8397. * Margin between the axis and the items in pixels.
  8398. * Default is 20.
  8399. * {Number} margin.item.horizontal
  8400. * Horizontal margin between items in pixels.
  8401. * Default is 10.
  8402. * {Number} margin.item.vertical
  8403. * Vertical Margin between items in pixels.
  8404. * Default is 10.
  8405. * {Number} margin.item
  8406. * Margin between items in pixels in both horizontal
  8407. * and vertical direction. Default is 10.
  8408. * {Number} margin
  8409. * Set margin for both axis and items in pixels.
  8410. * {Number} padding
  8411. * Padding of the contents of an item in pixels.
  8412. * Must correspond with the items css. Default is 5.
  8413. * {Boolean} selectable
  8414. * If true (default), items can be selected.
  8415. * {Boolean} editable
  8416. * Set all editable options to true or false
  8417. * {Boolean} editable.updateTime
  8418. * Allow dragging an item to an other moment in time
  8419. * {Boolean} editable.updateGroup
  8420. * Allow dragging an item to an other group
  8421. * {Boolean} editable.add
  8422. * Allow creating new items on double tap
  8423. * {Boolean} editable.remove
  8424. * Allow removing items by clicking the delete button
  8425. * top right of a selected item.
  8426. * {Function(item: Item, callback: Function)} onAdd
  8427. * Callback function triggered when an item is about to be added:
  8428. * when the user double taps an empty space in the Timeline.
  8429. * {Function(item: Item, callback: Function)} onUpdate
  8430. * Callback function fired when an item is about to be updated.
  8431. * This function typically has to show a dialog where the user
  8432. * change the item. If not implemented, nothing happens.
  8433. * {Function(item: Item, callback: Function)} onMove
  8434. * Fired when an item has been moved. If not implemented,
  8435. * the move action will be accepted.
  8436. * {Function(item: Item, callback: Function)} onRemove
  8437. * Fired when an item is about to be deleted.
  8438. * If not implemented, the item will be always removed.
  8439. */
  8440. ItemSet.prototype.setOptions = function(options) {
  8441. if (options) {
  8442. // copy all options that we know
  8443. var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder'];
  8444. util.selectiveExtend(fields, this.options, options);
  8445. if ('margin' in options) {
  8446. if (typeof options.margin === 'number') {
  8447. this.options.margin.axis = options.margin;
  8448. this.options.margin.item.horizontal = options.margin;
  8449. this.options.margin.item.vertical = options.margin;
  8450. }
  8451. else if (typeof options.margin === 'object') {
  8452. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  8453. if ('item' in options.margin) {
  8454. if (typeof options.margin.item === 'number') {
  8455. this.options.margin.item.horizontal = options.margin.item;
  8456. this.options.margin.item.vertical = options.margin.item;
  8457. }
  8458. else if (typeof options.margin.item === 'object') {
  8459. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  8460. }
  8461. }
  8462. }
  8463. }
  8464. if ('editable' in options) {
  8465. if (typeof options.editable === 'boolean') {
  8466. this.options.editable.updateTime = options.editable;
  8467. this.options.editable.updateGroup = options.editable;
  8468. this.options.editable.add = options.editable;
  8469. this.options.editable.remove = options.editable;
  8470. }
  8471. else if (typeof options.editable === 'object') {
  8472. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
  8473. }
  8474. }
  8475. // callback functions
  8476. var addCallback = (function (name) {
  8477. if (name in options) {
  8478. var fn = options[name];
  8479. if (!(fn instanceof Function)) {
  8480. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  8481. }
  8482. this.options[name] = fn;
  8483. }
  8484. }).bind(this);
  8485. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(addCallback);
  8486. // force the itemSet to refresh: options like orientation and margins may be changed
  8487. this.markDirty();
  8488. }
  8489. };
  8490. /**
  8491. * Mark the ItemSet dirty so it will refresh everything with next redraw
  8492. */
  8493. ItemSet.prototype.markDirty = function() {
  8494. this.groupIds = [];
  8495. this.stackDirty = true;
  8496. };
  8497. /**
  8498. * Destroy the ItemSet
  8499. */
  8500. ItemSet.prototype.destroy = function() {
  8501. this.hide();
  8502. this.setItems(null);
  8503. this.setGroups(null);
  8504. this.hammer = null;
  8505. this.body = null;
  8506. this.conversion = null;
  8507. };
  8508. /**
  8509. * Hide the component from the DOM
  8510. */
  8511. ItemSet.prototype.hide = function() {
  8512. // remove the frame containing the items
  8513. if (this.dom.frame.parentNode) {
  8514. this.dom.frame.parentNode.removeChild(this.dom.frame);
  8515. }
  8516. // remove the axis with dots
  8517. if (this.dom.axis.parentNode) {
  8518. this.dom.axis.parentNode.removeChild(this.dom.axis);
  8519. }
  8520. // remove the labelset containing all group labels
  8521. if (this.dom.labelSet.parentNode) {
  8522. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  8523. }
  8524. };
  8525. /**
  8526. * Show the component in the DOM (when not already visible).
  8527. * @return {Boolean} changed
  8528. */
  8529. ItemSet.prototype.show = function() {
  8530. // show frame containing the items
  8531. if (!this.dom.frame.parentNode) {
  8532. this.body.dom.center.appendChild(this.dom.frame);
  8533. }
  8534. // show axis with dots
  8535. if (!this.dom.axis.parentNode) {
  8536. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  8537. }
  8538. // show labelset containing labels
  8539. if (!this.dom.labelSet.parentNode) {
  8540. this.body.dom.left.appendChild(this.dom.labelSet);
  8541. }
  8542. };
  8543. /**
  8544. * Set selected items by their id. Replaces the current selection
  8545. * Unknown id's are silently ignored.
  8546. * @param {Array} [ids] An array with zero or more id's of the items to be
  8547. * selected. If ids is an empty array, all items will be
  8548. * unselected.
  8549. */
  8550. ItemSet.prototype.setSelection = function(ids) {
  8551. var i, ii, id, item;
  8552. if (ids) {
  8553. if (!Array.isArray(ids)) {
  8554. throw new TypeError('Array expected');
  8555. }
  8556. // unselect currently selected items
  8557. for (i = 0, ii = this.selection.length; i < ii; i++) {
  8558. id = this.selection[i];
  8559. item = this.items[id];
  8560. if (item) item.unselect();
  8561. }
  8562. // select items
  8563. this.selection = [];
  8564. for (i = 0, ii = ids.length; i < ii; i++) {
  8565. id = ids[i];
  8566. item = this.items[id];
  8567. if (item) {
  8568. this.selection.push(id);
  8569. item.select();
  8570. }
  8571. }
  8572. }
  8573. };
  8574. /**
  8575. * Get the selected items by their id
  8576. * @return {Array} ids The ids of the selected items
  8577. */
  8578. ItemSet.prototype.getSelection = function() {
  8579. return this.selection.concat([]);
  8580. };
  8581. /**
  8582. * Get the id's of the currently visible items.
  8583. * @returns {Array} The ids of the visible items
  8584. */
  8585. ItemSet.prototype.getVisibleItems = function() {
  8586. var range = this.body.range.getRange();
  8587. var left = this.body.util.toScreen(range.start);
  8588. var right = this.body.util.toScreen(range.end);
  8589. var ids = [];
  8590. for (var groupId in this.groups) {
  8591. if (this.groups.hasOwnProperty(groupId)) {
  8592. var group = this.groups[groupId];
  8593. var rawVisibleItems = group.visibleItems;
  8594. // filter the "raw" set with visibleItems into a set which is really
  8595. // visible by pixels
  8596. for (var i = 0; i < rawVisibleItems.length; i++) {
  8597. var item = rawVisibleItems[i];
  8598. // TODO: also check whether visible vertically
  8599. if ((item.left < right) && (item.left + item.width > left)) {
  8600. ids.push(item.id);
  8601. }
  8602. }
  8603. }
  8604. }
  8605. return ids;
  8606. };
  8607. /**
  8608. * Deselect a selected item
  8609. * @param {String | Number} id
  8610. * @private
  8611. */
  8612. ItemSet.prototype._deselect = function(id) {
  8613. var selection = this.selection;
  8614. for (var i = 0, ii = selection.length; i < ii; i++) {
  8615. if (selection[i] == id) { // non-strict comparison!
  8616. selection.splice(i, 1);
  8617. break;
  8618. }
  8619. }
  8620. };
  8621. /**
  8622. * Repaint the component
  8623. * @return {boolean} Returns true if the component is resized
  8624. */
  8625. ItemSet.prototype.redraw = function() {
  8626. var margin = this.options.margin,
  8627. range = this.body.range,
  8628. asSize = util.option.asSize,
  8629. options = this.options,
  8630. orientation = options.orientation,
  8631. resized = false,
  8632. frame = this.dom.frame,
  8633. editable = options.editable.updateTime || options.editable.updateGroup;
  8634. // update class name
  8635. frame.className = 'itemset' + (editable ? ' editable' : '');
  8636. // reorder the groups (if needed)
  8637. resized = this._orderGroups() || resized;
  8638. // check whether zoomed (in that case we need to re-stack everything)
  8639. // TODO: would be nicer to get this as a trigger from Range
  8640. var visibleInterval = range.end - range.start;
  8641. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  8642. if (zoomed) this.stackDirty = true;
  8643. this.lastVisibleInterval = visibleInterval;
  8644. this.props.lastWidth = this.props.width;
  8645. // redraw all groups
  8646. var restack = this.stackDirty,
  8647. firstGroup = this._firstGroup(),
  8648. firstMargin = {
  8649. item: margin.item,
  8650. axis: margin.axis
  8651. },
  8652. nonFirstMargin = {
  8653. item: margin.item,
  8654. axis: margin.item.vertical / 2
  8655. },
  8656. height = 0,
  8657. minHeight = margin.axis + margin.item.vertical;
  8658. util.forEach(this.groups, function (group) {
  8659. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  8660. var groupResized = group.redraw(range, groupMargin, restack);
  8661. resized = groupResized || resized;
  8662. height += group.height;
  8663. });
  8664. height = Math.max(height, minHeight);
  8665. this.stackDirty = false;
  8666. // update frame height
  8667. frame.style.height = asSize(height);
  8668. // calculate actual size and position
  8669. this.props.top = frame.offsetTop;
  8670. this.props.left = frame.offsetLeft;
  8671. this.props.width = frame.offsetWidth;
  8672. this.props.height = height;
  8673. // reposition axis
  8674. this.dom.axis.style.top = asSize((orientation == 'top') ?
  8675. (this.body.domProps.top.height + this.body.domProps.border.top) :
  8676. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  8677. this.dom.axis.style.left = this.body.domProps.border.left + 'px';
  8678. // check if this component is resized
  8679. resized = this._isResized() || resized;
  8680. return resized;
  8681. };
  8682. /**
  8683. * Get the first group, aligned with the axis
  8684. * @return {Group | null} firstGroup
  8685. * @private
  8686. */
  8687. ItemSet.prototype._firstGroup = function() {
  8688. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  8689. var firstGroupId = this.groupIds[firstGroupIndex];
  8690. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  8691. return firstGroup || null;
  8692. };
  8693. /**
  8694. * Create or delete the group holding all ungrouped items. This group is used when
  8695. * there are no groups specified.
  8696. * @protected
  8697. */
  8698. ItemSet.prototype._updateUngrouped = function() {
  8699. var ungrouped = this.groups[UNGROUPED];
  8700. if (this.groupsData) {
  8701. // remove the group holding all ungrouped items
  8702. if (ungrouped) {
  8703. ungrouped.hide();
  8704. delete this.groups[UNGROUPED];
  8705. }
  8706. }
  8707. else {
  8708. // create a group holding all (unfiltered) items
  8709. if (!ungrouped) {
  8710. var id = null;
  8711. var data = null;
  8712. ungrouped = new Group(id, data, this);
  8713. this.groups[UNGROUPED] = ungrouped;
  8714. for (var itemId in this.items) {
  8715. if (this.items.hasOwnProperty(itemId)) {
  8716. ungrouped.add(this.items[itemId]);
  8717. }
  8718. }
  8719. ungrouped.show();
  8720. }
  8721. }
  8722. };
  8723. /**
  8724. * Get the element for the labelset
  8725. * @return {HTMLElement} labelSet
  8726. */
  8727. ItemSet.prototype.getLabelSet = function() {
  8728. return this.dom.labelSet;
  8729. };
  8730. /**
  8731. * Set items
  8732. * @param {vis.DataSet | null} items
  8733. */
  8734. ItemSet.prototype.setItems = function(items) {
  8735. var me = this,
  8736. ids,
  8737. oldItemsData = this.itemsData;
  8738. // replace the dataset
  8739. if (!items) {
  8740. this.itemsData = null;
  8741. }
  8742. else if (items instanceof DataSet || items instanceof DataView) {
  8743. this.itemsData = items;
  8744. }
  8745. else {
  8746. throw new TypeError('Data must be an instance of DataSet or DataView');
  8747. }
  8748. if (oldItemsData) {
  8749. // unsubscribe from old dataset
  8750. util.forEach(this.itemListeners, function (callback, event) {
  8751. oldItemsData.off(event, callback);
  8752. });
  8753. // remove all drawn items
  8754. ids = oldItemsData.getIds();
  8755. this._onRemove(ids);
  8756. }
  8757. if (this.itemsData) {
  8758. // subscribe to new dataset
  8759. var id = this.id;
  8760. util.forEach(this.itemListeners, function (callback, event) {
  8761. me.itemsData.on(event, callback, id);
  8762. });
  8763. // add all new items
  8764. ids = this.itemsData.getIds();
  8765. this._onAdd(ids);
  8766. // update the group holding all ungrouped items
  8767. this._updateUngrouped();
  8768. }
  8769. };
  8770. /**
  8771. * Get the current items
  8772. * @returns {vis.DataSet | null}
  8773. */
  8774. ItemSet.prototype.getItems = function() {
  8775. return this.itemsData;
  8776. };
  8777. /**
  8778. * Set groups
  8779. * @param {vis.DataSet} groups
  8780. */
  8781. ItemSet.prototype.setGroups = function(groups) {
  8782. var me = this,
  8783. ids;
  8784. // unsubscribe from current dataset
  8785. if (this.groupsData) {
  8786. util.forEach(this.groupListeners, function (callback, event) {
  8787. me.groupsData.unsubscribe(event, callback);
  8788. });
  8789. // remove all drawn groups
  8790. ids = this.groupsData.getIds();
  8791. this.groupsData = null;
  8792. this._onRemoveGroups(ids); // note: this will cause a redraw
  8793. }
  8794. // replace the dataset
  8795. if (!groups) {
  8796. this.groupsData = null;
  8797. }
  8798. else if (groups instanceof DataSet || groups instanceof DataView) {
  8799. this.groupsData = groups;
  8800. }
  8801. else {
  8802. throw new TypeError('Data must be an instance of DataSet or DataView');
  8803. }
  8804. if (this.groupsData) {
  8805. // subscribe to new dataset
  8806. var id = this.id;
  8807. util.forEach(this.groupListeners, function (callback, event) {
  8808. me.groupsData.on(event, callback, id);
  8809. });
  8810. // draw all ms
  8811. ids = this.groupsData.getIds();
  8812. this._onAddGroups(ids);
  8813. }
  8814. // update the group holding all ungrouped items
  8815. this._updateUngrouped();
  8816. // update the order of all items in each group
  8817. this._order();
  8818. this.body.emitter.emit('change');
  8819. };
  8820. /**
  8821. * Get the current groups
  8822. * @returns {vis.DataSet | null} groups
  8823. */
  8824. ItemSet.prototype.getGroups = function() {
  8825. return this.groupsData;
  8826. };
  8827. /**
  8828. * Remove an item by its id
  8829. * @param {String | Number} id
  8830. */
  8831. ItemSet.prototype.removeItem = function(id) {
  8832. var item = this.itemsData.get(id),
  8833. dataset = this.itemsData.getDataSet();
  8834. if (item) {
  8835. // confirm deletion
  8836. this.options.onRemove(item, function (item) {
  8837. if (item) {
  8838. // remove by id here, it is possible that an item has no id defined
  8839. // itself, so better not delete by the item itself
  8840. dataset.remove(id);
  8841. }
  8842. });
  8843. }
  8844. };
  8845. /**
  8846. * Handle updated items
  8847. * @param {Number[]} ids
  8848. * @protected
  8849. */
  8850. ItemSet.prototype._onUpdate = function(ids) {
  8851. var me = this;
  8852. ids.forEach(function (id) {
  8853. var itemData = me.itemsData.get(id, me.itemOptions),
  8854. item = me.items[id],
  8855. type = itemData.type || me.options.type || (itemData.end ? 'range' : 'box');
  8856. var constructor = ItemSet.types[type];
  8857. if (item) {
  8858. // update item
  8859. if (!constructor || !(item instanceof constructor)) {
  8860. // item type has changed, delete the item and recreate it
  8861. me._removeItem(item);
  8862. item = null;
  8863. }
  8864. else {
  8865. me._updateItem(item, itemData);
  8866. }
  8867. }
  8868. if (!item) {
  8869. // create item
  8870. if (constructor) {
  8871. item = new constructor(itemData, me.conversion, me.options);
  8872. item.id = id; // TODO: not so nice setting id afterwards
  8873. me._addItem(item);
  8874. }
  8875. else if (type == 'rangeoverflow') {
  8876. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  8877. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  8878. '.vis.timeline .item.range .content {overflow: visible;}');
  8879. }
  8880. else {
  8881. throw new TypeError('Unknown item type "' + type + '"');
  8882. }
  8883. }
  8884. });
  8885. this._order();
  8886. this.stackDirty = true; // force re-stacking of all items next redraw
  8887. this.body.emitter.emit('change');
  8888. };
  8889. /**
  8890. * Handle added items
  8891. * @param {Number[]} ids
  8892. * @protected
  8893. */
  8894. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  8895. /**
  8896. * Handle removed items
  8897. * @param {Number[]} ids
  8898. * @protected
  8899. */
  8900. ItemSet.prototype._onRemove = function(ids) {
  8901. var count = 0;
  8902. var me = this;
  8903. ids.forEach(function (id) {
  8904. var item = me.items[id];
  8905. if (item) {
  8906. count++;
  8907. me._removeItem(item);
  8908. }
  8909. });
  8910. if (count) {
  8911. // update order
  8912. this._order();
  8913. this.stackDirty = true; // force re-stacking of all items next redraw
  8914. this.body.emitter.emit('change');
  8915. }
  8916. };
  8917. /**
  8918. * Update the order of item in all groups
  8919. * @private
  8920. */
  8921. ItemSet.prototype._order = function() {
  8922. // reorder the items in all groups
  8923. // TODO: optimization: only reorder groups affected by the changed items
  8924. util.forEach(this.groups, function (group) {
  8925. group.order();
  8926. });
  8927. };
  8928. /**
  8929. * Handle updated groups
  8930. * @param {Number[]} ids
  8931. * @private
  8932. */
  8933. ItemSet.prototype._onUpdateGroups = function(ids) {
  8934. this._onAddGroups(ids);
  8935. };
  8936. /**
  8937. * Handle changed groups
  8938. * @param {Number[]} ids
  8939. * @private
  8940. */
  8941. ItemSet.prototype._onAddGroups = function(ids) {
  8942. var me = this;
  8943. ids.forEach(function (id) {
  8944. var groupData = me.groupsData.get(id);
  8945. var group = me.groups[id];
  8946. if (!group) {
  8947. // check for reserved ids
  8948. if (id == UNGROUPED) {
  8949. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  8950. }
  8951. var groupOptions = Object.create(me.options);
  8952. util.extend(groupOptions, {
  8953. height: null
  8954. });
  8955. group = new Group(id, groupData, me);
  8956. me.groups[id] = group;
  8957. // add items with this groupId to the new group
  8958. for (var itemId in me.items) {
  8959. if (me.items.hasOwnProperty(itemId)) {
  8960. var item = me.items[itemId];
  8961. if (item.data.group == id) {
  8962. group.add(item);
  8963. }
  8964. }
  8965. }
  8966. group.order();
  8967. group.show();
  8968. }
  8969. else {
  8970. // update group
  8971. group.setData(groupData);
  8972. }
  8973. });
  8974. this.body.emitter.emit('change');
  8975. };
  8976. /**
  8977. * Handle removed groups
  8978. * @param {Number[]} ids
  8979. * @private
  8980. */
  8981. ItemSet.prototype._onRemoveGroups = function(ids) {
  8982. var groups = this.groups;
  8983. ids.forEach(function (id) {
  8984. var group = groups[id];
  8985. if (group) {
  8986. group.hide();
  8987. delete groups[id];
  8988. }
  8989. });
  8990. this.markDirty();
  8991. this.body.emitter.emit('change');
  8992. };
  8993. /**
  8994. * Reorder the groups if needed
  8995. * @return {boolean} changed
  8996. * @private
  8997. */
  8998. ItemSet.prototype._orderGroups = function () {
  8999. if (this.groupsData) {
  9000. // reorder the groups
  9001. var groupIds = this.groupsData.getIds({
  9002. order: this.options.groupOrder
  9003. });
  9004. var changed = !util.equalArray(groupIds, this.groupIds);
  9005. if (changed) {
  9006. // hide all groups, removes them from the DOM
  9007. var groups = this.groups;
  9008. groupIds.forEach(function (groupId) {
  9009. groups[groupId].hide();
  9010. });
  9011. // show the groups again, attach them to the DOM in correct order
  9012. groupIds.forEach(function (groupId) {
  9013. groups[groupId].show();
  9014. });
  9015. this.groupIds = groupIds;
  9016. }
  9017. return changed;
  9018. }
  9019. else {
  9020. return false;
  9021. }
  9022. };
  9023. /**
  9024. * Add a new item
  9025. * @param {Item} item
  9026. * @private
  9027. */
  9028. ItemSet.prototype._addItem = function(item) {
  9029. this.items[item.id] = item;
  9030. // add to group
  9031. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  9032. var group = this.groups[groupId];
  9033. if (group) group.add(item);
  9034. };
  9035. /**
  9036. * Update an existing item
  9037. * @param {Item} item
  9038. * @param {Object} itemData
  9039. * @private
  9040. */
  9041. ItemSet.prototype._updateItem = function(item, itemData) {
  9042. var oldGroupId = item.data.group;
  9043. item.data = itemData;
  9044. if (item.displayed) {
  9045. item.redraw();
  9046. }
  9047. // update group
  9048. if (oldGroupId != item.data.group) {
  9049. var oldGroup = this.groups[oldGroupId];
  9050. if (oldGroup) oldGroup.remove(item);
  9051. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  9052. var group = this.groups[groupId];
  9053. if (group) group.add(item);
  9054. }
  9055. };
  9056. /**
  9057. * Delete an item from the ItemSet: remove it from the DOM, from the map
  9058. * with items, and from the map with visible items, and from the selection
  9059. * @param {Item} item
  9060. * @private
  9061. */
  9062. ItemSet.prototype._removeItem = function(item) {
  9063. // remove from DOM
  9064. item.hide();
  9065. // remove from items
  9066. delete this.items[item.id];
  9067. // remove from selection
  9068. var index = this.selection.indexOf(item.id);
  9069. if (index != -1) this.selection.splice(index, 1);
  9070. // remove from group
  9071. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  9072. var group = this.groups[groupId];
  9073. if (group) group.remove(item);
  9074. };
  9075. /**
  9076. * Create an array containing all items being a range (having an end date)
  9077. * @param array
  9078. * @returns {Array}
  9079. * @private
  9080. */
  9081. ItemSet.prototype._constructByEndArray = function(array) {
  9082. var endArray = [];
  9083. for (var i = 0; i < array.length; i++) {
  9084. if (array[i] instanceof ItemRange) {
  9085. endArray.push(array[i]);
  9086. }
  9087. }
  9088. return endArray;
  9089. };
  9090. /**
  9091. * Register the clicked item on touch, before dragStart is initiated.
  9092. *
  9093. * dragStart is initiated from a mousemove event, which can have left the item
  9094. * already resulting in an item == null
  9095. *
  9096. * @param {Event} event
  9097. * @private
  9098. */
  9099. ItemSet.prototype._onTouch = function (event) {
  9100. // store the touched item, used in _onDragStart
  9101. this.touchParams.item = ItemSet.itemFromTarget(event);
  9102. };
  9103. /**
  9104. * Start dragging the selected events
  9105. * @param {Event} event
  9106. * @private
  9107. */
  9108. ItemSet.prototype._onDragStart = function (event) {
  9109. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  9110. return;
  9111. }
  9112. var item = this.touchParams.item || null,
  9113. me = this,
  9114. props;
  9115. if (item && item.selected) {
  9116. var dragLeftItem = event.target.dragLeftItem;
  9117. var dragRightItem = event.target.dragRightItem;
  9118. if (dragLeftItem) {
  9119. props = {
  9120. item: dragLeftItem
  9121. };
  9122. if (me.options.editable.updateTime) {
  9123. props.start = item.data.start.valueOf();
  9124. }
  9125. if (me.options.editable.updateGroup) {
  9126. if ('group' in item.data) props.group = item.data.group;
  9127. }
  9128. this.touchParams.itemProps = [props];
  9129. }
  9130. else if (dragRightItem) {
  9131. props = {
  9132. item: dragRightItem
  9133. };
  9134. if (me.options.editable.updateTime) {
  9135. props.end = item.data.end.valueOf();
  9136. }
  9137. if (me.options.editable.updateGroup) {
  9138. if ('group' in item.data) props.group = item.data.group;
  9139. }
  9140. this.touchParams.itemProps = [props];
  9141. }
  9142. else {
  9143. this.touchParams.itemProps = this.getSelection().map(function (id) {
  9144. var item = me.items[id];
  9145. var props = {
  9146. item: item
  9147. };
  9148. if (me.options.editable.updateTime) {
  9149. if ('start' in item.data) props.start = item.data.start.valueOf();
  9150. if ('end' in item.data) props.end = item.data.end.valueOf();
  9151. }
  9152. if (me.options.editable.updateGroup) {
  9153. if ('group' in item.data) props.group = item.data.group;
  9154. }
  9155. return props;
  9156. });
  9157. }
  9158. event.stopPropagation();
  9159. }
  9160. };
  9161. /**
  9162. * Drag selected items
  9163. * @param {Event} event
  9164. * @private
  9165. */
  9166. ItemSet.prototype._onDrag = function (event) {
  9167. if (this.touchParams.itemProps) {
  9168. var range = this.body.range,
  9169. snap = this.body.util.snap || null,
  9170. deltaX = event.gesture.deltaX,
  9171. scale = (this.props.width / (range.end - range.start)),
  9172. offset = deltaX / scale;
  9173. // move
  9174. this.touchParams.itemProps.forEach(function (props) {
  9175. if ('start' in props) {
  9176. var start = new Date(props.start + offset);
  9177. props.item.data.start = snap ? snap(start) : start;
  9178. }
  9179. if ('end' in props) {
  9180. var end = new Date(props.end + offset);
  9181. props.item.data.end = snap ? snap(end) : end;
  9182. }
  9183. if ('group' in props) {
  9184. // drag from one group to another
  9185. var group = ItemSet.groupFromTarget(event);
  9186. if (group && group.groupId != props.item.data.group) {
  9187. var oldGroup = props.item.parent;
  9188. oldGroup.remove(props.item);
  9189. oldGroup.order();
  9190. group.add(props.item);
  9191. group.order();
  9192. props.item.data.group = group.groupId;
  9193. }
  9194. }
  9195. });
  9196. // TODO: implement onMoving handler
  9197. this.stackDirty = true; // force re-stacking of all items next redraw
  9198. this.body.emitter.emit('change');
  9199. event.stopPropagation();
  9200. }
  9201. };
  9202. /**
  9203. * End of dragging selected items
  9204. * @param {Event} event
  9205. * @private
  9206. */
  9207. ItemSet.prototype._onDragEnd = function (event) {
  9208. if (this.touchParams.itemProps) {
  9209. // prepare a change set for the changed items
  9210. var changes = [],
  9211. me = this,
  9212. dataset = this.itemsData.getDataSet();
  9213. this.touchParams.itemProps.forEach(function (props) {
  9214. var id = props.item.id,
  9215. itemData = me.itemsData.get(id, me.itemOptions);
  9216. var changed = false;
  9217. if ('start' in props.item.data) {
  9218. changed = (props.start != props.item.data.start.valueOf());
  9219. itemData.start = util.convert(props.item.data.start,
  9220. dataset._options.type && dataset._options.type.start || 'Date');
  9221. }
  9222. if ('end' in props.item.data) {
  9223. changed = changed || (props.end != props.item.data.end.valueOf());
  9224. itemData.end = util.convert(props.item.data.end,
  9225. dataset._options.type && dataset._options.type.end || 'Date');
  9226. }
  9227. if ('group' in props.item.data) {
  9228. changed = changed || (props.group != props.item.data.group);
  9229. itemData.group = props.item.data.group;
  9230. }
  9231. // only apply changes when start or end is actually changed
  9232. if (changed) {
  9233. me.options.onMove(itemData, function (itemData) {
  9234. if (itemData) {
  9235. // apply changes
  9236. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  9237. changes.push(itemData);
  9238. }
  9239. else {
  9240. // restore original values
  9241. if ('start' in props) props.item.data.start = props.start;
  9242. if ('end' in props) props.item.data.end = props.end;
  9243. me.stackDirty = true; // force re-stacking of all items next redraw
  9244. me.body.emitter.emit('change');
  9245. }
  9246. });
  9247. }
  9248. });
  9249. this.touchParams.itemProps = null;
  9250. // apply the changes to the data (if there are changes)
  9251. if (changes.length) {
  9252. dataset.update(changes);
  9253. }
  9254. event.stopPropagation();
  9255. }
  9256. };
  9257. /**
  9258. * Handle selecting/deselecting an item when tapping it
  9259. * @param {Event} event
  9260. * @private
  9261. */
  9262. ItemSet.prototype._onSelectItem = function (event) {
  9263. if (!this.options.selectable) return;
  9264. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  9265. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  9266. if (ctrlKey || shiftKey) {
  9267. this._onMultiSelectItem(event);
  9268. return;
  9269. }
  9270. var oldSelection = this.getSelection();
  9271. var item = ItemSet.itemFromTarget(event);
  9272. var selection = item ? [item.id] : [];
  9273. this.setSelection(selection);
  9274. var newSelection = this.getSelection();
  9275. // emit a select event,
  9276. // except when old selection is empty and new selection is still empty
  9277. if (newSelection.length > 0 || oldSelection.length > 0) {
  9278. this.body.emitter.emit('select', {
  9279. items: this.getSelection()
  9280. });
  9281. }
  9282. event.stopPropagation();
  9283. };
  9284. /**
  9285. * Handle creation and updates of an item on double tap
  9286. * @param event
  9287. * @private
  9288. */
  9289. ItemSet.prototype._onAddItem = function (event) {
  9290. if (!this.options.selectable) return;
  9291. if (!this.options.editable.add) return;
  9292. var me = this,
  9293. snap = this.body.util.snap || null,
  9294. item = ItemSet.itemFromTarget(event);
  9295. if (item) {
  9296. // update item
  9297. // execute async handler to update the item (or cancel it)
  9298. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  9299. this.options.onUpdate(itemData, function (itemData) {
  9300. if (itemData) {
  9301. me.itemsData.update(itemData);
  9302. }
  9303. });
  9304. }
  9305. else {
  9306. // add item
  9307. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  9308. var x = event.gesture.center.pageX - xAbs;
  9309. var start = this.body.util.toTime(x);
  9310. var newItem = {
  9311. start: snap ? snap(start) : start,
  9312. content: 'new item'
  9313. };
  9314. // when default type is a range, add a default end date to the new item
  9315. if (this.options.type === 'range') {
  9316. var end = this.body.util.toTime(x + this.props.width / 5);
  9317. newItem.end = snap ? snap(end) : end;
  9318. }
  9319. newItem[this.itemsData.fieldId] = util.randomUUID();
  9320. var group = ItemSet.groupFromTarget(event);
  9321. if (group) {
  9322. newItem.group = group.groupId;
  9323. }
  9324. // execute async handler to customize (or cancel) adding an item
  9325. this.options.onAdd(newItem, function (item) {
  9326. if (item) {
  9327. me.itemsData.add(newItem);
  9328. // TODO: need to trigger a redraw?
  9329. }
  9330. });
  9331. }
  9332. };
  9333. /**
  9334. * Handle selecting/deselecting multiple items when holding an item
  9335. * @param {Event} event
  9336. * @private
  9337. */
  9338. ItemSet.prototype._onMultiSelectItem = function (event) {
  9339. if (!this.options.selectable) return;
  9340. var selection,
  9341. item = ItemSet.itemFromTarget(event);
  9342. if (item) {
  9343. // multi select items
  9344. selection = this.getSelection(); // current selection
  9345. var index = selection.indexOf(item.id);
  9346. if (index == -1) {
  9347. // item is not yet selected -> select it
  9348. selection.push(item.id);
  9349. }
  9350. else {
  9351. // item is already selected -> deselect it
  9352. selection.splice(index, 1);
  9353. }
  9354. this.setSelection(selection);
  9355. this.body.emitter.emit('select', {
  9356. items: this.getSelection()
  9357. });
  9358. event.stopPropagation();
  9359. }
  9360. };
  9361. /**
  9362. * Find an item from an event target:
  9363. * searches for the attribute 'timeline-item' in the event target's element tree
  9364. * @param {Event} event
  9365. * @return {Item | null} item
  9366. */
  9367. ItemSet.itemFromTarget = function(event) {
  9368. var target = event.target;
  9369. while (target) {
  9370. if (target.hasOwnProperty('timeline-item')) {
  9371. return target['timeline-item'];
  9372. }
  9373. target = target.parentNode;
  9374. }
  9375. return null;
  9376. };
  9377. /**
  9378. * Find the Group from an event target:
  9379. * searches for the attribute 'timeline-group' in the event target's element tree
  9380. * @param {Event} event
  9381. * @return {Group | null} group
  9382. */
  9383. ItemSet.groupFromTarget = function(event) {
  9384. var target = event.target;
  9385. while (target) {
  9386. if (target.hasOwnProperty('timeline-group')) {
  9387. return target['timeline-group'];
  9388. }
  9389. target = target.parentNode;
  9390. }
  9391. return null;
  9392. };
  9393. /**
  9394. * Find the ItemSet from an event target:
  9395. * searches for the attribute 'timeline-itemset' in the event target's element tree
  9396. * @param {Event} event
  9397. * @return {ItemSet | null} item
  9398. */
  9399. ItemSet.itemSetFromTarget = function(event) {
  9400. var target = event.target;
  9401. while (target) {
  9402. if (target.hasOwnProperty('timeline-itemset')) {
  9403. return target['timeline-itemset'];
  9404. }
  9405. target = target.parentNode;
  9406. }
  9407. return null;
  9408. };
  9409. module.exports = ItemSet;
  9410. /***/ },
  9411. /* 25 */
  9412. /***/ function(module, exports, __webpack_require__) {
  9413. var util = __webpack_require__(1);
  9414. var DOMutil = __webpack_require__(2);
  9415. var Component = __webpack_require__(18);
  9416. /**
  9417. * Legend for Graph2d
  9418. */
  9419. function Legend(body, options, side) {
  9420. this.body = body;
  9421. this.defaultOptions = {
  9422. enabled: true,
  9423. icons: true,
  9424. iconSize: 20,
  9425. iconSpacing: 6,
  9426. left: {
  9427. visible: true,
  9428. position: 'top-left' // top/bottom - left,center,right
  9429. },
  9430. right: {
  9431. visible: true,
  9432. position: 'top-left' // top/bottom - left,center,right
  9433. }
  9434. }
  9435. this.side = side;
  9436. this.options = util.extend({},this.defaultOptions);
  9437. this.svgElements = {};
  9438. this.dom = {};
  9439. this.groups = {};
  9440. this.amountOfGroups = 0;
  9441. this._create();
  9442. this.setOptions(options);
  9443. }
  9444. Legend.prototype = new Component();
  9445. Legend.prototype.addGroup = function(label, graphOptions) {
  9446. if (!this.groups.hasOwnProperty(label)) {
  9447. this.groups[label] = graphOptions;
  9448. }
  9449. this.amountOfGroups += 1;
  9450. };
  9451. Legend.prototype.updateGroup = function(label, graphOptions) {
  9452. this.groups[label] = graphOptions;
  9453. };
  9454. Legend.prototype.removeGroup = function(label) {
  9455. if (this.groups.hasOwnProperty(label)) {
  9456. delete this.groups[label];
  9457. this.amountOfGroups -= 1;
  9458. }
  9459. };
  9460. Legend.prototype._create = function() {
  9461. this.dom.frame = document.createElement('div');
  9462. this.dom.frame.className = 'legend';
  9463. this.dom.frame.style.position = "absolute";
  9464. this.dom.frame.style.top = "10px";
  9465. this.dom.frame.style.display = "block";
  9466. this.dom.textArea = document.createElement('div');
  9467. this.dom.textArea.className = 'legendText';
  9468. this.dom.textArea.style.position = "relative";
  9469. this.dom.textArea.style.top = "0px";
  9470. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  9471. this.svg.style.position = 'absolute';
  9472. this.svg.style.top = 0 +'px';
  9473. this.svg.style.width = this.options.iconSize + 5 + 'px';
  9474. this.dom.frame.appendChild(this.svg);
  9475. this.dom.frame.appendChild(this.dom.textArea);
  9476. };
  9477. /**
  9478. * Hide the component from the DOM
  9479. */
  9480. Legend.prototype.hide = function() {
  9481. // remove the frame containing the items
  9482. if (this.dom.frame.parentNode) {
  9483. this.dom.frame.parentNode.removeChild(this.dom.frame);
  9484. }
  9485. };
  9486. /**
  9487. * Show the component in the DOM (when not already visible).
  9488. * @return {Boolean} changed
  9489. */
  9490. Legend.prototype.show = function() {
  9491. // show frame containing the items
  9492. if (!this.dom.frame.parentNode) {
  9493. this.body.dom.center.appendChild(this.dom.frame);
  9494. }
  9495. };
  9496. Legend.prototype.setOptions = function(options) {
  9497. var fields = ['enabled','orientation','icons','left','right'];
  9498. util.selectiveDeepExtend(fields, this.options, options);
  9499. };
  9500. Legend.prototype.redraw = function() {
  9501. var activeGroups = 0;
  9502. for (var groupId in this.groups) {
  9503. if (this.groups.hasOwnProperty(groupId)) {
  9504. if (this.groups[groupId].visible == true) {
  9505. activeGroups++;
  9506. }
  9507. }
  9508. }
  9509. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  9510. this.hide();
  9511. }
  9512. else {
  9513. this.show();
  9514. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  9515. this.dom.frame.style.left = '4px';
  9516. this.dom.frame.style.textAlign = "left";
  9517. this.dom.textArea.style.textAlign = "left";
  9518. this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px';
  9519. this.dom.textArea.style.right = '';
  9520. this.svg.style.left = 0 +'px';
  9521. this.svg.style.right = '';
  9522. }
  9523. else {
  9524. this.dom.frame.style.right = '4px';
  9525. this.dom.frame.style.textAlign = "right";
  9526. this.dom.textArea.style.textAlign = "right";
  9527. this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px';
  9528. this.dom.textArea.style.left = '';
  9529. this.svg.style.right = 0 +'px';
  9530. this.svg.style.left = '';
  9531. }
  9532. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  9533. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  9534. this.dom.frame.style.bottom = '';
  9535. }
  9536. else {
  9537. this.dom.frame.style.bottom = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  9538. this.dom.frame.style.top = '';
  9539. }
  9540. if (this.options.icons == false) {
  9541. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  9542. this.dom.textArea.style.right = '';
  9543. this.dom.textArea.style.left = '';
  9544. this.svg.style.width = '0px';
  9545. }
  9546. else {
  9547. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'
  9548. this.drawLegendIcons();
  9549. }
  9550. var content = '';
  9551. for (var groupId in this.groups) {
  9552. if (this.groups.hasOwnProperty(groupId)) {
  9553. if (this.groups[groupId].visible == true) {
  9554. content += this.groups[groupId].content + '<br />';
  9555. }
  9556. }
  9557. }
  9558. this.dom.textArea.innerHTML = content;
  9559. this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px';
  9560. }
  9561. };
  9562. Legend.prototype.drawLegendIcons = function() {
  9563. if (this.dom.frame.parentNode) {
  9564. DOMutil.prepareElements(this.svgElements);
  9565. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  9566. var iconOffset = Number(padding.replace('px',''));
  9567. var x = iconOffset;
  9568. var iconWidth = this.options.iconSize;
  9569. var iconHeight = 0.75 * this.options.iconSize;
  9570. var y = iconOffset + 0.5 * iconHeight + 3;
  9571. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  9572. for (var groupId in this.groups) {
  9573. if (this.groups.hasOwnProperty(groupId)) {
  9574. if (this.groups[groupId].visible == true) {
  9575. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  9576. y += iconHeight + this.options.iconSpacing;
  9577. }
  9578. }
  9579. }
  9580. DOMutil.cleanupElements(this.svgElements);
  9581. }
  9582. };
  9583. module.exports = Legend;
  9584. /***/ },
  9585. /* 26 */
  9586. /***/ function(module, exports, __webpack_require__) {
  9587. var util = __webpack_require__(1);
  9588. var DOMutil = __webpack_require__(2);
  9589. var DataSet = __webpack_require__(3);
  9590. var DataView = __webpack_require__(4);
  9591. var Component = __webpack_require__(18);
  9592. var DataAxis = __webpack_require__(21);
  9593. var GraphGroup = __webpack_require__(22);
  9594. var Legend = __webpack_require__(25);
  9595. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  9596. /**
  9597. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  9598. *
  9599. * @param body
  9600. * @param options
  9601. * @constructor
  9602. */
  9603. function LineGraph(body, options) {
  9604. this.id = util.randomUUID();
  9605. this.body = body;
  9606. this.defaultOptions = {
  9607. yAxisOrientation: 'left',
  9608. defaultGroup: 'default',
  9609. sort: true,
  9610. sampling: true,
  9611. graphHeight: '400px',
  9612. shaded: {
  9613. enabled: false,
  9614. orientation: 'bottom' // top, bottom
  9615. },
  9616. style: 'line', // line, bar
  9617. barChart: {
  9618. width: 50,
  9619. align: 'center' // left, center, right
  9620. },
  9621. catmullRom: {
  9622. enabled: true,
  9623. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  9624. alpha: 0.5
  9625. },
  9626. drawPoints: {
  9627. enabled: true,
  9628. size: 6,
  9629. style: 'square' // square, circle
  9630. },
  9631. dataAxis: {
  9632. showMinorLabels: true,
  9633. showMajorLabels: true,
  9634. icons: false,
  9635. width: '40px',
  9636. visible: true
  9637. },
  9638. legend: {
  9639. enabled: false,
  9640. icons: true,
  9641. left: {
  9642. visible: true,
  9643. position: 'top-left' // top/bottom - left,right
  9644. },
  9645. right: {
  9646. visible: true,
  9647. position: 'top-right' // top/bottom - left,right
  9648. }
  9649. }
  9650. };
  9651. // options is shared by this ItemSet and all its items
  9652. this.options = util.extend({}, this.defaultOptions);
  9653. this.dom = {};
  9654. this.props = {};
  9655. this.hammer = null;
  9656. this.groups = {};
  9657. var me = this;
  9658. this.itemsData = null; // DataSet
  9659. this.groupsData = null; // DataSet
  9660. // listeners for the DataSet of the items
  9661. this.itemListeners = {
  9662. 'add': function (event, params, senderId) {
  9663. me._onAdd(params.items);
  9664. },
  9665. 'update': function (event, params, senderId) {
  9666. me._onUpdate(params.items);
  9667. },
  9668. 'remove': function (event, params, senderId) {
  9669. me._onRemove(params.items);
  9670. }
  9671. };
  9672. // listeners for the DataSet of the groups
  9673. this.groupListeners = {
  9674. 'add': function (event, params, senderId) {
  9675. me._onAddGroups(params.items);
  9676. },
  9677. 'update': function (event, params, senderId) {
  9678. me._onUpdateGroups(params.items);
  9679. },
  9680. 'remove': function (event, params, senderId) {
  9681. me._onRemoveGroups(params.items);
  9682. }
  9683. };
  9684. this.items = {}; // object with an Item for every data item
  9685. this.selection = []; // list with the ids of all selected nodes
  9686. this.lastStart = this.body.range.start;
  9687. this.touchParams = {}; // stores properties while dragging
  9688. this.svgElements = {};
  9689. this.setOptions(options);
  9690. this.groupsUsingDefaultStyles = [0];
  9691. this.body.emitter.on("rangechange",function() {
  9692. if (me.lastStart != 0) {
  9693. var offset = me.body.range.start - me.lastStart;
  9694. var range = me.body.range.end - me.body.range.start;
  9695. if (me.width != 0) {
  9696. var rangePerPixelInv = me.width/range;
  9697. var xOffset = offset * rangePerPixelInv;
  9698. me.svg.style.left = (-me.width - xOffset) + "px";
  9699. }
  9700. }
  9701. });
  9702. this.body.emitter.on("rangechanged", function() {
  9703. me.lastStart = me.body.range.start;
  9704. me.svg.style.left = util.option.asSize(-me.width);
  9705. me._updateGraph.apply(me);
  9706. });
  9707. // create the HTML DOM
  9708. this._create();
  9709. this.body.emitter.emit("change");
  9710. }
  9711. LineGraph.prototype = new Component();
  9712. /**
  9713. * Create the HTML DOM for the ItemSet
  9714. */
  9715. LineGraph.prototype._create = function(){
  9716. var frame = document.createElement('div');
  9717. frame.className = 'LineGraph';
  9718. this.dom.frame = frame;
  9719. // create svg element for graph drawing.
  9720. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  9721. this.svg.style.position = "relative";
  9722. this.svg.style.height = ('' + this.options.graphHeight).replace("px",'') + 'px';
  9723. this.svg.style.display = "block";
  9724. frame.appendChild(this.svg);
  9725. // data axis
  9726. this.options.dataAxis.orientation = 'left';
  9727. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg);
  9728. this.options.dataAxis.orientation = 'right';
  9729. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg);
  9730. delete this.options.dataAxis.orientation;
  9731. // legends
  9732. this.legendLeft = new Legend(this.body, this.options.legend, 'left');
  9733. this.legendRight = new Legend(this.body, this.options.legend, 'right');
  9734. this.show();
  9735. };
  9736. /**
  9737. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  9738. * @param options
  9739. */
  9740. LineGraph.prototype.setOptions = function(options) {
  9741. if (options) {
  9742. var fields = ['sampling','defaultGroup','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort'];
  9743. util.selectiveDeepExtend(fields, this.options, options);
  9744. util.mergeOptions(this.options, options,'catmullRom');
  9745. util.mergeOptions(this.options, options,'drawPoints');
  9746. util.mergeOptions(this.options, options,'shaded');
  9747. util.mergeOptions(this.options, options,'legend');
  9748. if (options.catmullRom) {
  9749. if (typeof options.catmullRom == 'object') {
  9750. if (options.catmullRom.parametrization) {
  9751. if (options.catmullRom.parametrization == 'uniform') {
  9752. this.options.catmullRom.alpha = 0;
  9753. }
  9754. else if (options.catmullRom.parametrization == 'chordal') {
  9755. this.options.catmullRom.alpha = 1.0;
  9756. }
  9757. else {
  9758. this.options.catmullRom.parametrization = 'centripetal';
  9759. this.options.catmullRom.alpha = 0.5;
  9760. }
  9761. }
  9762. }
  9763. }
  9764. if (this.yAxisLeft) {
  9765. if (options.dataAxis !== undefined) {
  9766. this.yAxisLeft.setOptions(this.options.dataAxis);
  9767. this.yAxisRight.setOptions(this.options.dataAxis);
  9768. }
  9769. }
  9770. if (this.legendLeft) {
  9771. if (options.legend !== undefined) {
  9772. this.legendLeft.setOptions(this.options.legend);
  9773. this.legendRight.setOptions(this.options.legend);
  9774. }
  9775. }
  9776. if (this.groups.hasOwnProperty(UNGROUPED)) {
  9777. this.groups[UNGROUPED].setOptions(options);
  9778. }
  9779. }
  9780. if (this.dom.frame) {
  9781. this._updateGraph();
  9782. }
  9783. };
  9784. /**
  9785. * Hide the component from the DOM
  9786. */
  9787. LineGraph.prototype.hide = function() {
  9788. // remove the frame containing the items
  9789. if (this.dom.frame.parentNode) {
  9790. this.dom.frame.parentNode.removeChild(this.dom.frame);
  9791. }
  9792. };
  9793. /**
  9794. * Show the component in the DOM (when not already visible).
  9795. * @return {Boolean} changed
  9796. */
  9797. LineGraph.prototype.show = function() {
  9798. // show frame containing the items
  9799. if (!this.dom.frame.parentNode) {
  9800. this.body.dom.center.appendChild(this.dom.frame);
  9801. }
  9802. };
  9803. /**
  9804. * Set items
  9805. * @param {vis.DataSet | null} items
  9806. */
  9807. LineGraph.prototype.setItems = function(items) {
  9808. var me = this,
  9809. ids,
  9810. oldItemsData = this.itemsData;
  9811. // replace the dataset
  9812. if (!items) {
  9813. this.itemsData = null;
  9814. }
  9815. else if (items instanceof DataSet || items instanceof DataView) {
  9816. this.itemsData = items;
  9817. }
  9818. else {
  9819. throw new TypeError('Data must be an instance of DataSet or DataView');
  9820. }
  9821. if (oldItemsData) {
  9822. // unsubscribe from old dataset
  9823. util.forEach(this.itemListeners, function (callback, event) {
  9824. oldItemsData.off(event, callback);
  9825. });
  9826. // remove all drawn items
  9827. ids = oldItemsData.getIds();
  9828. this._onRemove(ids);
  9829. }
  9830. if (this.itemsData) {
  9831. // subscribe to new dataset
  9832. var id = this.id;
  9833. util.forEach(this.itemListeners, function (callback, event) {
  9834. me.itemsData.on(event, callback, id);
  9835. });
  9836. // add all new items
  9837. ids = this.itemsData.getIds();
  9838. this._onAdd(ids);
  9839. }
  9840. this._updateUngrouped();
  9841. this._updateGraph();
  9842. this.redraw();
  9843. };
  9844. /**
  9845. * Set groups
  9846. * @param {vis.DataSet} groups
  9847. */
  9848. LineGraph.prototype.setGroups = function(groups) {
  9849. var me = this,
  9850. ids;
  9851. // unsubscribe from current dataset
  9852. if (this.groupsData) {
  9853. util.forEach(this.groupListeners, function (callback, event) {
  9854. me.groupsData.unsubscribe(event, callback);
  9855. });
  9856. // remove all drawn groups
  9857. ids = this.groupsData.getIds();
  9858. this.groupsData = null;
  9859. this._onRemoveGroups(ids); // note: this will cause a redraw
  9860. }
  9861. // replace the dataset
  9862. if (!groups) {
  9863. this.groupsData = null;
  9864. }
  9865. else if (groups instanceof DataSet || groups instanceof DataView) {
  9866. this.groupsData = groups;
  9867. }
  9868. else {
  9869. throw new TypeError('Data must be an instance of DataSet or DataView');
  9870. }
  9871. if (this.groupsData) {
  9872. // subscribe to new dataset
  9873. var id = this.id;
  9874. util.forEach(this.groupListeners, function (callback, event) {
  9875. me.groupsData.on(event, callback, id);
  9876. });
  9877. // draw all ms
  9878. ids = this.groupsData.getIds();
  9879. this._onAddGroups(ids);
  9880. }
  9881. this._onUpdate();
  9882. };
  9883. LineGraph.prototype._onUpdate = function(ids) {
  9884. this._updateUngrouped();
  9885. this._updateAllGroupData();
  9886. this._updateGraph();
  9887. this.redraw();
  9888. };
  9889. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  9890. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  9891. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  9892. for (var i = 0; i < groupIds.length; i++) {
  9893. var group = this.groupsData.get(groupIds[i]);
  9894. this._updateGroup(group, groupIds[i]);
  9895. }
  9896. this._updateGraph();
  9897. this.redraw();
  9898. };
  9899. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  9900. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  9901. for (var i = 0; i < groupIds.length; i++) {
  9902. if (!this.groups.hasOwnProperty(groupIds[i])) {
  9903. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  9904. this.yAxisRight.removeGroup(groupIds[i]);
  9905. this.legendRight.removeGroup(groupIds[i]);
  9906. this.legendRight.redraw();
  9907. }
  9908. else {
  9909. this.yAxisLeft.removeGroup(groupIds[i]);
  9910. this.legendLeft.removeGroup(groupIds[i]);
  9911. this.legendLeft.redraw();
  9912. }
  9913. delete this.groups[groupIds[i]];
  9914. }
  9915. }
  9916. this._updateUngrouped();
  9917. this._updateGraph();
  9918. this.redraw();
  9919. };
  9920. /**
  9921. * update a group object
  9922. *
  9923. * @param group
  9924. * @param groupId
  9925. * @private
  9926. */
  9927. LineGraph.prototype._updateGroup = function (group, groupId) {
  9928. if (!this.groups.hasOwnProperty(groupId)) {
  9929. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  9930. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  9931. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  9932. this.legendRight.addGroup(groupId, this.groups[groupId]);
  9933. }
  9934. else {
  9935. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  9936. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  9937. }
  9938. }
  9939. else {
  9940. this.groups[groupId].update(group);
  9941. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  9942. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  9943. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  9944. }
  9945. else {
  9946. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  9947. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  9948. }
  9949. }
  9950. this.legendLeft.redraw();
  9951. this.legendRight.redraw();
  9952. };
  9953. LineGraph.prototype._updateAllGroupData = function () {
  9954. if (this.itemsData != null) {
  9955. var groupsContent = {};
  9956. for (var groupId in this.groups) {
  9957. if (this.groups.hasOwnProperty(groupId)) {
  9958. groupsContent[groupId] = [];
  9959. }
  9960. }
  9961. for (var itemId in this.itemsData._data) {
  9962. if (this.itemsData._data.hasOwnProperty(itemId)) {
  9963. var item = this.itemsData._data[itemId];
  9964. item.x = util.convert(item.x,"Date");
  9965. groupsContent[item.group].push(item);
  9966. }
  9967. }
  9968. for (var groupId in this.groups) {
  9969. if (this.groups.hasOwnProperty(groupId)) {
  9970. this.groups[groupId].setItems(groupsContent[groupId]);
  9971. }
  9972. }
  9973. }
  9974. };
  9975. /**
  9976. * Create or delete the group holding all ungrouped items. This group is used when
  9977. * there are no groups specified. This anonymous group is called 'graph'.
  9978. * @protected
  9979. */
  9980. LineGraph.prototype._updateUngrouped = function() {
  9981. if (this.itemsData != null) {
  9982. // var t0 = new Date();
  9983. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  9984. this._updateGroup(group, UNGROUPED);
  9985. var ungroupedCounter = 0;
  9986. if (this.itemsData) {
  9987. for (var itemId in this.itemsData._data) {
  9988. if (this.itemsData._data.hasOwnProperty(itemId)) {
  9989. var item = this.itemsData._data[itemId];
  9990. if (item != undefined) {
  9991. if (item.hasOwnProperty('group')) {
  9992. if (item.group === undefined) {
  9993. item.group = UNGROUPED;
  9994. }
  9995. }
  9996. else {
  9997. item.group = UNGROUPED;
  9998. }
  9999. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  10000. }
  10001. }
  10002. }
  10003. }
  10004. // much much slower
  10005. // var datapoints = this.itemsData.get({
  10006. // filter: function (item) {return item.group === undefined;},
  10007. // showInternalIds:true
  10008. // });
  10009. // if (datapoints.length > 0) {
  10010. // var updateQuery = [];
  10011. // for (var i = 0; i < datapoints.length; i++) {
  10012. // updateQuery.push({id:datapoints[i].id, group: UNGROUPED});
  10013. // }
  10014. // this.itemsData.update(updateQuery, true);
  10015. // }
  10016. // var t1 = new Date();
  10017. // var pointInUNGROUPED = this.itemsData.get({filter: function (item) {return item.group == UNGROUPED;}});
  10018. if (ungroupedCounter == 0) {
  10019. delete this.groups[UNGROUPED];
  10020. this.legendLeft.removeGroup(UNGROUPED);
  10021. this.legendRight.removeGroup(UNGROUPED);
  10022. this.yAxisLeft.removeGroup(UNGROUPED);
  10023. this.yAxisRight.removeGroup(UNGROUPED);
  10024. }
  10025. // console.log("getting amount ungrouped",new Date() - t1);
  10026. // console.log("putting in ungrouped",new Date() - t0);
  10027. }
  10028. else {
  10029. delete this.groups[UNGROUPED];
  10030. this.legendLeft.removeGroup(UNGROUPED);
  10031. this.legendRight.removeGroup(UNGROUPED);
  10032. this.yAxisLeft.removeGroup(UNGROUPED);
  10033. this.yAxisRight.removeGroup(UNGROUPED);
  10034. }
  10035. this.legendLeft.redraw();
  10036. this.legendRight.redraw();
  10037. };
  10038. /**
  10039. * Redraw the component, mandatory function
  10040. * @return {boolean} Returns true if the component is resized
  10041. */
  10042. LineGraph.prototype.redraw = function() {
  10043. var resized = false;
  10044. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  10045. if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) {
  10046. resized = true;
  10047. }
  10048. // check if this component is resized
  10049. resized = this._isResized() || resized;
  10050. // check whether zoomed (in that case we need to re-stack everything)
  10051. var visibleInterval = this.body.range.end - this.body.range.start;
  10052. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  10053. this.lastVisibleInterval = visibleInterval;
  10054. this.lastWidth = this.width;
  10055. // calculate actual size and position
  10056. this.width = this.dom.frame.offsetWidth;
  10057. // the svg element is three times as big as the width, this allows for fully dragging left and right
  10058. // without reloading the graph. the controls for this are bound to events in the constructor
  10059. if (resized == true) {
  10060. this.svg.style.width = util.option.asSize(3*this.width);
  10061. this.svg.style.left = util.option.asSize(-this.width);
  10062. }
  10063. if (zoomed == true) {
  10064. this._updateGraph();
  10065. }
  10066. this.legendLeft.redraw();
  10067. this.legendRight.redraw();
  10068. return resized;
  10069. };
  10070. /**
  10071. * Update and redraw the graph.
  10072. *
  10073. */
  10074. LineGraph.prototype._updateGraph = function () {
  10075. // reset the svg elements
  10076. DOMutil.prepareElements(this.svgElements);
  10077. if (this.width != 0 && this.itemsData != null) {
  10078. var group, groupData, preprocessedGroup, i;
  10079. var preprocessedGroupData = [];
  10080. var processedGroupData = [];
  10081. var groupRanges = [];
  10082. var changeCalled = false;
  10083. // getting group Ids
  10084. var groupIds = [];
  10085. for (var groupId in this.groups) {
  10086. if (this.groups.hasOwnProperty(groupId)) {
  10087. groupIds.push(groupId);
  10088. }
  10089. }
  10090. // this is the range of the SVG canvas
  10091. var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width);
  10092. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  10093. // first select and preprocess the data from the datasets.
  10094. // the groups have their preselection of data, we now loop over this data to see
  10095. // what data we need to draw. Sorted data is much faster.
  10096. // more optimization is possible by doing the sampling before and using the binary search
  10097. // to find the end date to determine the increment.
  10098. if (groupIds.length > 0) {
  10099. for (i = 0; i < groupIds.length; i++) {
  10100. group = this.groups[groupIds[i]];
  10101. if (group.visible == true) {
  10102. groupData = [];
  10103. // optimization for sorted data
  10104. if (group.options.sort == true) {
  10105. var guess = Math.max(0,util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before'));
  10106. for (var j = guess; j < group.itemsData.length; j++) {
  10107. var item = group.itemsData[j];
  10108. if (item !== undefined) {
  10109. if (item.x > maxDate) {
  10110. groupData.push(item);
  10111. break;
  10112. }
  10113. else {
  10114. groupData.push(item);
  10115. }
  10116. }
  10117. }
  10118. }
  10119. else {
  10120. for (var j = 0; j < group.itemsData.length; j++) {
  10121. var item = group.itemsData[j];
  10122. if (item !== undefined) {
  10123. if (item.x > minDate && item.x < maxDate) {
  10124. groupData.push(item);
  10125. }
  10126. }
  10127. }
  10128. }
  10129. // preprocess, split into ranges and data
  10130. if (groupData.length > 0) {
  10131. preprocessedGroup = this._preprocessData(groupData, group);
  10132. groupRanges.push({min: preprocessedGroup.min, max: preprocessedGroup.max});
  10133. preprocessedGroupData.push(preprocessedGroup.data);
  10134. }
  10135. else {
  10136. groupRanges.push({});
  10137. preprocessedGroupData.push([]);
  10138. }
  10139. }
  10140. else {
  10141. groupRanges.push({});
  10142. preprocessedGroupData.push([]);
  10143. }
  10144. }
  10145. // update the Y axis first, we use this data to draw at the correct Y points
  10146. // changeCalled is required to clean the SVG on a change emit.
  10147. changeCalled = this._updateYAxis(groupIds, groupRanges);
  10148. if (changeCalled == true) {
  10149. DOMutil.cleanupElements(this.svgElements);
  10150. this.body.emitter.emit("change");
  10151. return;
  10152. }
  10153. // with the yAxis scaled correctly, use this to get the Y values of the points.
  10154. for (i = 0; i < groupIds.length; i++) {
  10155. group = this.groups[groupIds[i]];
  10156. processedGroupData.push(this._convertYvalues(preprocessedGroupData[i],group))
  10157. }
  10158. // draw the groups
  10159. for (i = 0; i < groupIds.length; i++) {
  10160. group = this.groups[groupIds[i]];
  10161. if (group.visible == true) {
  10162. if (group.options.style == 'line') {
  10163. this._drawLineGraph(processedGroupData[i], group);
  10164. }
  10165. else {
  10166. this._drawBarGraph (processedGroupData[i], group);
  10167. }
  10168. }
  10169. }
  10170. }
  10171. }
  10172. // cleanup unused svg elements
  10173. DOMutil.cleanupElements(this.svgElements);
  10174. };
  10175. /**
  10176. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  10177. * @param {array} groupIds
  10178. * @private
  10179. */
  10180. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  10181. var changeCalled = false;
  10182. var yAxisLeftUsed = false;
  10183. var yAxisRightUsed = false;
  10184. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  10185. var orientation = 'left';
  10186. // if groups are present
  10187. if (groupIds.length > 0) {
  10188. for (var i = 0; i < groupIds.length; i++) {
  10189. orientation = 'left';
  10190. var group = this.groups[groupIds[i]];
  10191. if (group.visible == true) {
  10192. if (group.options.yAxisOrientation == 'right') {
  10193. orientation = 'right';
  10194. }
  10195. minVal = groupRanges[i].min;
  10196. maxVal = groupRanges[i].max;
  10197. if (orientation == 'left') {
  10198. yAxisLeftUsed = true;
  10199. minLeft = minLeft > minVal ? minVal : minLeft;
  10200. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  10201. }
  10202. else {
  10203. yAxisRightUsed = true;
  10204. minRight = minRight > minVal ? minVal : minRight;
  10205. maxRight = maxRight < maxVal ? maxVal : maxRight;
  10206. }
  10207. }
  10208. }
  10209. if (yAxisLeftUsed == true) {
  10210. this.yAxisLeft.setRange(minLeft, maxLeft);
  10211. }
  10212. if (yAxisRightUsed == true) {
  10213. this.yAxisRight.setRange(minRight, maxRight);
  10214. }
  10215. }
  10216. changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled;
  10217. changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled;
  10218. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  10219. this.yAxisLeft.drawIcons = true;
  10220. this.yAxisRight.drawIcons = true;
  10221. }
  10222. else {
  10223. this.yAxisLeft.drawIcons = false;
  10224. this.yAxisRight.drawIcons = false;
  10225. }
  10226. this.yAxisRight.master = !yAxisLeftUsed;
  10227. if (this.yAxisRight.master == false) {
  10228. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  10229. else {this.yAxisLeft.lineOffset = 0;}
  10230. changeCalled = this.yAxisLeft.redraw() || changeCalled;
  10231. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  10232. changeCalled = this.yAxisRight.redraw() || changeCalled;
  10233. }
  10234. else {
  10235. changeCalled = this.yAxisRight.redraw() || changeCalled;
  10236. }
  10237. return changeCalled;
  10238. };
  10239. /**
  10240. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  10241. *
  10242. * @param {boolean} axisUsed
  10243. * @returns {boolean}
  10244. * @private
  10245. * @param axis
  10246. */
  10247. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  10248. var changed = false;
  10249. if (axisUsed == false) {
  10250. if (axis.dom.frame.parentNode) {
  10251. axis.hide();
  10252. changed = true;
  10253. }
  10254. }
  10255. else {
  10256. if (!axis.dom.frame.parentNode) {
  10257. axis.show();
  10258. changed = true;
  10259. }
  10260. }
  10261. return changed;
  10262. };
  10263. /**
  10264. * draw a bar graph
  10265. * @param datapoints
  10266. * @param group
  10267. */
  10268. LineGraph.prototype._drawBarGraph = function (dataset, group) {
  10269. if (dataset != null) {
  10270. if (dataset.length > 0) {
  10271. var coreDistance;
  10272. var minWidth = 0.1 * group.options.barChart.width;
  10273. var offset = 0;
  10274. var width = group.options.barChart.width;
  10275. if (group.options.barChart.align == 'left') {offset -= 0.5*width;}
  10276. else if (group.options.barChart.align == 'right') {offset += 0.5*width;}
  10277. for (var i = 0; i < dataset.length; i++) {
  10278. // dynammically downscale the width so there is no overlap up to 1/10th the original width
  10279. if (i+1 < dataset.length) {coreDistance = Math.abs(dataset[i+1].x - dataset[i].x);}
  10280. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[i-1].x - dataset[i].x));}
  10281. if (coreDistance < width) {width = coreDistance < minWidth ? minWidth : coreDistance;}
  10282. DOMutil.drawBar(dataset[i].x + offset, dataset[i].y, width, group.zeroPosition - dataset[i].y, group.className + ' bar', this.svgElements, this.svg);
  10283. }
  10284. // draw points
  10285. if (group.options.drawPoints.enabled == true) {
  10286. this._drawPoints(dataset, group, this.svgElements, this.svg, offset);
  10287. }
  10288. }
  10289. }
  10290. };
  10291. /**
  10292. * draw a line graph
  10293. *
  10294. * @param datapoints
  10295. * @param group
  10296. */
  10297. LineGraph.prototype._drawLineGraph = function (dataset, group) {
  10298. if (dataset != null) {
  10299. if (dataset.length > 0) {
  10300. var path, d;
  10301. var svgHeight = Number(this.svg.style.height.replace("px",""));
  10302. path = DOMutil.getSVGElement('path', this.svgElements, this.svg);
  10303. path.setAttributeNS(null, "class", group.className);
  10304. // construct path from dataset
  10305. if (group.options.catmullRom.enabled == true) {
  10306. d = this._catmullRom(dataset, group);
  10307. }
  10308. else {
  10309. d = this._linear(dataset);
  10310. }
  10311. // append with points for fill and finalize the path
  10312. if (group.options.shaded.enabled == true) {
  10313. var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg);
  10314. var dFill;
  10315. if (group.options.shaded.orientation == 'top') {
  10316. dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0;
  10317. }
  10318. else {
  10319. dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight;
  10320. }
  10321. fillPath.setAttributeNS(null, "class", group.className + " fill");
  10322. fillPath.setAttributeNS(null, "d", dFill);
  10323. }
  10324. // copy properties to path for drawing.
  10325. path.setAttributeNS(null, "d", "M" + d);
  10326. // draw points
  10327. if (group.options.drawPoints.enabled == true) {
  10328. this._drawPoints(dataset, group, this.svgElements, this.svg);
  10329. }
  10330. }
  10331. }
  10332. };
  10333. /**
  10334. * draw the data points
  10335. *
  10336. * @param dataset
  10337. * @param JSONcontainer
  10338. * @param svg
  10339. * @param group
  10340. */
  10341. LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) {
  10342. if (offset === undefined) {offset = 0;}
  10343. for (var i = 0; i < dataset.length; i++) {
  10344. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg);
  10345. }
  10346. };
  10347. /**
  10348. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  10349. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  10350. * the yAxis.
  10351. *
  10352. * @param datapoints
  10353. * @returns {Array}
  10354. * @private
  10355. */
  10356. LineGraph.prototype._preprocessData = function (datapoints, group) {
  10357. var extractedData = [];
  10358. var xValue, yValue;
  10359. var toScreen = this.body.util.toScreen;
  10360. var increment = 1;
  10361. var amountOfPoints = datapoints.length;
  10362. var yMin = datapoints[0].y;
  10363. var yMax = datapoints[0].y;
  10364. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  10365. // of width changing of the yAxis.
  10366. if (group.options.sampling == true) {
  10367. var xDistance = this.body.util.toGlobalScreen(datapoints[datapoints.length-1].x) - this.body.util.toGlobalScreen(datapoints[0].x);
  10368. var pointsPerPixel = amountOfPoints/xDistance;
  10369. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1,Math.round(pointsPerPixel)));
  10370. }
  10371. for (var i = 0; i < amountOfPoints; i += increment) {
  10372. xValue = toScreen(datapoints[i].x) + this.width - 1;
  10373. yValue = datapoints[i].y;
  10374. extractedData.push({x: xValue, y: yValue});
  10375. yMin = yMin > yValue ? yValue : yMin;
  10376. yMax = yMax < yValue ? yValue : yMax;
  10377. }
  10378. // extractedData.sort(function (a,b) {return a.x - b.x;});
  10379. return {min: yMin, max: yMax, data: extractedData};
  10380. };
  10381. /**
  10382. * This uses the DataAxis object to generate the correct Y coordinate on the SVG window. It uses the
  10383. * util function toScreen to get the x coordinate from the timestamp.
  10384. *
  10385. * @param datapoints
  10386. * @param options
  10387. * @returns {Array}
  10388. * @private
  10389. */
  10390. LineGraph.prototype._convertYvalues = function (datapoints, group) {
  10391. var extractedData = [];
  10392. var xValue, yValue;
  10393. var axis = this.yAxisLeft;
  10394. var svgHeight = Number(this.svg.style.height.replace("px",""));
  10395. if (group.options.yAxisOrientation == 'right') {
  10396. axis = this.yAxisRight;
  10397. }
  10398. for (var i = 0; i < datapoints.length; i++) {
  10399. xValue = datapoints[i].x;
  10400. yValue = Math.round(axis.convertValue(datapoints[i].y));
  10401. extractedData.push({x: xValue, y: yValue});
  10402. }
  10403. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  10404. // extractedData.sort(function (a,b) {return a.x - b.x;});
  10405. return extractedData;
  10406. };
  10407. /**
  10408. * This uses an uniform parametrization of the CatmullRom algorithm:
  10409. * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al.
  10410. * @param data
  10411. * @returns {string}
  10412. * @private
  10413. */
  10414. LineGraph.prototype._catmullRomUniform = function(data) {
  10415. // catmull rom
  10416. var p0, p1, p2, p3, bp1, bp2;
  10417. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  10418. var normalization = 1/6;
  10419. var length = data.length;
  10420. for (var i = 0; i < length - 1; i++) {
  10421. p0 = (i == 0) ? data[0] : data[i-1];
  10422. p1 = data[i];
  10423. p2 = data[i+1];
  10424. p3 = (i + 2 < length) ? data[i+2] : p2;
  10425. // Catmull-Rom to Cubic Bezier conversion matrix
  10426. // 0 1 0 0
  10427. // -1/6 1 1/6 0
  10428. // 0 1/6 1 -1/6
  10429. // 0 0 1 0
  10430. // bp0 = { x: p1.x, y: p1.y };
  10431. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  10432. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  10433. // bp0 = { x: p2.x, y: p2.y };
  10434. d += "C" +
  10435. bp1.x + "," +
  10436. bp1.y + " " +
  10437. bp2.x + "," +
  10438. bp2.y + " " +
  10439. p2.x + "," +
  10440. p2.y + " ";
  10441. }
  10442. return d;
  10443. };
  10444. /**
  10445. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  10446. * By default, the centripetal parameterization is used because this gives the nicest results.
  10447. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  10448. *
  10449. * One optimization can be used to reuse distances since this is a sliding window approach.
  10450. * @param data
  10451. * @returns {string}
  10452. * @private
  10453. */
  10454. LineGraph.prototype._catmullRom = function(data, group) {
  10455. var alpha = group.options.catmullRom.alpha;
  10456. if (alpha == 0 || alpha === undefined) {
  10457. return this._catmullRomUniform(data);
  10458. }
  10459. else {
  10460. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  10461. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  10462. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  10463. var length = data.length;
  10464. for (var i = 0; i < length - 1; i++) {
  10465. p0 = (i == 0) ? data[0] : data[i-1];
  10466. p1 = data[i];
  10467. p2 = data[i+1];
  10468. p3 = (i + 2 < length) ? data[i+2] : p2;
  10469. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  10470. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  10471. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  10472. // Catmull-Rom to Cubic Bezier conversion matrix
  10473. //
  10474. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  10475. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  10476. //
  10477. // [ 0 1 0 0 ]
  10478. // [ -d2^2a/N A/N d1^2a/N 0 ]
  10479. // [ 0 d3^2a/M B/M -d2^2a/M ]
  10480. // [ 0 0 1 0 ]
  10481. // [ 0 1 0 0 ]
  10482. // [ -d2pow2a/N A/N d1pow2a/N 0 ]
  10483. // [ 0 d3pow2a/M B/M -d2pow2a/M ]
  10484. // [ 0 0 1 0 ]
  10485. d3powA = Math.pow(d3, alpha);
  10486. d3pow2A = Math.pow(d3,2*alpha);
  10487. d2powA = Math.pow(d2, alpha);
  10488. d2pow2A = Math.pow(d2,2*alpha);
  10489. d1powA = Math.pow(d1, alpha);
  10490. d1pow2A = Math.pow(d1,2*alpha);
  10491. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  10492. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  10493. N = 3*d1powA * (d1powA + d2powA);
  10494. if (N > 0) {N = 1 / N;}
  10495. M = 3*d3powA * (d3powA + d2powA);
  10496. if (M > 0) {M = 1 / M;}
  10497. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  10498. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  10499. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  10500. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  10501. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  10502. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  10503. d += "C" +
  10504. bp1.x + "," +
  10505. bp1.y + " " +
  10506. bp2.x + "," +
  10507. bp2.y + " " +
  10508. p2.x + "," +
  10509. p2.y + " ";
  10510. }
  10511. return d;
  10512. }
  10513. };
  10514. /**
  10515. * this generates the SVG path for a linear drawing between datapoints.
  10516. * @param data
  10517. * @returns {string}
  10518. * @private
  10519. */
  10520. LineGraph.prototype._linear = function(data) {
  10521. // linear
  10522. var d = "";
  10523. for (var i = 0; i < data.length; i++) {
  10524. if (i == 0) {
  10525. d += data[i].x + "," + data[i].y;
  10526. }
  10527. else {
  10528. d += " " + data[i].x + "," + data[i].y;
  10529. }
  10530. }
  10531. return d;
  10532. };
  10533. module.exports = LineGraph;
  10534. /***/ },
  10535. /* 27 */
  10536. /***/ function(module, exports, __webpack_require__) {
  10537. var util = __webpack_require__(1);
  10538. var Component = __webpack_require__(18);
  10539. var TimeStep = __webpack_require__(17);
  10540. /**
  10541. * A horizontal time axis
  10542. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  10543. * @param {Object} [options] See TimeAxis.setOptions for the available
  10544. * options.
  10545. * @constructor TimeAxis
  10546. * @extends Component
  10547. */
  10548. function TimeAxis (body, options) {
  10549. this.dom = {
  10550. foreground: null,
  10551. majorLines: [],
  10552. majorTexts: [],
  10553. minorLines: [],
  10554. minorTexts: [],
  10555. redundant: {
  10556. majorLines: [],
  10557. majorTexts: [],
  10558. minorLines: [],
  10559. minorTexts: []
  10560. }
  10561. };
  10562. this.props = {
  10563. range: {
  10564. start: 0,
  10565. end: 0,
  10566. minimumStep: 0
  10567. },
  10568. lineTop: 0
  10569. };
  10570. this.defaultOptions = {
  10571. orientation: 'bottom', // supported: 'top', 'bottom'
  10572. // TODO: implement timeaxis orientations 'left' and 'right'
  10573. showMinorLabels: true,
  10574. showMajorLabels: true
  10575. };
  10576. this.options = util.extend({}, this.defaultOptions);
  10577. this.body = body;
  10578. // create the HTML DOM
  10579. this._create();
  10580. this.setOptions(options);
  10581. }
  10582. TimeAxis.prototype = new Component();
  10583. /**
  10584. * Set options for the TimeAxis.
  10585. * Parameters will be merged in current options.
  10586. * @param {Object} options Available options:
  10587. * {string} [orientation]
  10588. * {boolean} [showMinorLabels]
  10589. * {boolean} [showMajorLabels]
  10590. */
  10591. TimeAxis.prototype.setOptions = function(options) {
  10592. if (options) {
  10593. // copy all options that we know
  10594. util.selectiveExtend(['orientation', 'showMinorLabels', 'showMajorLabels'], this.options, options);
  10595. }
  10596. };
  10597. /**
  10598. * Create the HTML DOM for the TimeAxis
  10599. */
  10600. TimeAxis.prototype._create = function() {
  10601. this.dom.foreground = document.createElement('div');
  10602. this.dom.background = document.createElement('div');
  10603. this.dom.foreground.className = 'timeaxis foreground';
  10604. this.dom.background.className = 'timeaxis background';
  10605. };
  10606. /**
  10607. * Destroy the TimeAxis
  10608. */
  10609. TimeAxis.prototype.destroy = function() {
  10610. // remove from DOM
  10611. if (this.dom.foreground.parentNode) {
  10612. this.dom.foreground.parentNode.removeChild(this.dom.foreground);
  10613. }
  10614. if (this.dom.background.parentNode) {
  10615. this.dom.background.parentNode.removeChild(this.dom.background);
  10616. }
  10617. this.body = null;
  10618. };
  10619. /**
  10620. * Repaint the component
  10621. * @return {boolean} Returns true if the component is resized
  10622. */
  10623. TimeAxis.prototype.redraw = function () {
  10624. var options = this.options,
  10625. props = this.props,
  10626. foreground = this.dom.foreground,
  10627. background = this.dom.background;
  10628. // determine the correct parent DOM element (depending on option orientation)
  10629. var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom;
  10630. var parentChanged = (foreground.parentNode !== parent);
  10631. // calculate character width and height
  10632. this._calculateCharSize();
  10633. // TODO: recalculate sizes only needed when parent is resized or options is changed
  10634. var orientation = this.options.orientation,
  10635. showMinorLabels = this.options.showMinorLabels,
  10636. showMajorLabels = this.options.showMajorLabels;
  10637. // determine the width and height of the elemens for the axis
  10638. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  10639. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  10640. props.height = props.minorLabelHeight + props.majorLabelHeight;
  10641. props.width = foreground.offsetWidth;
  10642. props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight -
  10643. (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
  10644. props.minorLineWidth = 1; // TODO: really calculate width
  10645. props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
  10646. props.majorLineWidth = 1; // TODO: really calculate width
  10647. // take foreground and background offline while updating (is almost twice as fast)
  10648. var foregroundNextSibling = foreground.nextSibling;
  10649. var backgroundNextSibling = background.nextSibling;
  10650. foreground.parentNode && foreground.parentNode.removeChild(foreground);
  10651. background.parentNode && background.parentNode.removeChild(background);
  10652. foreground.style.height = this.props.height + 'px';
  10653. this._repaintLabels();
  10654. // put DOM online again (at the same place)
  10655. if (foregroundNextSibling) {
  10656. parent.insertBefore(foreground, foregroundNextSibling);
  10657. }
  10658. else {
  10659. parent.appendChild(foreground)
  10660. }
  10661. if (backgroundNextSibling) {
  10662. this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
  10663. }
  10664. else {
  10665. this.body.dom.backgroundVertical.appendChild(background)
  10666. }
  10667. return this._isResized() || parentChanged;
  10668. };
  10669. /**
  10670. * Repaint major and minor text labels and vertical grid lines
  10671. * @private
  10672. */
  10673. TimeAxis.prototype._repaintLabels = function () {
  10674. var orientation = this.options.orientation;
  10675. // calculate range and step (step such that we have space for 7 characters per label)
  10676. var start = util.convert(this.body.range.start, 'Number'),
  10677. end = util.convert(this.body.range.end, 'Number'),
  10678. minimumStep = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  10679. -this.body.util.toTime(0).valueOf();
  10680. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  10681. this.step = step;
  10682. // Move all DOM elements to a "redundant" list, where they
  10683. // can be picked for re-use, and clear the lists with lines and texts.
  10684. // At the end of the function _repaintLabels, left over elements will be cleaned up
  10685. var dom = this.dom;
  10686. dom.redundant.majorLines = dom.majorLines;
  10687. dom.redundant.majorTexts = dom.majorTexts;
  10688. dom.redundant.minorLines = dom.minorLines;
  10689. dom.redundant.minorTexts = dom.minorTexts;
  10690. dom.majorLines = [];
  10691. dom.majorTexts = [];
  10692. dom.minorLines = [];
  10693. dom.minorTexts = [];
  10694. step.first();
  10695. var xFirstMajorLabel = undefined;
  10696. var max = 0;
  10697. while (step.hasNext() && max < 1000) {
  10698. max++;
  10699. var cur = step.getCurrent(),
  10700. x = this.body.util.toScreen(cur),
  10701. isMajor = step.isMajor();
  10702. // TODO: lines must have a width, such that we can create css backgrounds
  10703. if (this.options.showMinorLabels) {
  10704. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  10705. }
  10706. if (isMajor && this.options.showMajorLabels) {
  10707. if (x > 0) {
  10708. if (xFirstMajorLabel == undefined) {
  10709. xFirstMajorLabel = x;
  10710. }
  10711. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  10712. }
  10713. this._repaintMajorLine(x, orientation);
  10714. }
  10715. else {
  10716. this._repaintMinorLine(x, orientation);
  10717. }
  10718. step.next();
  10719. }
  10720. // create a major label on the left when needed
  10721. if (this.options.showMajorLabels) {
  10722. var leftTime = this.body.util.toTime(0),
  10723. leftText = step.getLabelMajor(leftTime),
  10724. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  10725. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  10726. this._repaintMajorText(0, leftText, orientation);
  10727. }
  10728. }
  10729. // Cleanup leftover DOM elements from the redundant list
  10730. util.forEach(this.dom.redundant, function (arr) {
  10731. while (arr.length) {
  10732. var elem = arr.pop();
  10733. if (elem && elem.parentNode) {
  10734. elem.parentNode.removeChild(elem);
  10735. }
  10736. }
  10737. });
  10738. };
  10739. /**
  10740. * Create a minor label for the axis at position x
  10741. * @param {Number} x
  10742. * @param {String} text
  10743. * @param {String} orientation "top" or "bottom" (default)
  10744. * @private
  10745. */
  10746. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  10747. // reuse redundant label
  10748. var label = this.dom.redundant.minorTexts.shift();
  10749. if (!label) {
  10750. // create new label
  10751. var content = document.createTextNode('');
  10752. label = document.createElement('div');
  10753. label.appendChild(content);
  10754. label.className = 'text minor';
  10755. this.dom.foreground.appendChild(label);
  10756. }
  10757. this.dom.minorTexts.push(label);
  10758. label.childNodes[0].nodeValue = text;
  10759. label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0';
  10760. label.style.left = x + 'px';
  10761. //label.title = title; // TODO: this is a heavy operation
  10762. };
  10763. /**
  10764. * Create a Major label for the axis at position x
  10765. * @param {Number} x
  10766. * @param {String} text
  10767. * @param {String} orientation "top" or "bottom" (default)
  10768. * @private
  10769. */
  10770. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  10771. // reuse redundant label
  10772. var label = this.dom.redundant.majorTexts.shift();
  10773. if (!label) {
  10774. // create label
  10775. var content = document.createTextNode(text);
  10776. label = document.createElement('div');
  10777. label.className = 'text major';
  10778. label.appendChild(content);
  10779. this.dom.foreground.appendChild(label);
  10780. }
  10781. this.dom.majorTexts.push(label);
  10782. label.childNodes[0].nodeValue = text;
  10783. //label.title = title; // TODO: this is a heavy operation
  10784. label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px');
  10785. label.style.left = x + 'px';
  10786. };
  10787. /**
  10788. * Create a minor line for the axis at position x
  10789. * @param {Number} x
  10790. * @param {String} orientation "top" or "bottom" (default)
  10791. * @private
  10792. */
  10793. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  10794. // reuse redundant line
  10795. var line = this.dom.redundant.minorLines.shift();
  10796. if (!line) {
  10797. // create vertical line
  10798. line = document.createElement('div');
  10799. line.className = 'grid vertical minor';
  10800. this.dom.background.appendChild(line);
  10801. }
  10802. this.dom.minorLines.push(line);
  10803. var props = this.props;
  10804. if (orientation == 'top') {
  10805. line.style.top = props.majorLabelHeight + 'px';
  10806. }
  10807. else {
  10808. line.style.top = this.body.domProps.top.height + 'px';
  10809. }
  10810. line.style.height = props.minorLineHeight + 'px';
  10811. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  10812. };
  10813. /**
  10814. * Create a Major line for the axis at position x
  10815. * @param {Number} x
  10816. * @param {String} orientation "top" or "bottom" (default)
  10817. * @private
  10818. */
  10819. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  10820. // reuse redundant line
  10821. var line = this.dom.redundant.majorLines.shift();
  10822. if (!line) {
  10823. // create vertical line
  10824. line = document.createElement('DIV');
  10825. line.className = 'grid vertical major';
  10826. this.dom.background.appendChild(line);
  10827. }
  10828. this.dom.majorLines.push(line);
  10829. var props = this.props;
  10830. if (orientation == 'top') {
  10831. line.style.top = '0';
  10832. }
  10833. else {
  10834. line.style.top = this.body.domProps.top.height + 'px';
  10835. }
  10836. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  10837. line.style.height = props.majorLineHeight + 'px';
  10838. };
  10839. /**
  10840. * Determine the size of text on the axis (both major and minor axis).
  10841. * The size is calculated only once and then cached in this.props.
  10842. * @private
  10843. */
  10844. TimeAxis.prototype._calculateCharSize = function () {
  10845. // Note: We calculate char size with every redraw. Size may change, for
  10846. // example when any of the timelines parents had display:none for example.
  10847. // determine the char width and height on the minor axis
  10848. if (!this.dom.measureCharMinor) {
  10849. this.dom.measureCharMinor = document.createElement('DIV');
  10850. this.dom.measureCharMinor.className = 'text minor measure';
  10851. this.dom.measureCharMinor.style.position = 'absolute';
  10852. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  10853. this.dom.foreground.appendChild(this.dom.measureCharMinor);
  10854. }
  10855. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  10856. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  10857. // determine the char width and height on the major axis
  10858. if (!this.dom.measureCharMajor) {
  10859. this.dom.measureCharMajor = document.createElement('DIV');
  10860. this.dom.measureCharMajor.className = 'text minor measure';
  10861. this.dom.measureCharMajor.style.position = 'absolute';
  10862. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  10863. this.dom.foreground.appendChild(this.dom.measureCharMajor);
  10864. }
  10865. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  10866. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  10867. };
  10868. /**
  10869. * Snap a date to a rounded value.
  10870. * The snap intervals are dependent on the current scale and step.
  10871. * @param {Date} date the date to be snapped.
  10872. * @return {Date} snappedDate
  10873. */
  10874. TimeAxis.prototype.snap = function(date) {
  10875. return this.step.snap(date);
  10876. };
  10877. module.exports = TimeAxis;
  10878. /***/ },
  10879. /* 28 */
  10880. /***/ function(module, exports, __webpack_require__) {
  10881. var Item = __webpack_require__(29);
  10882. /**
  10883. * @constructor ItemBox
  10884. * @extends Item
  10885. * @param {Object} data Object containing parameters start
  10886. * content, className.
  10887. * @param {{toScreen: function, toTime: function}} conversion
  10888. * Conversion functions from time to screen and vice versa
  10889. * @param {Object} [options] Configuration options
  10890. * // TODO: describe available options
  10891. */
  10892. function ItemBox (data, conversion, options) {
  10893. this.props = {
  10894. dot: {
  10895. width: 0,
  10896. height: 0
  10897. },
  10898. line: {
  10899. width: 0,
  10900. height: 0
  10901. }
  10902. };
  10903. // validate data
  10904. if (data) {
  10905. if (data.start == undefined) {
  10906. throw new Error('Property "start" missing in item ' + data);
  10907. }
  10908. }
  10909. Item.call(this, data, conversion, options);
  10910. }
  10911. ItemBox.prototype = new Item (null, null, null);
  10912. /**
  10913. * Check whether this item is visible inside given range
  10914. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  10915. * @returns {boolean} True if visible
  10916. */
  10917. ItemBox.prototype.isVisible = function(range) {
  10918. // determine visibility
  10919. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  10920. var interval = (range.end - range.start) / 4;
  10921. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  10922. };
  10923. /**
  10924. * Repaint the item
  10925. */
  10926. ItemBox.prototype.redraw = function() {
  10927. var dom = this.dom;
  10928. if (!dom) {
  10929. // create DOM
  10930. this.dom = {};
  10931. dom = this.dom;
  10932. // create main box
  10933. dom.box = document.createElement('DIV');
  10934. // contents box (inside the background box). used for making margins
  10935. dom.content = document.createElement('DIV');
  10936. dom.content.className = 'content';
  10937. dom.box.appendChild(dom.content);
  10938. // line to axis
  10939. dom.line = document.createElement('DIV');
  10940. dom.line.className = 'line';
  10941. // dot on axis
  10942. dom.dot = document.createElement('DIV');
  10943. dom.dot.className = 'dot';
  10944. // attach this item as attribute
  10945. dom.box['timeline-item'] = this;
  10946. }
  10947. // append DOM to parent DOM
  10948. if (!this.parent) {
  10949. throw new Error('Cannot redraw item: no parent attached');
  10950. }
  10951. if (!dom.box.parentNode) {
  10952. var foreground = this.parent.dom.foreground;
  10953. if (!foreground) throw new Error('Cannot redraw time axis: parent has no foreground container element');
  10954. foreground.appendChild(dom.box);
  10955. }
  10956. if (!dom.line.parentNode) {
  10957. var background = this.parent.dom.background;
  10958. if (!background) throw new Error('Cannot redraw time axis: parent has no background container element');
  10959. background.appendChild(dom.line);
  10960. }
  10961. if (!dom.dot.parentNode) {
  10962. var axis = this.parent.dom.axis;
  10963. if (!background) throw new Error('Cannot redraw time axis: parent has no axis container element');
  10964. axis.appendChild(dom.dot);
  10965. }
  10966. this.displayed = true;
  10967. // update contents
  10968. if (this.data.content != this.content) {
  10969. this.content = this.data.content;
  10970. if (this.content instanceof Element) {
  10971. dom.content.innerHTML = '';
  10972. dom.content.appendChild(this.content);
  10973. }
  10974. else if (this.data.content != undefined) {
  10975. dom.content.innerHTML = this.content;
  10976. }
  10977. else {
  10978. throw new Error('Property "content" missing in item ' + this.data.id);
  10979. }
  10980. this.dirty = true;
  10981. }
  10982. // update title
  10983. if (this.data.title != this.title) {
  10984. dom.box.title = this.data.title;
  10985. this.title = this.data.title;
  10986. }
  10987. // update class
  10988. var className = (this.data.className? ' ' + this.data.className : '') +
  10989. (this.selected ? ' selected' : '');
  10990. if (this.className != className) {
  10991. this.className = className;
  10992. dom.box.className = 'item box' + className;
  10993. dom.line.className = 'item line' + className;
  10994. dom.dot.className = 'item dot' + className;
  10995. this.dirty = true;
  10996. }
  10997. // recalculate size
  10998. if (this.dirty) {
  10999. this.props.dot.height = dom.dot.offsetHeight;
  11000. this.props.dot.width = dom.dot.offsetWidth;
  11001. this.props.line.width = dom.line.offsetWidth;
  11002. this.width = dom.box.offsetWidth;
  11003. this.height = dom.box.offsetHeight;
  11004. this.dirty = false;
  11005. }
  11006. this._repaintDeleteButton(dom.box);
  11007. };
  11008. /**
  11009. * Show the item in the DOM (when not already displayed). The items DOM will
  11010. * be created when needed.
  11011. */
  11012. ItemBox.prototype.show = function() {
  11013. if (!this.displayed) {
  11014. this.redraw();
  11015. }
  11016. };
  11017. /**
  11018. * Hide the item from the DOM (when visible)
  11019. */
  11020. ItemBox.prototype.hide = function() {
  11021. if (this.displayed) {
  11022. var dom = this.dom;
  11023. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  11024. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  11025. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  11026. this.top = null;
  11027. this.left = null;
  11028. this.displayed = false;
  11029. }
  11030. };
  11031. /**
  11032. * Reposition the item horizontally
  11033. * @Override
  11034. */
  11035. ItemBox.prototype.repositionX = function() {
  11036. var start = this.conversion.toScreen(this.data.start),
  11037. align = this.options.align,
  11038. left,
  11039. box = this.dom.box,
  11040. line = this.dom.line,
  11041. dot = this.dom.dot;
  11042. // calculate left position of the box
  11043. if (align == 'right') {
  11044. this.left = start - this.width;
  11045. }
  11046. else if (align == 'left') {
  11047. this.left = start;
  11048. }
  11049. else {
  11050. // default or 'center'
  11051. this.left = start - this.width / 2;
  11052. }
  11053. // reposition box
  11054. box.style.left = this.left + 'px';
  11055. // reposition line
  11056. line.style.left = (start - this.props.line.width / 2) + 'px';
  11057. // reposition dot
  11058. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  11059. };
  11060. /**
  11061. * Reposition the item vertically
  11062. * @Override
  11063. */
  11064. ItemBox.prototype.repositionY = function() {
  11065. var orientation = this.options.orientation,
  11066. box = this.dom.box,
  11067. line = this.dom.line,
  11068. dot = this.dom.dot;
  11069. if (orientation == 'top') {
  11070. box.style.top = (this.top || 0) + 'px';
  11071. line.style.top = '0';
  11072. line.style.height = (this.parent.top + this.top + 1) + 'px';
  11073. line.style.bottom = '';
  11074. }
  11075. else { // orientation 'bottom'
  11076. var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
  11077. var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
  11078. box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
  11079. line.style.top = (itemSetHeight - lineHeight) + 'px';
  11080. line.style.bottom = '0';
  11081. }
  11082. dot.style.top = (-this.props.dot.height / 2) + 'px';
  11083. };
  11084. module.exports = ItemBox;
  11085. /***/ },
  11086. /* 29 */
  11087. /***/ function(module, exports, __webpack_require__) {
  11088. var Hammer = __webpack_require__(41);
  11089. /**
  11090. * @constructor Item
  11091. * @param {Object} data Object containing (optional) parameters type,
  11092. * start, end, content, group, className.
  11093. * @param {{toScreen: function, toTime: function}} conversion
  11094. * Conversion functions from time to screen and vice versa
  11095. * @param {Object} options Configuration options
  11096. * // TODO: describe available options
  11097. */
  11098. function Item (data, conversion, options) {
  11099. this.id = null;
  11100. this.parent = null;
  11101. this.data = data;
  11102. this.dom = null;
  11103. this.conversion = conversion || {};
  11104. this.options = options || {};
  11105. this.selected = false;
  11106. this.displayed = false;
  11107. this.dirty = true;
  11108. this.top = null;
  11109. this.left = null;
  11110. this.width = null;
  11111. this.height = null;
  11112. }
  11113. /**
  11114. * Select current item
  11115. */
  11116. Item.prototype.select = function() {
  11117. this.selected = true;
  11118. if (this.displayed) this.redraw();
  11119. };
  11120. /**
  11121. * Unselect current item
  11122. */
  11123. Item.prototype.unselect = function() {
  11124. this.selected = false;
  11125. if (this.displayed) this.redraw();
  11126. };
  11127. /**
  11128. * Set a parent for the item
  11129. * @param {ItemSet | Group} parent
  11130. */
  11131. Item.prototype.setParent = function(parent) {
  11132. if (this.displayed) {
  11133. this.hide();
  11134. this.parent = parent;
  11135. if (this.parent) {
  11136. this.show();
  11137. }
  11138. }
  11139. else {
  11140. this.parent = parent;
  11141. }
  11142. };
  11143. /**
  11144. * Check whether this item is visible inside given range
  11145. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  11146. * @returns {boolean} True if visible
  11147. */
  11148. Item.prototype.isVisible = function(range) {
  11149. // Should be implemented by Item implementations
  11150. return false;
  11151. };
  11152. /**
  11153. * Show the Item in the DOM (when not already visible)
  11154. * @return {Boolean} changed
  11155. */
  11156. Item.prototype.show = function() {
  11157. return false;
  11158. };
  11159. /**
  11160. * Hide the Item from the DOM (when visible)
  11161. * @return {Boolean} changed
  11162. */
  11163. Item.prototype.hide = function() {
  11164. return false;
  11165. };
  11166. /**
  11167. * Repaint the item
  11168. */
  11169. Item.prototype.redraw = function() {
  11170. // should be implemented by the item
  11171. };
  11172. /**
  11173. * Reposition the Item horizontally
  11174. */
  11175. Item.prototype.repositionX = function() {
  11176. // should be implemented by the item
  11177. };
  11178. /**
  11179. * Reposition the Item vertically
  11180. */
  11181. Item.prototype.repositionY = function() {
  11182. // should be implemented by the item
  11183. };
  11184. /**
  11185. * Repaint a delete button on the top right of the item when the item is selected
  11186. * @param {HTMLElement} anchor
  11187. * @protected
  11188. */
  11189. Item.prototype._repaintDeleteButton = function (anchor) {
  11190. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  11191. // create and show button
  11192. var me = this;
  11193. var deleteButton = document.createElement('div');
  11194. deleteButton.className = 'delete';
  11195. deleteButton.title = 'Delete this item';
  11196. Hammer(deleteButton, {
  11197. preventDefault: true
  11198. }).on('tap', function (event) {
  11199. me.parent.removeFromDataSet(me);
  11200. event.stopPropagation();
  11201. });
  11202. anchor.appendChild(deleteButton);
  11203. this.dom.deleteButton = deleteButton;
  11204. }
  11205. else if (!this.selected && this.dom.deleteButton) {
  11206. // remove button
  11207. if (this.dom.deleteButton.parentNode) {
  11208. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  11209. }
  11210. this.dom.deleteButton = null;
  11211. }
  11212. };
  11213. module.exports = Item;
  11214. /***/ },
  11215. /* 30 */
  11216. /***/ function(module, exports, __webpack_require__) {
  11217. var Item = __webpack_require__(29);
  11218. /**
  11219. * @constructor ItemPoint
  11220. * @extends Item
  11221. * @param {Object} data Object containing parameters start
  11222. * content, className.
  11223. * @param {{toScreen: function, toTime: function}} conversion
  11224. * Conversion functions from time to screen and vice versa
  11225. * @param {Object} [options] Configuration options
  11226. * // TODO: describe available options
  11227. */
  11228. function ItemPoint (data, conversion, options) {
  11229. this.props = {
  11230. dot: {
  11231. top: 0,
  11232. width: 0,
  11233. height: 0
  11234. },
  11235. content: {
  11236. height: 0,
  11237. marginLeft: 0
  11238. }
  11239. };
  11240. // validate data
  11241. if (data) {
  11242. if (data.start == undefined) {
  11243. throw new Error('Property "start" missing in item ' + data);
  11244. }
  11245. }
  11246. Item.call(this, data, conversion, options);
  11247. }
  11248. ItemPoint.prototype = new Item (null, null, null);
  11249. /**
  11250. * Check whether this item is visible inside given range
  11251. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  11252. * @returns {boolean} True if visible
  11253. */
  11254. ItemPoint.prototype.isVisible = function(range) {
  11255. // determine visibility
  11256. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  11257. var interval = (range.end - range.start) / 4;
  11258. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  11259. };
  11260. /**
  11261. * Repaint the item
  11262. */
  11263. ItemPoint.prototype.redraw = function() {
  11264. var dom = this.dom;
  11265. if (!dom) {
  11266. // create DOM
  11267. this.dom = {};
  11268. dom = this.dom;
  11269. // background box
  11270. dom.point = document.createElement('div');
  11271. // className is updated in redraw()
  11272. // contents box, right from the dot
  11273. dom.content = document.createElement('div');
  11274. dom.content.className = 'content';
  11275. dom.point.appendChild(dom.content);
  11276. // dot at start
  11277. dom.dot = document.createElement('div');
  11278. dom.point.appendChild(dom.dot);
  11279. // attach this item as attribute
  11280. dom.point['timeline-item'] = this;
  11281. }
  11282. // append DOM to parent DOM
  11283. if (!this.parent) {
  11284. throw new Error('Cannot redraw item: no parent attached');
  11285. }
  11286. if (!dom.point.parentNode) {
  11287. var foreground = this.parent.dom.foreground;
  11288. if (!foreground) {
  11289. throw new Error('Cannot redraw time axis: parent has no foreground container element');
  11290. }
  11291. foreground.appendChild(dom.point);
  11292. }
  11293. this.displayed = true;
  11294. // update contents
  11295. if (this.data.content != this.content) {
  11296. this.content = this.data.content;
  11297. if (this.content instanceof Element) {
  11298. dom.content.innerHTML = '';
  11299. dom.content.appendChild(this.content);
  11300. }
  11301. else if (this.data.content != undefined) {
  11302. dom.content.innerHTML = this.content;
  11303. }
  11304. else {
  11305. throw new Error('Property "content" missing in item ' + this.data.id);
  11306. }
  11307. this.dirty = true;
  11308. }
  11309. // update title
  11310. if (this.data.title != this.title) {
  11311. dom.point.title = this.data.title;
  11312. this.title = this.data.title;
  11313. }
  11314. // update class
  11315. var className = (this.data.className? ' ' + this.data.className : '') +
  11316. (this.selected ? ' selected' : '');
  11317. if (this.className != className) {
  11318. this.className = className;
  11319. dom.point.className = 'item point' + className;
  11320. dom.dot.className = 'item dot' + className;
  11321. this.dirty = true;
  11322. }
  11323. // recalculate size
  11324. if (this.dirty) {
  11325. this.width = dom.point.offsetWidth;
  11326. this.height = dom.point.offsetHeight;
  11327. this.props.dot.width = dom.dot.offsetWidth;
  11328. this.props.dot.height = dom.dot.offsetHeight;
  11329. this.props.content.height = dom.content.offsetHeight;
  11330. // resize contents
  11331. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  11332. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  11333. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  11334. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  11335. this.dirty = false;
  11336. }
  11337. this._repaintDeleteButton(dom.point);
  11338. };
  11339. /**
  11340. * Show the item in the DOM (when not already visible). The items DOM will
  11341. * be created when needed.
  11342. */
  11343. ItemPoint.prototype.show = function() {
  11344. if (!this.displayed) {
  11345. this.redraw();
  11346. }
  11347. };
  11348. /**
  11349. * Hide the item from the DOM (when visible)
  11350. */
  11351. ItemPoint.prototype.hide = function() {
  11352. if (this.displayed) {
  11353. if (this.dom.point.parentNode) {
  11354. this.dom.point.parentNode.removeChild(this.dom.point);
  11355. }
  11356. this.top = null;
  11357. this.left = null;
  11358. this.displayed = false;
  11359. }
  11360. };
  11361. /**
  11362. * Reposition the item horizontally
  11363. * @Override
  11364. */
  11365. ItemPoint.prototype.repositionX = function() {
  11366. var start = this.conversion.toScreen(this.data.start);
  11367. this.left = start - this.props.dot.width;
  11368. // reposition point
  11369. this.dom.point.style.left = this.left + 'px';
  11370. };
  11371. /**
  11372. * Reposition the item vertically
  11373. * @Override
  11374. */
  11375. ItemPoint.prototype.repositionY = function() {
  11376. var orientation = this.options.orientation,
  11377. point = this.dom.point;
  11378. if (orientation == 'top') {
  11379. point.style.top = this.top + 'px';
  11380. }
  11381. else {
  11382. point.style.top = (this.parent.height - this.top - this.height) + 'px';
  11383. }
  11384. };
  11385. module.exports = ItemPoint;
  11386. /***/ },
  11387. /* 31 */
  11388. /***/ function(module, exports, __webpack_require__) {
  11389. var Hammer = __webpack_require__(41);
  11390. var Item = __webpack_require__(29);
  11391. /**
  11392. * @constructor ItemRange
  11393. * @extends Item
  11394. * @param {Object} data Object containing parameters start, end
  11395. * content, className.
  11396. * @param {{toScreen: function, toTime: function}} conversion
  11397. * Conversion functions from time to screen and vice versa
  11398. * @param {Object} [options] Configuration options
  11399. * // TODO: describe options
  11400. */
  11401. function ItemRange (data, conversion, options) {
  11402. this.props = {
  11403. content: {
  11404. width: 0
  11405. }
  11406. };
  11407. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  11408. // validate data
  11409. if (data) {
  11410. if (data.start == undefined) {
  11411. throw new Error('Property "start" missing in item ' + data.id);
  11412. }
  11413. if (data.end == undefined) {
  11414. throw new Error('Property "end" missing in item ' + data.id);
  11415. }
  11416. }
  11417. Item.call(this, data, conversion, options);
  11418. }
  11419. ItemRange.prototype = new Item (null, null, null);
  11420. ItemRange.prototype.baseClassName = 'item range';
  11421. /**
  11422. * Check whether this item is visible inside given range
  11423. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  11424. * @returns {boolean} True if visible
  11425. */
  11426. ItemRange.prototype.isVisible = function(range) {
  11427. // determine visibility
  11428. return (this.data.start < range.end) && (this.data.end > range.start);
  11429. };
  11430. /**
  11431. * Repaint the item
  11432. */
  11433. ItemRange.prototype.redraw = function() {
  11434. var dom = this.dom;
  11435. if (!dom) {
  11436. // create DOM
  11437. this.dom = {};
  11438. dom = this.dom;
  11439. // background box
  11440. dom.box = document.createElement('div');
  11441. // className is updated in redraw()
  11442. // contents box
  11443. dom.content = document.createElement('div');
  11444. dom.content.className = 'content';
  11445. dom.box.appendChild(dom.content);
  11446. // attach this item as attribute
  11447. dom.box['timeline-item'] = this;
  11448. }
  11449. // append DOM to parent DOM
  11450. if (!this.parent) {
  11451. throw new Error('Cannot redraw item: no parent attached');
  11452. }
  11453. if (!dom.box.parentNode) {
  11454. var foreground = this.parent.dom.foreground;
  11455. if (!foreground) {
  11456. throw new Error('Cannot redraw time axis: parent has no foreground container element');
  11457. }
  11458. foreground.appendChild(dom.box);
  11459. }
  11460. this.displayed = true;
  11461. // update contents
  11462. if (this.data.content != this.content) {
  11463. this.content = this.data.content;
  11464. if (this.content instanceof Element) {
  11465. dom.content.innerHTML = '';
  11466. dom.content.appendChild(this.content);
  11467. }
  11468. else if (this.data.content != undefined) {
  11469. dom.content.innerHTML = this.content;
  11470. }
  11471. else {
  11472. throw new Error('Property "content" missing in item ' + this.data.id);
  11473. }
  11474. this.dirty = true;
  11475. }
  11476. // update title
  11477. if (this.data.title != this.title) {
  11478. dom.box.title = this.data.title;
  11479. this.title = this.data.title;
  11480. }
  11481. // update class
  11482. var className = (this.data.className ? (' ' + this.data.className) : '') +
  11483. (this.selected ? ' selected' : '');
  11484. if (this.className != className) {
  11485. this.className = className;
  11486. dom.box.className = this.baseClassName + className;
  11487. this.dirty = true;
  11488. }
  11489. // recalculate size
  11490. if (this.dirty) {
  11491. // determine from css whether this box has overflow
  11492. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  11493. this.props.content.width = this.dom.content.offsetWidth;
  11494. this.height = this.dom.box.offsetHeight;
  11495. this.dirty = false;
  11496. }
  11497. this._repaintDeleteButton(dom.box);
  11498. this._repaintDragLeft();
  11499. this._repaintDragRight();
  11500. };
  11501. /**
  11502. * Show the item in the DOM (when not already visible). The items DOM will
  11503. * be created when needed.
  11504. */
  11505. ItemRange.prototype.show = function() {
  11506. if (!this.displayed) {
  11507. this.redraw();
  11508. }
  11509. };
  11510. /**
  11511. * Hide the item from the DOM (when visible)
  11512. * @return {Boolean} changed
  11513. */
  11514. ItemRange.prototype.hide = function() {
  11515. if (this.displayed) {
  11516. var box = this.dom.box;
  11517. if (box.parentNode) {
  11518. box.parentNode.removeChild(box);
  11519. }
  11520. this.top = null;
  11521. this.left = null;
  11522. this.displayed = false;
  11523. }
  11524. };
  11525. /**
  11526. * Reposition the item horizontally
  11527. * @Override
  11528. */
  11529. // TODO: delete the old function
  11530. ItemRange.prototype.repositionX = function() {
  11531. var props = this.props,
  11532. parentWidth = this.parent.width,
  11533. start = this.conversion.toScreen(this.data.start),
  11534. end = this.conversion.toScreen(this.data.end),
  11535. padding = this.options.padding,
  11536. contentLeft;
  11537. // limit the width of the this, as browsers cannot draw very wide divs
  11538. if (start < -parentWidth) {
  11539. start = -parentWidth;
  11540. }
  11541. if (end > 2 * parentWidth) {
  11542. end = 2 * parentWidth;
  11543. }
  11544. var boxWidth = Math.max(end - start, 1);
  11545. if (this.overflow) {
  11546. // when range exceeds left of the window, position the contents at the left of the visible area
  11547. contentLeft = Math.max(-start, 0);
  11548. this.left = start;
  11549. this.width = boxWidth + this.props.content.width;
  11550. // Note: The calculation of width is an optimistic calculation, giving
  11551. // a width which will not change when moving the Timeline
  11552. // So no restacking needed, which is nicer for the eye;
  11553. }
  11554. else { // no overflow
  11555. // when range exceeds left of the window, position the contents at the left of the visible area
  11556. if (start < 0) {
  11557. contentLeft = Math.min(-start,
  11558. (end - start - props.content.width - 2 * padding));
  11559. // TODO: remove the need for options.padding. it's terrible.
  11560. }
  11561. else {
  11562. contentLeft = 0;
  11563. }
  11564. this.left = start;
  11565. this.width = boxWidth;
  11566. }
  11567. this.dom.box.style.left = this.left + 'px';
  11568. this.dom.box.style.width = boxWidth + 'px';
  11569. this.dom.content.style.left = contentLeft + 'px';
  11570. };
  11571. /**
  11572. * Reposition the item vertically
  11573. * @Override
  11574. */
  11575. ItemRange.prototype.repositionY = function() {
  11576. var orientation = this.options.orientation,
  11577. box = this.dom.box;
  11578. if (orientation == 'top') {
  11579. box.style.top = this.top + 'px';
  11580. }
  11581. else {
  11582. box.style.top = (this.parent.height - this.top - this.height) + 'px';
  11583. }
  11584. };
  11585. /**
  11586. * Repaint a drag area on the left side of the range when the range is selected
  11587. * @protected
  11588. */
  11589. ItemRange.prototype._repaintDragLeft = function () {
  11590. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  11591. // create and show drag area
  11592. var dragLeft = document.createElement('div');
  11593. dragLeft.className = 'drag-left';
  11594. dragLeft.dragLeftItem = this;
  11595. // TODO: this should be redundant?
  11596. Hammer(dragLeft, {
  11597. preventDefault: true
  11598. }).on('drag', function () {
  11599. //console.log('drag left')
  11600. });
  11601. this.dom.box.appendChild(dragLeft);
  11602. this.dom.dragLeft = dragLeft;
  11603. }
  11604. else if (!this.selected && this.dom.dragLeft) {
  11605. // delete drag area
  11606. if (this.dom.dragLeft.parentNode) {
  11607. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  11608. }
  11609. this.dom.dragLeft = null;
  11610. }
  11611. };
  11612. /**
  11613. * Repaint a drag area on the right side of the range when the range is selected
  11614. * @protected
  11615. */
  11616. ItemRange.prototype._repaintDragRight = function () {
  11617. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  11618. // create and show drag area
  11619. var dragRight = document.createElement('div');
  11620. dragRight.className = 'drag-right';
  11621. dragRight.dragRightItem = this;
  11622. // TODO: this should be redundant?
  11623. Hammer(dragRight, {
  11624. preventDefault: true
  11625. }).on('drag', function () {
  11626. //console.log('drag right')
  11627. });
  11628. this.dom.box.appendChild(dragRight);
  11629. this.dom.dragRight = dragRight;
  11630. }
  11631. else if (!this.selected && this.dom.dragRight) {
  11632. // delete drag area
  11633. if (this.dom.dragRight.parentNode) {
  11634. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  11635. }
  11636. this.dom.dragRight = null;
  11637. }
  11638. };
  11639. module.exports = ItemRange;
  11640. /***/ },
  11641. /* 32 */
  11642. /***/ function(module, exports, __webpack_require__) {
  11643. var Emitter = __webpack_require__(46);
  11644. var Hammer = __webpack_require__(41);
  11645. var mousetrap = __webpack_require__(47);
  11646. var util = __webpack_require__(1);
  11647. var hammerUtil = __webpack_require__(43);
  11648. var DataSet = __webpack_require__(3);
  11649. var DataView = __webpack_require__(4);
  11650. var dotparser = __webpack_require__(38);
  11651. var gephiParser = __webpack_require__(39);
  11652. var Groups = __webpack_require__(34);
  11653. var Images = __webpack_require__(35);
  11654. var Node = __webpack_require__(36);
  11655. var Edge = __webpack_require__(33);
  11656. var Popup = __webpack_require__(37);
  11657. var MixinLoader = __webpack_require__(45);
  11658. // Load custom shapes into CanvasRenderingContext2D
  11659. __webpack_require__(44);
  11660. /**
  11661. * @constructor Network
  11662. * Create a network visualization, displaying nodes and edges.
  11663. *
  11664. * @param {Element} container The DOM element in which the Network will
  11665. * be created. Normally a div element.
  11666. * @param {Object} data An object containing parameters
  11667. * {Array} nodes
  11668. * {Array} edges
  11669. * @param {Object} options Options
  11670. */
  11671. function Network (container, data, options) {
  11672. if (!(this instanceof Network)) {
  11673. throw new SyntaxError('Constructor must be called with the new operator');
  11674. }
  11675. this._initializeMixinLoaders();
  11676. // create variables and set default values
  11677. this.containerElement = container;
  11678. // render and calculation settings
  11679. this.renderRefreshRate = 60; // hz (fps)
  11680. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  11681. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  11682. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  11683. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation
  11684. this.initializing = true;
  11685. this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null};
  11686. // set constant values
  11687. this.defaultOptions = {
  11688. nodes: {
  11689. mass: 1,
  11690. radiusMin: 10,
  11691. radiusMax: 30,
  11692. radius: 10,
  11693. shape: 'ellipse',
  11694. image: undefined,
  11695. widthMin: 16, // px
  11696. widthMax: 64, // px
  11697. fixed: false,
  11698. fontColor: 'black',
  11699. fontSize: 14, // px
  11700. fontFace: 'verdana',
  11701. level: -1,
  11702. color: {
  11703. border: '#2B7CE9',
  11704. background: '#97C2FC',
  11705. highlight: {
  11706. border: '#2B7CE9',
  11707. background: '#D2E5FF'
  11708. },
  11709. hover: {
  11710. border: '#2B7CE9',
  11711. background: '#D2E5FF'
  11712. }
  11713. },
  11714. borderColor: '#2B7CE9',
  11715. backgroundColor: '#97C2FC',
  11716. highlightColor: '#D2E5FF',
  11717. group: undefined,
  11718. borderWidth: 1
  11719. },
  11720. edges: {
  11721. widthMin: 1,
  11722. widthMax: 15,
  11723. width: 1,
  11724. widthSelectionMultiplier: 2,
  11725. hoverWidth: 1.5,
  11726. style: 'line',
  11727. color: {
  11728. color:'#848484',
  11729. highlight:'#848484',
  11730. hover: '#848484'
  11731. },
  11732. fontColor: '#343434',
  11733. fontSize: 14, // px
  11734. fontFace: 'arial',
  11735. fontFill: 'white',
  11736. arrowScaleFactor: 1,
  11737. dash: {
  11738. length: 10,
  11739. gap: 5,
  11740. altLength: undefined
  11741. },
  11742. inheritColor: "from" // to, from, false, true (== from)
  11743. },
  11744. configurePhysics:false,
  11745. physics: {
  11746. barnesHut: {
  11747. enabled: true,
  11748. theta: 1 / 0.6, // inverted to save time during calculation
  11749. gravitationalConstant: -2000,
  11750. centralGravity: 0.3,
  11751. springLength: 95,
  11752. springConstant: 0.04,
  11753. damping: 0.09
  11754. },
  11755. repulsion: {
  11756. centralGravity: 0.0,
  11757. springLength: 200,
  11758. springConstant: 0.05,
  11759. nodeDistance: 100,
  11760. damping: 0.09
  11761. },
  11762. hierarchicalRepulsion: {
  11763. enabled: false,
  11764. centralGravity: 0.0,
  11765. springLength: 100,
  11766. springConstant: 0.01,
  11767. nodeDistance: 150,
  11768. damping: 0.09
  11769. },
  11770. damping: null,
  11771. centralGravity: null,
  11772. springLength: null,
  11773. springConstant: null
  11774. },
  11775. clustering: { // Per Node in Cluster = PNiC
  11776. enabled: false, // (Boolean) | global on/off switch for clustering.
  11777. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  11778. 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
  11779. 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
  11780. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  11781. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  11782. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  11783. 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.
  11784. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  11785. maxFontSize: 1000,
  11786. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  11787. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  11788. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  11789. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  11790. height: 1, // (px PNiC) | growth of the height per node in cluster.
  11791. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  11792. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  11793. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  11794. clusterLevelDifference: 2
  11795. },
  11796. navigation: {
  11797. enabled: false
  11798. },
  11799. keyboard: {
  11800. enabled: false,
  11801. speed: {x: 10, y: 10, zoom: 0.02}
  11802. },
  11803. dataManipulation: {
  11804. enabled: false,
  11805. initiallyVisible: false
  11806. },
  11807. hierarchicalLayout: {
  11808. enabled:false,
  11809. levelSeparation: 150,
  11810. nodeSpacing: 100,
  11811. direction: "UD" // UD, DU, LR, RL
  11812. },
  11813. freezeForStabilization: false,
  11814. smoothCurves: {
  11815. enabled: true,
  11816. dynamic: true,
  11817. type: "continuous",
  11818. roundness: 0.5
  11819. },
  11820. dynamicSmoothCurves: true,
  11821. maxVelocity: 30,
  11822. minVelocity: 0.1, // px/s
  11823. stabilize: true, // stabilize before displaying the network
  11824. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  11825. labels:{
  11826. add:"Add Node",
  11827. edit:"Edit",
  11828. link:"Add Link",
  11829. del:"Delete selected",
  11830. editNode:"Edit Node",
  11831. editEdge:"Edit Edge",
  11832. back:"Back",
  11833. addDescription:"Click in an empty space to place a new node.",
  11834. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  11835. editEdgeDescription:"Click on the control points and drag them to a node to connect to it.",
  11836. addError:"The function for add does not support two arguments (data,callback).",
  11837. linkError:"The function for connect does not support two arguments (data,callback).",
  11838. editError:"The function for edit does not support two arguments (data, callback).",
  11839. editBoundError:"No edit function has been bound to this button.",
  11840. deleteError:"The function for delete does not support two arguments (data, callback).",
  11841. deleteClusterError:"Clusters cannot be deleted."
  11842. },
  11843. tooltip: {
  11844. delay: 300,
  11845. fontColor: 'black',
  11846. fontSize: 14, // px
  11847. fontFace: 'verdana',
  11848. color: {
  11849. border: '#666',
  11850. background: '#FFFFC6'
  11851. }
  11852. },
  11853. dragNetwork: true,
  11854. dragNodes: true,
  11855. zoomable: true,
  11856. hover: false,
  11857. hideEdgesOnDrag: false,
  11858. hideNodesOnDrag: false,
  11859. width : '100%',
  11860. height : '100%',
  11861. selectable: true
  11862. };
  11863. this.constants = util.extend({}, this.defaultOptions);
  11864. this.hoverObj = {nodes:{},edges:{}};
  11865. this.controlNodesActive = false;
  11866. // Node variables
  11867. var network = this;
  11868. this.groups = new Groups(); // object with groups
  11869. this.images = new Images(); // object with images
  11870. this.images.setOnloadCallback(function () {
  11871. network._redraw();
  11872. });
  11873. // keyboard navigation variables
  11874. this.xIncrement = 0;
  11875. this.yIncrement = 0;
  11876. this.zoomIncrement = 0;
  11877. // loading all the mixins:
  11878. // load the force calculation functions, grouped under the physics system.
  11879. this._loadPhysicsSystem();
  11880. // create a frame and canvas
  11881. this._create();
  11882. // load the sector system. (mandatory, fully integrated with Network)
  11883. this._loadSectorSystem();
  11884. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  11885. this._loadClusterSystem();
  11886. // load the selection system. (mandatory, required by Network)
  11887. this._loadSelectionSystem();
  11888. // load the selection system. (mandatory, required by Network)
  11889. this._loadHierarchySystem();
  11890. // apply options
  11891. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11892. this._setScale(1);
  11893. this.setOptions(options);
  11894. // other vars
  11895. this.freezeSimulation = false;// freeze the simulation
  11896. this.cachedFunctions = {};
  11897. // containers for nodes and edges
  11898. this.calculationNodes = {};
  11899. this.calculationNodeIndices = [];
  11900. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  11901. this.nodes = {}; // object with Node objects
  11902. this.edges = {}; // object with Edge objects
  11903. // position and scale variables and objects
  11904. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  11905. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  11906. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  11907. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  11908. this.scale = 1; // defining the global scale variable in the constructor
  11909. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  11910. // datasets or dataviews
  11911. this.nodesData = null; // A DataSet or DataView
  11912. this.edgesData = null; // A DataSet or DataView
  11913. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11914. this.nodesListeners = {
  11915. 'add': function (event, params) {
  11916. network._addNodes(params.items);
  11917. network.start();
  11918. },
  11919. 'update': function (event, params) {
  11920. network._updateNodes(params.items);
  11921. network.start();
  11922. },
  11923. 'remove': function (event, params) {
  11924. network._removeNodes(params.items);
  11925. network.start();
  11926. }
  11927. };
  11928. this.edgesListeners = {
  11929. 'add': function (event, params) {
  11930. network._addEdges(params.items);
  11931. network.start();
  11932. },
  11933. 'update': function (event, params) {
  11934. network._updateEdges(params.items);
  11935. network.start();
  11936. },
  11937. 'remove': function (event, params) {
  11938. network._removeEdges(params.items);
  11939. network.start();
  11940. }
  11941. };
  11942. // properties for the animation
  11943. this.moving = true;
  11944. this.timer = undefined; // Scheduling function. Is definded in this.start();
  11945. // load data (the disable start variable will be the same as the enabled clustering)
  11946. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  11947. // hierarchical layout
  11948. this.initializing = false;
  11949. if (this.constants.hierarchicalLayout.enabled == true) {
  11950. this._setupHierarchicalLayout();
  11951. }
  11952. else {
  11953. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  11954. if (this.constants.stabilize == false) {
  11955. this.zoomExtent(true,this.constants.clustering.enabled);
  11956. }
  11957. }
  11958. // if clustering is disabled, the simulation will have started in the setData function
  11959. if (this.constants.clustering.enabled) {
  11960. this.startWithClustering();
  11961. }
  11962. }
  11963. // Extend Network with an Emitter mixin
  11964. Emitter(Network.prototype);
  11965. /**
  11966. * Get the script path where the vis.js library is located
  11967. *
  11968. * @returns {string | null} path Path or null when not found. Path does not
  11969. * end with a slash.
  11970. * @private
  11971. */
  11972. Network.prototype._getScriptPath = function() {
  11973. var scripts = document.getElementsByTagName( 'script' );
  11974. // find script named vis.js or vis.min.js
  11975. for (var i = 0; i < scripts.length; i++) {
  11976. var src = scripts[i].src;
  11977. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  11978. if (match) {
  11979. // return path without the script name
  11980. return src.substring(0, src.length - match[0].length);
  11981. }
  11982. }
  11983. return null;
  11984. };
  11985. /**
  11986. * Find the center position of the network
  11987. * @private
  11988. */
  11989. Network.prototype._getRange = function() {
  11990. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11991. for (var nodeId in this.nodes) {
  11992. if (this.nodes.hasOwnProperty(nodeId)) {
  11993. node = this.nodes[nodeId];
  11994. if (minX > (node.x)) {minX = node.x;}
  11995. if (maxX < (node.x)) {maxX = node.x;}
  11996. if (minY > (node.y)) {minY = node.y;}
  11997. if (maxY < (node.y)) {maxY = node.y;}
  11998. }
  11999. }
  12000. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  12001. minY = 0, maxY = 0, minX = 0, maxX = 0;
  12002. }
  12003. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  12004. };
  12005. /**
  12006. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  12007. * @returns {{x: number, y: number}}
  12008. * @private
  12009. */
  12010. Network.prototype._findCenter = function(range) {
  12011. return {x: (0.5 * (range.maxX + range.minX)),
  12012. y: (0.5 * (range.maxY + range.minY))};
  12013. };
  12014. /**
  12015. * center the network
  12016. *
  12017. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  12018. */
  12019. Network.prototype._centerNetwork = function(range) {
  12020. var center = this._findCenter(range);
  12021. center.x *= this.scale;
  12022. center.y *= this.scale;
  12023. center.x -= 0.5 * this.frame.canvas.clientWidth;
  12024. center.y -= 0.5 * this.frame.canvas.clientHeight;
  12025. this._setTranslation(-center.x,-center.y); // set at 0,0
  12026. };
  12027. /**
  12028. * This function zooms out to fit all data on screen based on amount of nodes
  12029. *
  12030. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  12031. * @param {Boolean} [disableStart] | If true, start is not called.
  12032. */
  12033. Network.prototype.zoomExtent = function(initialZoom, disableStart) {
  12034. if (initialZoom === undefined) {
  12035. initialZoom = false;
  12036. }
  12037. if (disableStart === undefined) {
  12038. disableStart = false;
  12039. }
  12040. var range = this._getRange();
  12041. var zoomLevel;
  12042. if (initialZoom == true) {
  12043. var numberOfNodes = this.nodeIndices.length;
  12044. if (this.constants.smoothCurves == true) {
  12045. if (this.constants.clustering.enabled == true &&
  12046. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  12047. 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.
  12048. }
  12049. else {
  12050. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  12051. }
  12052. }
  12053. else {
  12054. if (this.constants.clustering.enabled == true &&
  12055. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  12056. 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.
  12057. }
  12058. else {
  12059. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  12060. }
  12061. }
  12062. // correct for larger canvasses.
  12063. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  12064. zoomLevel *= factor;
  12065. }
  12066. else {
  12067. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  12068. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  12069. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  12070. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  12071. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  12072. }
  12073. if (zoomLevel > 1.0) {
  12074. zoomLevel = 1.0;
  12075. }
  12076. this._setScale(zoomLevel);
  12077. this._centerNetwork(range);
  12078. if (disableStart == false) {
  12079. this.moving = true;
  12080. this.start();
  12081. }
  12082. };
  12083. /**
  12084. * Update the this.nodeIndices with the most recent node index list
  12085. * @private
  12086. */
  12087. Network.prototype._updateNodeIndexList = function() {
  12088. this._clearNodeIndexList();
  12089. for (var idx in this.nodes) {
  12090. if (this.nodes.hasOwnProperty(idx)) {
  12091. this.nodeIndices.push(idx);
  12092. }
  12093. }
  12094. };
  12095. /**
  12096. * Set nodes and edges, and optionally options as well.
  12097. *
  12098. * @param {Object} data Object containing parameters:
  12099. * {Array | DataSet | DataView} [nodes] Array with nodes
  12100. * {Array | DataSet | DataView} [edges] Array with edges
  12101. * {String} [dot] String containing data in DOT format
  12102. * {String} [gephi] String containing data in gephi JSON format
  12103. * {Options} [options] Object with options
  12104. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  12105. */
  12106. Network.prototype.setData = function(data, disableStart) {
  12107. if (disableStart === undefined) {
  12108. disableStart = false;
  12109. }
  12110. if (data && data.dot && (data.nodes || data.edges)) {
  12111. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  12112. ' parameter pair "nodes" and "edges", but not both.');
  12113. }
  12114. // set options
  12115. this.setOptions(data && data.options);
  12116. // set all data
  12117. if (data && data.dot) {
  12118. // parse DOT file
  12119. if(data && data.dot) {
  12120. var dotData = dotparser.DOTToGraph(data.dot);
  12121. this.setData(dotData);
  12122. return;
  12123. }
  12124. }
  12125. else if (data && data.gephi) {
  12126. // parse DOT file
  12127. if(data && data.gephi) {
  12128. var gephiData = gephiParser.parseGephi(data.gephi);
  12129. this.setData(gephiData);
  12130. return;
  12131. }
  12132. }
  12133. else {
  12134. this._setNodes(data && data.nodes);
  12135. this._setEdges(data && data.edges);
  12136. }
  12137. this._putDataInSector();
  12138. if (!disableStart) {
  12139. // find a stable position or start animating to a stable position
  12140. if (this.constants.stabilize) {
  12141. var me = this;
  12142. setTimeout(function() {me._stabilize(); me.start();},0)
  12143. }
  12144. else {
  12145. this.start();
  12146. }
  12147. }
  12148. };
  12149. /**
  12150. * Set options
  12151. * @param {Object} options
  12152. * @param {Boolean} [initializeView] | set zoom and translation to default.
  12153. */
  12154. Network.prototype.setOptions = function (options) {
  12155. if (options) {
  12156. var prop;
  12157. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation','keyboard','dataManipulation',
  12158. 'onAdd','onEdit','onEditEdge','onConnect','onDelete'
  12159. ];
  12160. util.selectiveNotDeepExtend(fields,this.constants, options);
  12161. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  12162. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  12163. if (options.physics) {
  12164. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  12165. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  12166. if (options.physics.hierarchicalRepulsion) {
  12167. this.constants.hierarchicalLayout.enabled = true;
  12168. this.constants.physics.hierarchicalRepulsion.enabled = true;
  12169. this.constants.physics.barnesHut.enabled = false;
  12170. for (prop in options.physics.hierarchicalRepulsion) {
  12171. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  12172. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  12173. }
  12174. }
  12175. }
  12176. }
  12177. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  12178. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  12179. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  12180. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  12181. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  12182. util.mergeOptions(this.constants, options,'smoothCurves');
  12183. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  12184. util.mergeOptions(this.constants, options,'clustering');
  12185. util.mergeOptions(this.constants, options,'navigation');
  12186. util.mergeOptions(this.constants, options,'keyboard');
  12187. util.mergeOptions(this.constants, options,'dataManipulation');
  12188. if (options.dataManipulation) {
  12189. this.editMode = this.constants.dataManipulation.initiallyVisible;
  12190. }
  12191. // TODO: work out these options and document them
  12192. if (options.edges) {
  12193. if (options.edges.color !== undefined) {
  12194. if (util.isString(options.edges.color)) {
  12195. this.constants.edges.color = {};
  12196. this.constants.edges.color.color = options.edges.color;
  12197. this.constants.edges.color.highlight = options.edges.color;
  12198. this.constants.edges.color.hover = options.edges.color;
  12199. }
  12200. else {
  12201. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  12202. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  12203. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  12204. }
  12205. }
  12206. if (!options.edges.fontColor) {
  12207. if (options.edges.color !== undefined) {
  12208. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  12209. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  12210. }
  12211. }
  12212. }
  12213. if (options.nodes) {
  12214. if (options.nodes.color) {
  12215. var newColorObj = util.parseColor(options.nodes.color);
  12216. this.constants.nodes.color.background = newColorObj.background;
  12217. this.constants.nodes.color.border = newColorObj.border;
  12218. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  12219. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  12220. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  12221. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  12222. }
  12223. }
  12224. if (options.groups) {
  12225. for (var groupname in options.groups) {
  12226. if (options.groups.hasOwnProperty(groupname)) {
  12227. var group = options.groups[groupname];
  12228. this.groups.add(groupname, group);
  12229. }
  12230. }
  12231. }
  12232. if (options.tooltip) {
  12233. for (prop in options.tooltip) {
  12234. if (options.tooltip.hasOwnProperty(prop)) {
  12235. this.constants.tooltip[prop] = options.tooltip[prop];
  12236. }
  12237. }
  12238. if (options.tooltip.color) {
  12239. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  12240. }
  12241. }
  12242. }
  12243. // (Re)loading the mixins that can be enabled or disabled in the options.
  12244. // load the force calculation functions, grouped under the physics system.
  12245. this._loadPhysicsSystem();
  12246. // load the navigation system.
  12247. this._loadNavigationControls();
  12248. // load the data manipulation system
  12249. this._loadManipulationSystem();
  12250. // configure the smooth curves
  12251. this._configureSmoothCurves();
  12252. // bind keys. If disabled, this will not do anything;
  12253. this._createKeyBinds();
  12254. this.setSize(this.constants.width, this.constants.height);
  12255. this.moving = true;
  12256. this.start();
  12257. };
  12258. /**
  12259. * Create the main frame for the Network.
  12260. * This function is executed once when a Network object is created. The frame
  12261. * contains a canvas, and this canvas contains all objects like the axis and
  12262. * nodes.
  12263. * @private
  12264. */
  12265. Network.prototype._create = function () {
  12266. // remove all elements from the container element.
  12267. while (this.containerElement.hasChildNodes()) {
  12268. this.containerElement.removeChild(this.containerElement.firstChild);
  12269. }
  12270. this.frame = document.createElement('div');
  12271. this.frame.className = 'network-frame';
  12272. this.frame.style.position = 'relative';
  12273. this.frame.style.overflow = 'hidden';
  12274. // create the network canvas (HTML canvas element)
  12275. this.frame.canvas = document.createElement( 'canvas' );
  12276. this.frame.canvas.style.position = 'relative';
  12277. this.frame.appendChild(this.frame.canvas);
  12278. if (!this.frame.canvas.getContext) {
  12279. var noCanvas = document.createElement( 'DIV' );
  12280. noCanvas.style.color = 'red';
  12281. noCanvas.style.fontWeight = 'bold' ;
  12282. noCanvas.style.padding = '10px';
  12283. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  12284. this.frame.canvas.appendChild(noCanvas);
  12285. }
  12286. var me = this;
  12287. this.drag = {};
  12288. this.pinch = {};
  12289. this.hammer = Hammer(this.frame.canvas, {
  12290. prevent_default: true
  12291. });
  12292. this.hammer.on('tap', me._onTap.bind(me) );
  12293. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  12294. this.hammer.on('hold', me._onHold.bind(me) );
  12295. this.hammer.on('pinch', me._onPinch.bind(me) );
  12296. this.hammer.on('touch', me._onTouch.bind(me) );
  12297. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  12298. this.hammer.on('drag', me._onDrag.bind(me) );
  12299. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  12300. this.hammer.on('release', me._onRelease.bind(me) );
  12301. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  12302. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  12303. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  12304. // add the frame to the container element
  12305. this.containerElement.appendChild(this.frame);
  12306. };
  12307. /**
  12308. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  12309. * @private
  12310. */
  12311. Network.prototype._createKeyBinds = function() {
  12312. var me = this;
  12313. this.mousetrap = mousetrap;
  12314. this.mousetrap.reset();
  12315. if (this.constants.keyboard.enabled == true) {
  12316. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  12317. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  12318. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  12319. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  12320. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  12321. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  12322. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  12323. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  12324. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  12325. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  12326. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  12327. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  12328. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  12329. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  12330. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  12331. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  12332. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  12333. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  12334. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  12335. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  12336. }
  12337. if (this.constants.dataManipulation.enabled == true) {
  12338. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  12339. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  12340. }
  12341. };
  12342. /**
  12343. * Get the pointer location from a touch location
  12344. * @param {{pageX: Number, pageY: Number}} touch
  12345. * @return {{x: Number, y: Number}} pointer
  12346. * @private
  12347. */
  12348. Network.prototype._getPointer = function (touch) {
  12349. return {
  12350. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  12351. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  12352. };
  12353. };
  12354. /**
  12355. * On start of a touch gesture, store the pointer
  12356. * @param event
  12357. * @private
  12358. */
  12359. Network.prototype._onTouch = function (event) {
  12360. this.drag.pointer = this._getPointer(event.gesture.center);
  12361. this.drag.pinched = false;
  12362. this.pinch.scale = this._getScale();
  12363. this._handleTouch(this.drag.pointer);
  12364. };
  12365. /**
  12366. * handle drag start event
  12367. * @private
  12368. */
  12369. Network.prototype._onDragStart = function () {
  12370. this._handleDragStart();
  12371. };
  12372. /**
  12373. * This function is called by _onDragStart.
  12374. * It is separated out because we can then overload it for the datamanipulation system.
  12375. *
  12376. * @private
  12377. */
  12378. Network.prototype._handleDragStart = function() {
  12379. var drag = this.drag;
  12380. var node = this._getNodeAt(drag.pointer);
  12381. // note: drag.pointer is set in _onTouch to get the initial touch location
  12382. drag.dragging = true;
  12383. drag.selection = [];
  12384. drag.translation = this._getTranslation();
  12385. drag.nodeId = null;
  12386. if (node != null) {
  12387. drag.nodeId = node.id;
  12388. // select the clicked node if not yet selected
  12389. if (!node.isSelected()) {
  12390. this._selectObject(node,false);
  12391. }
  12392. // create an array with the selected nodes and their original location and status
  12393. for (var objectId in this.selectionObj.nodes) {
  12394. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  12395. var object = this.selectionObj.nodes[objectId];
  12396. var s = {
  12397. id: object.id,
  12398. node: object,
  12399. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  12400. x: object.x,
  12401. y: object.y,
  12402. xFixed: object.xFixed,
  12403. yFixed: object.yFixed
  12404. };
  12405. object.xFixed = true;
  12406. object.yFixed = true;
  12407. drag.selection.push(s);
  12408. }
  12409. }
  12410. }
  12411. };
  12412. /**
  12413. * handle drag event
  12414. * @private
  12415. */
  12416. Network.prototype._onDrag = function (event) {
  12417. this._handleOnDrag(event)
  12418. };
  12419. /**
  12420. * This function is called by _onDrag.
  12421. * It is separated out because we can then overload it for the datamanipulation system.
  12422. *
  12423. * @private
  12424. */
  12425. Network.prototype._handleOnDrag = function(event) {
  12426. if (this.drag.pinched) {
  12427. return;
  12428. }
  12429. var pointer = this._getPointer(event.gesture.center);
  12430. var me = this;
  12431. var drag = this.drag;
  12432. var selection = drag.selection;
  12433. if (selection && selection.length && this.constants.dragNodes == true) {
  12434. // calculate delta's and new location
  12435. var deltaX = pointer.x - drag.pointer.x;
  12436. var deltaY = pointer.y - drag.pointer.y;
  12437. // update position of all selected nodes
  12438. selection.forEach(function (s) {
  12439. var node = s.node;
  12440. if (!s.xFixed) {
  12441. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  12442. }
  12443. if (!s.yFixed) {
  12444. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  12445. }
  12446. });
  12447. // start _animationStep if not yet running
  12448. if (!this.moving) {
  12449. this.moving = true;
  12450. this.start();
  12451. }
  12452. }
  12453. else {
  12454. if (this.constants.dragNetwork == true) {
  12455. // move the network
  12456. var diffX = pointer.x - this.drag.pointer.x;
  12457. var diffY = pointer.y - this.drag.pointer.y;
  12458. this._setTranslation(
  12459. this.drag.translation.x + diffX,
  12460. this.drag.translation.y + diffY
  12461. );
  12462. this._redraw();
  12463. // this.moving = true;
  12464. // this.start();
  12465. }
  12466. }
  12467. };
  12468. /**
  12469. * handle drag start event
  12470. * @private
  12471. */
  12472. Network.prototype._onDragEnd = function () {
  12473. this.drag.dragging = false;
  12474. var selection = this.drag.selection;
  12475. if (selection && selection.length) {
  12476. selection.forEach(function (s) {
  12477. // restore original xFixed and yFixed
  12478. s.node.xFixed = s.xFixed;
  12479. s.node.yFixed = s.yFixed;
  12480. });
  12481. this.moving = true;
  12482. this.start();
  12483. }
  12484. else {
  12485. this._redraw();
  12486. }
  12487. };
  12488. /**
  12489. * handle tap/click event: select/unselect a node
  12490. * @private
  12491. */
  12492. Network.prototype._onTap = function (event) {
  12493. var pointer = this._getPointer(event.gesture.center);
  12494. this.pointerPosition = pointer;
  12495. this._handleTap(pointer);
  12496. };
  12497. /**
  12498. * handle doubletap event
  12499. * @private
  12500. */
  12501. Network.prototype._onDoubleTap = function (event) {
  12502. var pointer = this._getPointer(event.gesture.center);
  12503. this._handleDoubleTap(pointer);
  12504. };
  12505. /**
  12506. * handle long tap event: multi select nodes
  12507. * @private
  12508. */
  12509. Network.prototype._onHold = function (event) {
  12510. var pointer = this._getPointer(event.gesture.center);
  12511. this.pointerPosition = pointer;
  12512. this._handleOnHold(pointer);
  12513. };
  12514. /**
  12515. * handle the release of the screen
  12516. *
  12517. * @private
  12518. */
  12519. Network.prototype._onRelease = function (event) {
  12520. var pointer = this._getPointer(event.gesture.center);
  12521. this._handleOnRelease(pointer);
  12522. };
  12523. /**
  12524. * Handle pinch event
  12525. * @param event
  12526. * @private
  12527. */
  12528. Network.prototype._onPinch = function (event) {
  12529. var pointer = this._getPointer(event.gesture.center);
  12530. this.drag.pinched = true;
  12531. if (!('scale' in this.pinch)) {
  12532. this.pinch.scale = 1;
  12533. }
  12534. // TODO: enabled moving while pinching?
  12535. var scale = this.pinch.scale * event.gesture.scale;
  12536. this._zoom(scale, pointer)
  12537. };
  12538. /**
  12539. * Zoom the network in or out
  12540. * @param {Number} scale a number around 1, and between 0.01 and 10
  12541. * @param {{x: Number, y: Number}} pointer Position on screen
  12542. * @return {Number} appliedScale scale is limited within the boundaries
  12543. * @private
  12544. */
  12545. Network.prototype._zoom = function(scale, pointer) {
  12546. if (this.constants.zoomable == true) {
  12547. var scaleOld = this._getScale();
  12548. if (scale < 0.00001) {
  12549. scale = 0.00001;
  12550. }
  12551. if (scale > 10) {
  12552. scale = 10;
  12553. }
  12554. var preScaleDragPointer = null;
  12555. if (this.drag !== undefined) {
  12556. if (this.drag.dragging == true) {
  12557. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  12558. }
  12559. }
  12560. // + this.frame.canvas.clientHeight / 2
  12561. var translation = this._getTranslation();
  12562. var scaleFrac = scale / scaleOld;
  12563. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  12564. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  12565. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  12566. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  12567. this._setScale(scale);
  12568. this._setTranslation(tx, ty);
  12569. this.updateClustersDefault();
  12570. if (preScaleDragPointer != null) {
  12571. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  12572. this.drag.pointer.x = postScaleDragPointer.x;
  12573. this.drag.pointer.y = postScaleDragPointer.y;
  12574. }
  12575. this._redraw();
  12576. if (scaleOld < scale) {
  12577. this.emit("zoom", {direction:"+"});
  12578. }
  12579. else {
  12580. this.emit("zoom", {direction:"-"});
  12581. }
  12582. return scale;
  12583. }
  12584. };
  12585. /**
  12586. * Event handler for mouse wheel event, used to zoom the timeline
  12587. * See http://adomas.org/javascript-mouse-wheel/
  12588. * https://github.com/EightMedia/hammer.js/issues/256
  12589. * @param {MouseEvent} event
  12590. * @private
  12591. */
  12592. Network.prototype._onMouseWheel = function(event) {
  12593. // retrieve delta
  12594. var delta = 0;
  12595. if (event.wheelDelta) { /* IE/Opera. */
  12596. delta = event.wheelDelta/120;
  12597. } else if (event.detail) { /* Mozilla case. */
  12598. // In Mozilla, sign of delta is different than in IE.
  12599. // Also, delta is multiple of 3.
  12600. delta = -event.detail/3;
  12601. }
  12602. // If delta is nonzero, handle it.
  12603. // Basically, delta is now positive if wheel was scrolled up,
  12604. // and negative, if wheel was scrolled down.
  12605. if (delta) {
  12606. // calculate the new scale
  12607. var scale = this._getScale();
  12608. var zoom = delta / 10;
  12609. if (delta < 0) {
  12610. zoom = zoom / (1 - zoom);
  12611. }
  12612. scale *= (1 + zoom);
  12613. // calculate the pointer location
  12614. var gesture = hammerUtil.fakeGesture(this, event);
  12615. var pointer = this._getPointer(gesture.center);
  12616. // apply the new scale
  12617. this._zoom(scale, pointer);
  12618. }
  12619. // Prevent default actions caused by mouse wheel.
  12620. event.preventDefault();
  12621. };
  12622. /**
  12623. * Mouse move handler for checking whether the title moves over a node with a title.
  12624. * @param {Event} event
  12625. * @private
  12626. */
  12627. Network.prototype._onMouseMoveTitle = function (event) {
  12628. var gesture = hammerUtil.fakeGesture(this, event);
  12629. var pointer = this._getPointer(gesture.center);
  12630. // check if the previously selected node is still selected
  12631. if (this.popupObj) {
  12632. this._checkHidePopup(pointer);
  12633. }
  12634. // start a timeout that will check if the mouse is positioned above
  12635. // an element
  12636. var me = this;
  12637. var checkShow = function() {
  12638. me._checkShowPopup(pointer);
  12639. };
  12640. if (this.popupTimer) {
  12641. clearInterval(this.popupTimer); // stop any running calculationTimer
  12642. }
  12643. if (!this.drag.dragging) {
  12644. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  12645. }
  12646. /**
  12647. * Adding hover highlights
  12648. */
  12649. if (this.constants.hover == true) {
  12650. // removing all hover highlights
  12651. for (var edgeId in this.hoverObj.edges) {
  12652. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  12653. this.hoverObj.edges[edgeId].hover = false;
  12654. delete this.hoverObj.edges[edgeId];
  12655. }
  12656. }
  12657. // adding hover highlights
  12658. var obj = this._getNodeAt(pointer);
  12659. if (obj == null) {
  12660. obj = this._getEdgeAt(pointer);
  12661. }
  12662. if (obj != null) {
  12663. this._hoverObject(obj);
  12664. }
  12665. // removing all node hover highlights except for the selected one.
  12666. for (var nodeId in this.hoverObj.nodes) {
  12667. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  12668. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  12669. this._blurObject(this.hoverObj.nodes[nodeId]);
  12670. delete this.hoverObj.nodes[nodeId];
  12671. }
  12672. }
  12673. }
  12674. this.redraw();
  12675. }
  12676. };
  12677. /**
  12678. * Check if there is an element on the given position in the network
  12679. * (a node or edge). If so, and if this element has a title,
  12680. * show a popup window with its title.
  12681. *
  12682. * @param {{x:Number, y:Number}} pointer
  12683. * @private
  12684. */
  12685. Network.prototype._checkShowPopup = function (pointer) {
  12686. var obj = {
  12687. left: this._XconvertDOMtoCanvas(pointer.x),
  12688. top: this._YconvertDOMtoCanvas(pointer.y),
  12689. right: this._XconvertDOMtoCanvas(pointer.x),
  12690. bottom: this._YconvertDOMtoCanvas(pointer.y)
  12691. };
  12692. var id;
  12693. var lastPopupNode = this.popupObj;
  12694. if (this.popupObj == undefined) {
  12695. // search the nodes for overlap, select the top one in case of multiple nodes
  12696. var nodes = this.nodes;
  12697. for (id in nodes) {
  12698. if (nodes.hasOwnProperty(id)) {
  12699. var node = nodes[id];
  12700. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  12701. this.popupObj = node;
  12702. break;
  12703. }
  12704. }
  12705. }
  12706. }
  12707. if (this.popupObj === undefined) {
  12708. // search the edges for overlap
  12709. var edges = this.edges;
  12710. for (id in edges) {
  12711. if (edges.hasOwnProperty(id)) {
  12712. var edge = edges[id];
  12713. if (edge.connected && (edge.getTitle() !== undefined) &&
  12714. edge.isOverlappingWith(obj)) {
  12715. this.popupObj = edge;
  12716. break;
  12717. }
  12718. }
  12719. }
  12720. }
  12721. if (this.popupObj) {
  12722. // show popup message window
  12723. if (this.popupObj != lastPopupNode) {
  12724. var me = this;
  12725. if (!me.popup) {
  12726. me.popup = new Popup(me.frame, me.constants.tooltip);
  12727. }
  12728. // adjust a small offset such that the mouse cursor is located in the
  12729. // bottom left location of the popup, and you can easily move over the
  12730. // popup area
  12731. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  12732. me.popup.setText(me.popupObj.getTitle());
  12733. me.popup.show();
  12734. }
  12735. }
  12736. else {
  12737. if (this.popup) {
  12738. this.popup.hide();
  12739. }
  12740. }
  12741. };
  12742. /**
  12743. * Check if the popup must be hided, which is the case when the mouse is no
  12744. * longer hovering on the object
  12745. * @param {{x:Number, y:Number}} pointer
  12746. * @private
  12747. */
  12748. Network.prototype._checkHidePopup = function (pointer) {
  12749. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  12750. this.popupObj = undefined;
  12751. if (this.popup) {
  12752. this.popup.hide();
  12753. }
  12754. }
  12755. };
  12756. /**
  12757. * Set a new size for the network
  12758. * @param {string} width Width in pixels or percentage (for example '800px'
  12759. * or '50%')
  12760. * @param {string} height Height in pixels or percentage (for example '400px'
  12761. * or '30%')
  12762. */
  12763. Network.prototype.setSize = function(width, height) {
  12764. this.frame.style.width = width;
  12765. this.frame.style.height = height;
  12766. this.frame.canvas.style.width = '100%';
  12767. this.frame.canvas.style.height = '100%';
  12768. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12769. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12770. if (this.manipulationDiv !== undefined) {
  12771. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  12772. }
  12773. if (this.navigationDivs !== undefined) {
  12774. if (this.navigationDivs['wrapper'] !== undefined) {
  12775. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  12776. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  12777. }
  12778. }
  12779. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  12780. };
  12781. /**
  12782. * Set a data set with nodes for the network
  12783. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12784. * @private
  12785. */
  12786. Network.prototype._setNodes = function(nodes) {
  12787. var oldNodesData = this.nodesData;
  12788. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12789. this.nodesData = nodes;
  12790. }
  12791. else if (nodes instanceof Array) {
  12792. this.nodesData = new DataSet();
  12793. this.nodesData.add(nodes);
  12794. }
  12795. else if (!nodes) {
  12796. this.nodesData = new DataSet();
  12797. }
  12798. else {
  12799. throw new TypeError('Array or DataSet expected');
  12800. }
  12801. if (oldNodesData) {
  12802. // unsubscribe from old dataset
  12803. util.forEach(this.nodesListeners, function (callback, event) {
  12804. oldNodesData.off(event, callback);
  12805. });
  12806. }
  12807. // remove drawn nodes
  12808. this.nodes = {};
  12809. if (this.nodesData) {
  12810. // subscribe to new dataset
  12811. var me = this;
  12812. util.forEach(this.nodesListeners, function (callback, event) {
  12813. me.nodesData.on(event, callback);
  12814. });
  12815. // draw all new nodes
  12816. var ids = this.nodesData.getIds();
  12817. this._addNodes(ids);
  12818. }
  12819. this._updateSelection();
  12820. };
  12821. /**
  12822. * Add nodes
  12823. * @param {Number[] | String[]} ids
  12824. * @private
  12825. */
  12826. Network.prototype._addNodes = function(ids) {
  12827. var id;
  12828. for (var i = 0, len = ids.length; i < len; i++) {
  12829. id = ids[i];
  12830. var data = this.nodesData.get(id);
  12831. var node = new Node(data, this.images, this.groups, this.constants);
  12832. this.nodes[id] = node; // note: this may replace an existing node
  12833. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  12834. var radius = 10 * 0.1*ids.length;
  12835. var angle = 2 * Math.PI * Math.random();
  12836. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12837. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12838. }
  12839. this.moving = true;
  12840. }
  12841. this._updateNodeIndexList();
  12842. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  12843. this._resetLevels();
  12844. this._setupHierarchicalLayout();
  12845. }
  12846. this._updateCalculationNodes();
  12847. this._reconnectEdges();
  12848. this._updateValueRange(this.nodes);
  12849. this.updateLabels();
  12850. };
  12851. /**
  12852. * Update existing nodes, or create them when not yet existing
  12853. * @param {Number[] | String[]} ids
  12854. * @private
  12855. */
  12856. Network.prototype._updateNodes = function(ids) {
  12857. var nodes = this.nodes,
  12858. nodesData = this.nodesData;
  12859. for (var i = 0, len = ids.length; i < len; i++) {
  12860. var id = ids[i];
  12861. var node = nodes[id];
  12862. var data = nodesData.get(id);
  12863. if (node) {
  12864. // update node
  12865. node.setProperties(data, this.constants);
  12866. }
  12867. else {
  12868. // create node
  12869. node = new Node(properties, this.images, this.groups, this.constants);
  12870. nodes[id] = node;
  12871. }
  12872. }
  12873. this.moving = true;
  12874. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  12875. this._resetLevels();
  12876. this._setupHierarchicalLayout();
  12877. }
  12878. this._updateNodeIndexList();
  12879. this._reconnectEdges();
  12880. this._updateValueRange(nodes);
  12881. };
  12882. /**
  12883. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12884. * @param {Number[] | String[]} ids
  12885. * @private
  12886. */
  12887. Network.prototype._removeNodes = function(ids) {
  12888. var nodes = this.nodes;
  12889. for (var i = 0, len = ids.length; i < len; i++) {
  12890. var id = ids[i];
  12891. delete nodes[id];
  12892. }
  12893. this._updateNodeIndexList();
  12894. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  12895. this._resetLevels();
  12896. this._setupHierarchicalLayout();
  12897. }
  12898. this._updateCalculationNodes();
  12899. this._reconnectEdges();
  12900. this._updateSelection();
  12901. this._updateValueRange(nodes);
  12902. };
  12903. /**
  12904. * Load edges by reading the data table
  12905. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12906. * @private
  12907. * @private
  12908. */
  12909. Network.prototype._setEdges = function(edges) {
  12910. var oldEdgesData = this.edgesData;
  12911. if (edges instanceof DataSet || edges instanceof DataView) {
  12912. this.edgesData = edges;
  12913. }
  12914. else if (edges instanceof Array) {
  12915. this.edgesData = new DataSet();
  12916. this.edgesData.add(edges);
  12917. }
  12918. else if (!edges) {
  12919. this.edgesData = new DataSet();
  12920. }
  12921. else {
  12922. throw new TypeError('Array or DataSet expected');
  12923. }
  12924. if (oldEdgesData) {
  12925. // unsubscribe from old dataset
  12926. util.forEach(this.edgesListeners, function (callback, event) {
  12927. oldEdgesData.off(event, callback);
  12928. });
  12929. }
  12930. // remove drawn edges
  12931. this.edges = {};
  12932. if (this.edgesData) {
  12933. // subscribe to new dataset
  12934. var me = this;
  12935. util.forEach(this.edgesListeners, function (callback, event) {
  12936. me.edgesData.on(event, callback);
  12937. });
  12938. // draw all new nodes
  12939. var ids = this.edgesData.getIds();
  12940. this._addEdges(ids);
  12941. }
  12942. this._reconnectEdges();
  12943. };
  12944. /**
  12945. * Add edges
  12946. * @param {Number[] | String[]} ids
  12947. * @private
  12948. */
  12949. Network.prototype._addEdges = function (ids) {
  12950. var edges = this.edges,
  12951. edgesData = this.edgesData;
  12952. for (var i = 0, len = ids.length; i < len; i++) {
  12953. var id = ids[i];
  12954. var oldEdge = edges[id];
  12955. if (oldEdge) {
  12956. oldEdge.disconnect();
  12957. }
  12958. var data = edgesData.get(id, {"showInternalIds" : true});
  12959. edges[id] = new Edge(data, this, this.constants);
  12960. }
  12961. this.moving = true;
  12962. this._updateValueRange(edges);
  12963. this._createBezierNodes();
  12964. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  12965. this._resetLevels();
  12966. this._setupHierarchicalLayout();
  12967. }
  12968. this._updateCalculationNodes();
  12969. };
  12970. /**
  12971. * Update existing edges, or create them when not yet existing
  12972. * @param {Number[] | String[]} ids
  12973. * @private
  12974. */
  12975. Network.prototype._updateEdges = function (ids) {
  12976. var edges = this.edges,
  12977. edgesData = this.edgesData;
  12978. for (var i = 0, len = ids.length; i < len; i++) {
  12979. var id = ids[i];
  12980. var data = edgesData.get(id);
  12981. var edge = edges[id];
  12982. if (edge) {
  12983. // update edge
  12984. edge.disconnect();
  12985. edge.setProperties(data, this.constants);
  12986. edge.connect();
  12987. }
  12988. else {
  12989. // create edge
  12990. edge = new Edge(data, this, this.constants);
  12991. this.edges[id] = edge;
  12992. }
  12993. }
  12994. this._createBezierNodes();
  12995. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  12996. this._resetLevels();
  12997. this._setupHierarchicalLayout();
  12998. }
  12999. this.moving = true;
  13000. this._updateValueRange(edges);
  13001. };
  13002. /**
  13003. * Remove existing edges. Non existing ids will be ignored
  13004. * @param {Number[] | String[]} ids
  13005. * @private
  13006. */
  13007. Network.prototype._removeEdges = function (ids) {
  13008. var edges = this.edges;
  13009. for (var i = 0, len = ids.length; i < len; i++) {
  13010. var id = ids[i];
  13011. var edge = edges[id];
  13012. if (edge) {
  13013. if (edge.via != null) {
  13014. delete this.sectors['support']['nodes'][edge.via.id];
  13015. }
  13016. edge.disconnect();
  13017. delete edges[id];
  13018. }
  13019. }
  13020. this.moving = true;
  13021. this._updateValueRange(edges);
  13022. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  13023. this._resetLevels();
  13024. this._setupHierarchicalLayout();
  13025. }
  13026. this._updateCalculationNodes();
  13027. };
  13028. /**
  13029. * Reconnect all edges
  13030. * @private
  13031. */
  13032. Network.prototype._reconnectEdges = function() {
  13033. var id,
  13034. nodes = this.nodes,
  13035. edges = this.edges;
  13036. for (id in nodes) {
  13037. if (nodes.hasOwnProperty(id)) {
  13038. nodes[id].edges = [];
  13039. }
  13040. }
  13041. for (id in edges) {
  13042. if (edges.hasOwnProperty(id)) {
  13043. var edge = edges[id];
  13044. edge.from = null;
  13045. edge.to = null;
  13046. edge.connect();
  13047. }
  13048. }
  13049. };
  13050. /**
  13051. * Update the values of all object in the given array according to the current
  13052. * value range of the objects in the array.
  13053. * @param {Object} obj An object containing a set of Edges or Nodes
  13054. * The objects must have a method getValue() and
  13055. * setValueRange(min, max).
  13056. * @private
  13057. */
  13058. Network.prototype._updateValueRange = function(obj) {
  13059. var id;
  13060. // determine the range of the objects
  13061. var valueMin = undefined;
  13062. var valueMax = undefined;
  13063. for (id in obj) {
  13064. if (obj.hasOwnProperty(id)) {
  13065. var value = obj[id].getValue();
  13066. if (value !== undefined) {
  13067. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  13068. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  13069. }
  13070. }
  13071. }
  13072. // adjust the range of all objects
  13073. if (valueMin !== undefined && valueMax !== undefined) {
  13074. for (id in obj) {
  13075. if (obj.hasOwnProperty(id)) {
  13076. obj[id].setValueRange(valueMin, valueMax);
  13077. }
  13078. }
  13079. }
  13080. };
  13081. /**
  13082. * Redraw the network with the current data
  13083. * chart will be resized too.
  13084. */
  13085. Network.prototype.redraw = function() {
  13086. this.setSize(this.constants.width, this.constants.height);
  13087. this._redraw();
  13088. };
  13089. /**
  13090. * Redraw the network with the current data
  13091. * @private
  13092. */
  13093. Network.prototype._redraw = function() {
  13094. var ctx = this.frame.canvas.getContext('2d');
  13095. // clear the canvas
  13096. var w = this.frame.canvas.width;
  13097. var h = this.frame.canvas.height;
  13098. ctx.clearRect(0, 0, w, h);
  13099. // set scaling and translation
  13100. ctx.save();
  13101. ctx.translate(this.translation.x, this.translation.y);
  13102. ctx.scale(this.scale, this.scale);
  13103. this.canvasTopLeft = {
  13104. "x": this._XconvertDOMtoCanvas(0),
  13105. "y": this._YconvertDOMtoCanvas(0)
  13106. };
  13107. this.canvasBottomRight = {
  13108. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  13109. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  13110. };
  13111. this._doInAllSectors("_drawAllSectorNodes",ctx);
  13112. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  13113. this._doInAllSectors("_drawEdges",ctx);
  13114. }
  13115. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  13116. this._doInAllSectors("_drawNodes",ctx,false);
  13117. }
  13118. if (this.controlNodesActive == true) {
  13119. this._doInAllSectors("_drawControlNodes",ctx);
  13120. }
  13121. // this._doInSupportSector("_drawNodes",ctx,true);
  13122. // this._drawTree(ctx,"#F00F0F");
  13123. // restore original scaling and translation
  13124. ctx.restore();
  13125. };
  13126. /**
  13127. * Set the translation of the network
  13128. * @param {Number} offsetX Horizontal offset
  13129. * @param {Number} offsetY Vertical offset
  13130. * @private
  13131. */
  13132. Network.prototype._setTranslation = function(offsetX, offsetY) {
  13133. if (this.translation === undefined) {
  13134. this.translation = {
  13135. x: 0,
  13136. y: 0
  13137. };
  13138. }
  13139. if (offsetX !== undefined) {
  13140. this.translation.x = offsetX;
  13141. }
  13142. if (offsetY !== undefined) {
  13143. this.translation.y = offsetY;
  13144. }
  13145. this.emit('viewChanged');
  13146. };
  13147. /**
  13148. * Get the translation of the network
  13149. * @return {Object} translation An object with parameters x and y, both a number
  13150. * @private
  13151. */
  13152. Network.prototype._getTranslation = function() {
  13153. return {
  13154. x: this.translation.x,
  13155. y: this.translation.y
  13156. };
  13157. };
  13158. /**
  13159. * Scale the network
  13160. * @param {Number} scale Scaling factor 1.0 is unscaled
  13161. * @private
  13162. */
  13163. Network.prototype._setScale = function(scale) {
  13164. this.scale = scale;
  13165. };
  13166. /**
  13167. * Get the current scale of the network
  13168. * @return {Number} scale Scaling factor 1.0 is unscaled
  13169. * @private
  13170. */
  13171. Network.prototype._getScale = function() {
  13172. return this.scale;
  13173. };
  13174. /**
  13175. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  13176. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  13177. * @param {number} x
  13178. * @returns {number}
  13179. * @private
  13180. */
  13181. Network.prototype._XconvertDOMtoCanvas = function(x) {
  13182. return (x - this.translation.x) / this.scale;
  13183. };
  13184. /**
  13185. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  13186. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  13187. * @param {number} x
  13188. * @returns {number}
  13189. * @private
  13190. */
  13191. Network.prototype._XconvertCanvasToDOM = function(x) {
  13192. return x * this.scale + this.translation.x;
  13193. };
  13194. /**
  13195. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  13196. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  13197. * @param {number} y
  13198. * @returns {number}
  13199. * @private
  13200. */
  13201. Network.prototype._YconvertDOMtoCanvas = function(y) {
  13202. return (y - this.translation.y) / this.scale;
  13203. };
  13204. /**
  13205. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  13206. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  13207. * @param {number} y
  13208. * @returns {number}
  13209. * @private
  13210. */
  13211. Network.prototype._YconvertCanvasToDOM = function(y) {
  13212. return y * this.scale + this.translation.y ;
  13213. };
  13214. /**
  13215. *
  13216. * @param {object} pos = {x: number, y: number}
  13217. * @returns {{x: number, y: number}}
  13218. * @constructor
  13219. */
  13220. Network.prototype.canvasToDOM = function(pos) {
  13221. return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)};
  13222. }
  13223. /**
  13224. *
  13225. * @param {object} pos = {x: number, y: number}
  13226. * @returns {{x: number, y: number}}
  13227. * @constructor
  13228. */
  13229. Network.prototype.DOMtoCanvas = function(pos) {
  13230. return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)};
  13231. }
  13232. /**
  13233. * Redraw all nodes
  13234. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  13235. * @param {CanvasRenderingContext2D} ctx
  13236. * @param {Boolean} [alwaysShow]
  13237. * @private
  13238. */
  13239. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  13240. if (alwaysShow === undefined) {
  13241. alwaysShow = false;
  13242. }
  13243. // first draw the unselected nodes
  13244. var nodes = this.nodes;
  13245. var selected = [];
  13246. for (var id in nodes) {
  13247. if (nodes.hasOwnProperty(id)) {
  13248. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  13249. if (nodes[id].isSelected()) {
  13250. selected.push(id);
  13251. }
  13252. else {
  13253. if (nodes[id].inArea() || alwaysShow) {
  13254. nodes[id].draw(ctx);
  13255. }
  13256. }
  13257. }
  13258. }
  13259. // draw the selected nodes on top
  13260. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  13261. if (nodes[selected[s]].inArea() || alwaysShow) {
  13262. nodes[selected[s]].draw(ctx);
  13263. }
  13264. }
  13265. };
  13266. /**
  13267. * Redraw all edges
  13268. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  13269. * @param {CanvasRenderingContext2D} ctx
  13270. * @private
  13271. */
  13272. Network.prototype._drawEdges = function(ctx) {
  13273. var edges = this.edges;
  13274. for (var id in edges) {
  13275. if (edges.hasOwnProperty(id)) {
  13276. var edge = edges[id];
  13277. edge.setScale(this.scale);
  13278. if (edge.connected) {
  13279. edges[id].draw(ctx);
  13280. }
  13281. }
  13282. }
  13283. };
  13284. /**
  13285. * Redraw all edges
  13286. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  13287. * @param {CanvasRenderingContext2D} ctx
  13288. * @private
  13289. */
  13290. Network.prototype._drawControlNodes = function(ctx) {
  13291. var edges = this.edges;
  13292. for (var id in edges) {
  13293. if (edges.hasOwnProperty(id)) {
  13294. edges[id]._drawControlNodes(ctx);
  13295. }
  13296. }
  13297. };
  13298. /**
  13299. * Find a stable position for all nodes
  13300. * @private
  13301. */
  13302. Network.prototype._stabilize = function() {
  13303. if (this.constants.freezeForStabilization == true) {
  13304. this._freezeDefinedNodes();
  13305. }
  13306. // find stable position
  13307. var count = 0;
  13308. while (this.moving && count < this.constants.stabilizationIterations) {
  13309. this._physicsTick();
  13310. count++;
  13311. }
  13312. this.zoomExtent(false,true);
  13313. if (this.constants.freezeForStabilization == true) {
  13314. this._restoreFrozenNodes();
  13315. }
  13316. this.emit("stabilized",{iterations:count});
  13317. };
  13318. /**
  13319. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  13320. * because only the supportnodes for the smoothCurves have to settle.
  13321. *
  13322. * @private
  13323. */
  13324. Network.prototype._freezeDefinedNodes = function() {
  13325. var nodes = this.nodes;
  13326. for (var id in nodes) {
  13327. if (nodes.hasOwnProperty(id)) {
  13328. if (nodes[id].x != null && nodes[id].y != null) {
  13329. nodes[id].fixedData.x = nodes[id].xFixed;
  13330. nodes[id].fixedData.y = nodes[id].yFixed;
  13331. nodes[id].xFixed = true;
  13332. nodes[id].yFixed = true;
  13333. }
  13334. }
  13335. }
  13336. };
  13337. /**
  13338. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  13339. *
  13340. * @private
  13341. */
  13342. Network.prototype._restoreFrozenNodes = function() {
  13343. var nodes = this.nodes;
  13344. for (var id in nodes) {
  13345. if (nodes.hasOwnProperty(id)) {
  13346. if (nodes[id].fixedData.x != null) {
  13347. nodes[id].xFixed = nodes[id].fixedData.x;
  13348. nodes[id].yFixed = nodes[id].fixedData.y;
  13349. }
  13350. }
  13351. }
  13352. };
  13353. /**
  13354. * Check if any of the nodes is still moving
  13355. * @param {number} vmin the minimum velocity considered as 'moving'
  13356. * @return {boolean} true if moving, false if non of the nodes is moving
  13357. * @private
  13358. */
  13359. Network.prototype._isMoving = function(vmin) {
  13360. var nodes = this.nodes;
  13361. for (var id in nodes) {
  13362. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  13363. return true;
  13364. }
  13365. }
  13366. return false;
  13367. };
  13368. /**
  13369. * /**
  13370. * Perform one discrete step for all nodes
  13371. *
  13372. * @private
  13373. */
  13374. Network.prototype._discreteStepNodes = function() {
  13375. var interval = this.physicsDiscreteStepsize;
  13376. var nodes = this.nodes;
  13377. var nodeId;
  13378. var nodesPresent = false;
  13379. if (this.constants.maxVelocity > 0) {
  13380. for (nodeId in nodes) {
  13381. if (nodes.hasOwnProperty(nodeId)) {
  13382. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  13383. nodesPresent = true;
  13384. }
  13385. }
  13386. }
  13387. else {
  13388. for (nodeId in nodes) {
  13389. if (nodes.hasOwnProperty(nodeId)) {
  13390. nodes[nodeId].discreteStep(interval);
  13391. nodesPresent = true;
  13392. }
  13393. }
  13394. }
  13395. if (nodesPresent == true) {
  13396. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  13397. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  13398. this.moving = true;
  13399. }
  13400. else {
  13401. this.moving = this._isMoving(vminCorrected);
  13402. if (this.moving == false) {
  13403. this.emit("stabilized",{iterations:null});
  13404. }
  13405. this.moving = this.moving || this.configurePhysics;
  13406. }
  13407. }
  13408. };
  13409. /**
  13410. * A single simulation step (or "tick") in the physics simulation
  13411. *
  13412. * @private
  13413. */
  13414. Network.prototype._physicsTick = function() {
  13415. if (!this.freezeSimulation) {
  13416. if (this.moving == true) {
  13417. this._doInAllActiveSectors("_initializeForceCalculation");
  13418. this._doInAllActiveSectors("_discreteStepNodes");
  13419. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  13420. this._doInSupportSector("_discreteStepNodes");
  13421. }
  13422. this._findCenter(this._getRange())
  13423. }
  13424. }
  13425. };
  13426. /**
  13427. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  13428. * It reschedules itself at the beginning of the function
  13429. *
  13430. * @private
  13431. */
  13432. Network.prototype._animationStep = function() {
  13433. // reset the timer so a new scheduled animation step can be set
  13434. this.timer = undefined;
  13435. // handle the keyboad movement
  13436. this._handleNavigation();
  13437. // this schedules a new animation step
  13438. this.start();
  13439. // start the physics simulation
  13440. var calculationTime = Date.now();
  13441. var maxSteps = 1;
  13442. this._physicsTick();
  13443. var timeRequired = Date.now() - calculationTime;
  13444. while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  13445. this._physicsTick();
  13446. timeRequired = Date.now() - calculationTime;
  13447. maxSteps++;
  13448. }
  13449. // start the rendering process
  13450. var renderTime = Date.now();
  13451. this._redraw();
  13452. this.renderTime = Date.now() - renderTime;
  13453. };
  13454. if (typeof window !== 'undefined') {
  13455. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  13456. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  13457. }
  13458. /**
  13459. * Schedule a animation step with the refreshrate interval.
  13460. */
  13461. Network.prototype.start = function() {
  13462. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  13463. if (!this.timer) {
  13464. var ua = navigator.userAgent.toLowerCase();
  13465. var requiresTimeout = false;
  13466. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  13467. requiresTimeout = true;
  13468. }
  13469. else if (ua.indexOf('safari') != -1) { // safari
  13470. if (ua.indexOf('chrome') <= -1) {
  13471. requiresTimeout = true;
  13472. }
  13473. }
  13474. if (requiresTimeout == true) {
  13475. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  13476. }
  13477. else{
  13478. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  13479. }
  13480. }
  13481. }
  13482. else {
  13483. this._redraw();
  13484. }
  13485. };
  13486. /**
  13487. * Move the network according to the keyboard presses.
  13488. *
  13489. * @private
  13490. */
  13491. Network.prototype._handleNavigation = function() {
  13492. if (this.xIncrement != 0 || this.yIncrement != 0) {
  13493. var translation = this._getTranslation();
  13494. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  13495. }
  13496. if (this.zoomIncrement != 0) {
  13497. var center = {
  13498. x: this.frame.canvas.clientWidth / 2,
  13499. y: this.frame.canvas.clientHeight / 2
  13500. };
  13501. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  13502. }
  13503. };
  13504. /**
  13505. * Freeze the _animationStep
  13506. */
  13507. Network.prototype.toggleFreeze = function() {
  13508. if (this.freezeSimulation == false) {
  13509. this.freezeSimulation = true;
  13510. }
  13511. else {
  13512. this.freezeSimulation = false;
  13513. this.start();
  13514. }
  13515. };
  13516. /**
  13517. * This function cleans the support nodes if they are not needed and adds them when they are.
  13518. *
  13519. * @param {boolean} [disableStart]
  13520. * @private
  13521. */
  13522. Network.prototype._configureSmoothCurves = function(disableStart) {
  13523. if (disableStart === undefined) {
  13524. disableStart = true;
  13525. }
  13526. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  13527. this._createBezierNodes();
  13528. // cleanup unused support nodes
  13529. for (var nodeId in this.sectors['support']['nodes']) {
  13530. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  13531. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  13532. delete this.sectors['support']['nodes'][nodeId];
  13533. }
  13534. }
  13535. }
  13536. }
  13537. else {
  13538. // delete the support nodes
  13539. this.sectors['support']['nodes'] = {};
  13540. for (var edgeId in this.edges) {
  13541. if (this.edges.hasOwnProperty(edgeId)) {
  13542. this.edges[edgeId].via = null;
  13543. }
  13544. }
  13545. }
  13546. this._updateCalculationNodes();
  13547. if (!disableStart) {
  13548. this.moving = true;
  13549. this.start();
  13550. }
  13551. };
  13552. /**
  13553. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  13554. * are used for the force calculation.
  13555. *
  13556. * @private
  13557. */
  13558. Network.prototype._createBezierNodes = function() {
  13559. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  13560. for (var edgeId in this.edges) {
  13561. if (this.edges.hasOwnProperty(edgeId)) {
  13562. var edge = this.edges[edgeId];
  13563. if (edge.via == null) {
  13564. var nodeId = "edgeId:".concat(edge.id);
  13565. this.sectors['support']['nodes'][nodeId] = new Node(
  13566. {id:nodeId,
  13567. mass:1,
  13568. shape:'circle',
  13569. image:"",
  13570. internalMultiplier:1
  13571. },{},{},this.constants);
  13572. edge.via = this.sectors['support']['nodes'][nodeId];
  13573. edge.via.parentEdgeId = edge.id;
  13574. edge.positionBezierNode();
  13575. }
  13576. }
  13577. }
  13578. }
  13579. };
  13580. /**
  13581. * load the functions that load the mixins into the prototype.
  13582. *
  13583. * @private
  13584. */
  13585. Network.prototype._initializeMixinLoaders = function () {
  13586. for (var mixin in MixinLoader) {
  13587. if (MixinLoader.hasOwnProperty(mixin)) {
  13588. Network.prototype[mixin] = MixinLoader[mixin];
  13589. }
  13590. }
  13591. };
  13592. /**
  13593. * Load the XY positions of the nodes into the dataset.
  13594. */
  13595. Network.prototype.storePosition = function() {
  13596. var dataArray = [];
  13597. for (var nodeId in this.nodes) {
  13598. if (this.nodes.hasOwnProperty(nodeId)) {
  13599. var node = this.nodes[nodeId];
  13600. var allowedToMoveX = !this.nodes.xFixed;
  13601. var allowedToMoveY = !this.nodes.yFixed;
  13602. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  13603. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  13604. }
  13605. }
  13606. }
  13607. this.nodesData.update(dataArray);
  13608. };
  13609. /**
  13610. * Center a node in view.
  13611. *
  13612. * @param {Number} nodeId
  13613. * @param {Number} [zoomLevel]
  13614. */
  13615. Network.prototype.focusOnNode = function (nodeId, zoomLevel) {
  13616. if (this.nodes.hasOwnProperty(nodeId)) {
  13617. if (zoomLevel === undefined) {
  13618. zoomLevel = this._getScale();
  13619. }
  13620. var nodePosition= {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  13621. var requiredScale = zoomLevel;
  13622. this._setScale(requiredScale);
  13623. var canvasCenter = this.DOMtoCanvas({x:0.5 * this.frame.canvas.width,y:0.5 * this.frame.canvas.height});
  13624. var translation = this._getTranslation();
  13625. var distanceFromCenter = {x:canvasCenter.x - nodePosition.x,
  13626. y:canvasCenter.y - nodePosition.y};
  13627. this._setTranslation(translation.x + requiredScale * distanceFromCenter.x,
  13628. translation.y + requiredScale * distanceFromCenter.y);
  13629. this.redraw();
  13630. }
  13631. else {
  13632. console.log("This nodeId cannot be found.")
  13633. }
  13634. };
  13635. module.exports = Network;
  13636. /***/ },
  13637. /* 33 */
  13638. /***/ function(module, exports, __webpack_require__) {
  13639. var util = __webpack_require__(1);
  13640. var Node = __webpack_require__(36);
  13641. /**
  13642. * @class Edge
  13643. *
  13644. * A edge connects two nodes
  13645. * @param {Object} properties Object with properties. Must contain
  13646. * At least properties from and to.
  13647. * Available properties: from (number),
  13648. * to (number), label (string, color (string),
  13649. * width (number), style (string),
  13650. * length (number), title (string)
  13651. * @param {Network} network A Network object, used to find and edge to
  13652. * nodes.
  13653. * @param {Object} constants An object with default values for
  13654. * example for the color
  13655. */
  13656. function Edge (properties, network, networkConstants) {
  13657. if (!network) {
  13658. throw "No network provided";
  13659. }
  13660. var fields = ['edges','physics'];
  13661. var constants = util.selectiveBridgeObject(fields,networkConstants);
  13662. this.options = constants.edges;
  13663. this.physics = constants.physics;
  13664. this.options['smoothCurves'] = networkConstants['smoothCurves'];
  13665. this.network = network;
  13666. // initialize variables
  13667. this.id = undefined;
  13668. this.fromId = undefined;
  13669. this.toId = undefined;
  13670. this.title = undefined;
  13671. this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
  13672. this.value = undefined;
  13673. this.selected = false;
  13674. this.hover = false;
  13675. this.from = null; // a node
  13676. this.to = null; // a node
  13677. this.via = null; // a temp node
  13678. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  13679. // by storing the original information we can revert to the original connection when the cluser is opened.
  13680. this.originalFromId = [];
  13681. this.originalToId = [];
  13682. this.connected = false;
  13683. this.widthFixed = false;
  13684. this.lengthFixed = false;
  13685. this.setProperties(properties);
  13686. this.controlNodesEnabled = false;
  13687. this.controlNodes = {from:null, to:null, positions:{}};
  13688. this.connectedNode = null;
  13689. }
  13690. /**
  13691. * Set or overwrite properties for the edge
  13692. * @param {Object} properties an object with properties
  13693. * @param {Object} constants and object with default, global properties
  13694. */
  13695. Edge.prototype.setProperties = function(properties) {
  13696. if (!properties) {
  13697. return;
  13698. }
  13699. var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
  13700. 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash'
  13701. ];
  13702. util.selectiveDeepExtend(fields, this.options, properties);
  13703. if (properties.from !== undefined) {this.fromId = properties.from;}
  13704. if (properties.to !== undefined) {this.toId = properties.to;}
  13705. if (properties.id !== undefined) {this.id = properties.id;}
  13706. if (properties.label !== undefined) {this.label = properties.label;}
  13707. if (properties.title !== undefined) {this.title = properties.title;}
  13708. if (properties.value !== undefined) {this.value = properties.value;}
  13709. if (properties.length !== undefined) {this.physics.springLength = properties.length;}
  13710. // scale the arrow
  13711. if (properties.arrowScaleFactor !== undefined) {this.options.arrowScaleFactor = properties.arrowScaleFactor;}
  13712. if (properties.inheritColor !== undefined) {this.options.inheritColor = properties.inheritColor;}
  13713. if (properties.color !== undefined) {
  13714. this.options.inheritColor = false;
  13715. if (util.isString(properties.color)) {
  13716. this.options.color.color = properties.color;
  13717. this.options.color.highlight = properties.color;
  13718. }
  13719. else {
  13720. if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
  13721. if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
  13722. if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
  13723. }
  13724. }
  13725. // A node is connected when it has a from and to node.
  13726. this.connect();
  13727. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  13728. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  13729. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  13730. // set draw method based on style
  13731. switch (this.options.style) {
  13732. case 'line': this.draw = this._drawLine; break;
  13733. case 'arrow': this.draw = this._drawArrow; break;
  13734. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  13735. case 'dash-line': this.draw = this._drawDashLine; break;
  13736. default: this.draw = this._drawLine; break;
  13737. }
  13738. };
  13739. /**
  13740. * Connect an edge to its nodes
  13741. */
  13742. Edge.prototype.connect = function () {
  13743. this.disconnect();
  13744. this.from = this.network.nodes[this.fromId] || null;
  13745. this.to = this.network.nodes[this.toId] || null;
  13746. this.connected = (this.from && this.to);
  13747. if (this.connected) {
  13748. this.from.attachEdge(this);
  13749. this.to.attachEdge(this);
  13750. }
  13751. else {
  13752. if (this.from) {
  13753. this.from.detachEdge(this);
  13754. }
  13755. if (this.to) {
  13756. this.to.detachEdge(this);
  13757. }
  13758. }
  13759. };
  13760. /**
  13761. * Disconnect an edge from its nodes
  13762. */
  13763. Edge.prototype.disconnect = function () {
  13764. if (this.from) {
  13765. this.from.detachEdge(this);
  13766. this.from = null;
  13767. }
  13768. if (this.to) {
  13769. this.to.detachEdge(this);
  13770. this.to = null;
  13771. }
  13772. this.connected = false;
  13773. };
  13774. /**
  13775. * get the title of this edge.
  13776. * @return {string} title The title of the edge, or undefined when no title
  13777. * has been set.
  13778. */
  13779. Edge.prototype.getTitle = function() {
  13780. return typeof this.title === "function" ? this.title() : this.title;
  13781. };
  13782. /**
  13783. * Retrieve the value of the edge. Can be undefined
  13784. * @return {Number} value
  13785. */
  13786. Edge.prototype.getValue = function() {
  13787. return this.value;
  13788. };
  13789. /**
  13790. * Adjust the value range of the edge. The edge will adjust it's width
  13791. * based on its value.
  13792. * @param {Number} min
  13793. * @param {Number} max
  13794. */
  13795. Edge.prototype.setValueRange = function(min, max) {
  13796. if (!this.widthFixed && this.value !== undefined) {
  13797. var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
  13798. this.options.width= (this.value - min) * scale + this.options.widthMin;
  13799. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  13800. }
  13801. };
  13802. /**
  13803. * Redraw a edge
  13804. * Draw this edge in the given canvas
  13805. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  13806. * @param {CanvasRenderingContext2D} ctx
  13807. */
  13808. Edge.prototype.draw = function(ctx) {
  13809. throw "Method draw not initialized in edge";
  13810. };
  13811. /**
  13812. * Check if this object is overlapping with the provided object
  13813. * @param {Object} obj an object with parameters left, top
  13814. * @return {boolean} True if location is located on the edge
  13815. */
  13816. Edge.prototype.isOverlappingWith = function(obj) {
  13817. if (this.connected) {
  13818. var distMax = 10;
  13819. var xFrom = this.from.x;
  13820. var yFrom = this.from.y;
  13821. var xTo = this.to.x;
  13822. var yTo = this.to.y;
  13823. var xObj = obj.left;
  13824. var yObj = obj.top;
  13825. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  13826. return (dist < distMax);
  13827. }
  13828. else {
  13829. return false
  13830. }
  13831. };
  13832. Edge.prototype._getColor = function() {
  13833. var colorObj = this.options.color;
  13834. if (this.options.inheritColor == "to") {
  13835. colorObj = {
  13836. highlight: this.to.options.color.highlight.border,
  13837. hover: this.to.options.color.hover.border,
  13838. color: this.to.options.color.border
  13839. };
  13840. }
  13841. else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
  13842. colorObj = {
  13843. highlight: this.from.options.color.highlight.border,
  13844. hover: this.from.options.color.hover.border,
  13845. color: this.from.options.color.border
  13846. };
  13847. }
  13848. if (this.selected == true) {return colorObj.highlight;}
  13849. else if (this.hover == true) {return colorObj.hover;}
  13850. else {return colorObj.color;}
  13851. }
  13852. /**
  13853. * Redraw a edge as a line
  13854. * Draw this edge in the given canvas
  13855. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  13856. * @param {CanvasRenderingContext2D} ctx
  13857. * @private
  13858. */
  13859. Edge.prototype._drawLine = function(ctx) {
  13860. // set style
  13861. ctx.strokeStyle = this._getColor();
  13862. ctx.lineWidth = this._getLineWidth();
  13863. if (this.from != this.to) {
  13864. // draw line
  13865. var via = this._line(ctx);
  13866. // draw label
  13867. var point;
  13868. if (this.label) {
  13869. if (this.options.smoothCurves.enabled == true && via != null) {
  13870. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  13871. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  13872. point = {x:midpointX, y:midpointY};
  13873. }
  13874. else {
  13875. point = this._pointOnLine(0.5);
  13876. }
  13877. this._label(ctx, this.label, point.x, point.y);
  13878. }
  13879. }
  13880. else {
  13881. var x, y;
  13882. var radius = this.physics.springLength / 4;
  13883. var node = this.from;
  13884. if (!node.width) {
  13885. node.resize(ctx);
  13886. }
  13887. if (node.width > node.height) {
  13888. x = node.x + node.width / 2;
  13889. y = node.y - radius;
  13890. }
  13891. else {
  13892. x = node.x + radius;
  13893. y = node.y - node.height / 2;
  13894. }
  13895. this._circle(ctx, x, y, radius);
  13896. point = this._pointOnCircle(x, y, radius, 0.5);
  13897. this._label(ctx, this.label, point.x, point.y);
  13898. }
  13899. };
  13900. /**
  13901. * Get the line width of the edge. Depends on width and whether one of the
  13902. * connected nodes is selected.
  13903. * @return {Number} width
  13904. * @private
  13905. */
  13906. Edge.prototype._getLineWidth = function() {
  13907. if (this.selected == true) {
  13908. return Math.min(this.widthSelected, this.options.widthMax)*this.networkScaleInv;
  13909. }
  13910. else {
  13911. if (this.hover == true) {
  13912. return Math.min(this.options.hoverWidth, this.options.widthMax)*this.networkScaleInv;
  13913. }
  13914. else {
  13915. return this.options.width*this.networkScaleInv;
  13916. }
  13917. }
  13918. };
  13919. Edge.prototype._getViaCoordinates = function () {
  13920. var xVia = null;
  13921. var yVia = null;
  13922. var factor = this.options.smoothCurves.roundness;
  13923. var type = this.options.smoothCurves.type;
  13924. var dx = Math.abs(this.from.x - this.to.x);
  13925. var dy = Math.abs(this.from.y - this.to.y);
  13926. if (type == 'discrete' || type == 'diagonalCross') {
  13927. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  13928. if (this.from.y > this.to.y) {
  13929. if (this.from.x < this.to.x) {
  13930. xVia = this.from.x + factor * dy;
  13931. yVia = this.from.y - factor * dy;
  13932. }
  13933. else if (this.from.x > this.to.x) {
  13934. xVia = this.from.x - factor * dy;
  13935. yVia = this.from.y - factor * dy;
  13936. }
  13937. }
  13938. else if (this.from.y < this.to.y) {
  13939. if (this.from.x < this.to.x) {
  13940. xVia = this.from.x + factor * dy;
  13941. yVia = this.from.y + factor * dy;
  13942. }
  13943. else if (this.from.x > this.to.x) {
  13944. xVia = this.from.x - factor * dy;
  13945. yVia = this.from.y + factor * dy;
  13946. }
  13947. }
  13948. if (type == "discrete") {
  13949. xVia = dx < factor * dy ? this.from.x : xVia;
  13950. }
  13951. }
  13952. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  13953. if (this.from.y > this.to.y) {
  13954. if (this.from.x < this.to.x) {
  13955. xVia = this.from.x + factor * dx;
  13956. yVia = this.from.y - factor * dx;
  13957. }
  13958. else if (this.from.x > this.to.x) {
  13959. xVia = this.from.x - factor * dx;
  13960. yVia = this.from.y - factor * dx;
  13961. }
  13962. }
  13963. else if (this.from.y < this.to.y) {
  13964. if (this.from.x < this.to.x) {
  13965. xVia = this.from.x + factor * dx;
  13966. yVia = this.from.y + factor * dx;
  13967. }
  13968. else if (this.from.x > this.to.x) {
  13969. xVia = this.from.x - factor * dx;
  13970. yVia = this.from.y + factor * dx;
  13971. }
  13972. }
  13973. if (type == "discrete") {
  13974. yVia = dy < factor * dx ? this.from.y : yVia;
  13975. }
  13976. }
  13977. }
  13978. else if (type == "straightCross") {
  13979. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
  13980. xVia = this.from.x;
  13981. if (this.from.y < this.to.y) {
  13982. yVia = this.to.y - (1-factor) * dy;
  13983. }
  13984. else {
  13985. yVia = this.to.y + (1-factor) * dy;
  13986. }
  13987. }
  13988. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
  13989. if (this.from.x < this.to.x) {
  13990. xVia = this.to.x - (1-factor) * dx;
  13991. }
  13992. else {
  13993. xVia = this.to.x + (1-factor) * dx;
  13994. }
  13995. yVia = this.from.y;
  13996. }
  13997. }
  13998. else if (type == 'horizontal') {
  13999. if (this.from.x < this.to.x) {
  14000. xVia = this.to.x - (1-factor) * dx;
  14001. }
  14002. else {
  14003. xVia = this.to.x + (1-factor) * dx;
  14004. }
  14005. yVia = this.from.y;
  14006. }
  14007. else if (type == 'vertical') {
  14008. xVia = this.from.x;
  14009. if (this.from.y < this.to.y) {
  14010. yVia = this.to.y - (1-factor) * dy;
  14011. }
  14012. else {
  14013. yVia = this.to.y + (1-factor) * dy;
  14014. }
  14015. }
  14016. else { // continuous
  14017. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  14018. if (this.from.y > this.to.y) {
  14019. if (this.from.x < this.to.x) {
  14020. // console.log(1)
  14021. xVia = this.from.x + factor * dy;
  14022. yVia = this.from.y - factor * dy;
  14023. xVia = this.to.x < xVia ? this.to.x : xVia;
  14024. }
  14025. else if (this.from.x > this.to.x) {
  14026. // console.log(2)
  14027. xVia = this.from.x - factor * dy;
  14028. yVia = this.from.y - factor * dy;
  14029. xVia = this.to.x > xVia ? this.to.x :xVia;
  14030. }
  14031. }
  14032. else if (this.from.y < this.to.y) {
  14033. if (this.from.x < this.to.x) {
  14034. // console.log(3)
  14035. xVia = this.from.x + factor * dy;
  14036. yVia = this.from.y + factor * dy;
  14037. xVia = this.to.x < xVia ? this.to.x : xVia;
  14038. }
  14039. else if (this.from.x > this.to.x) {
  14040. // console.log(4, this.from.x, this.to.x)
  14041. xVia = this.from.x - factor * dy;
  14042. yVia = this.from.y + factor * dy;
  14043. xVia = this.to.x > xVia ? this.to.x : xVia;
  14044. }
  14045. }
  14046. }
  14047. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  14048. if (this.from.y > this.to.y) {
  14049. if (this.from.x < this.to.x) {
  14050. // console.log(5)
  14051. xVia = this.from.x + factor * dx;
  14052. yVia = this.from.y - factor * dx;
  14053. yVia = this.to.y > yVia ? this.to.y : yVia;
  14054. }
  14055. else if (this.from.x > this.to.x) {
  14056. // console.log(6)
  14057. xVia = this.from.x - factor * dx;
  14058. yVia = this.from.y - factor * dx;
  14059. yVia = this.to.y > yVia ? this.to.y : yVia;
  14060. }
  14061. }
  14062. else if (this.from.y < this.to.y) {
  14063. if (this.from.x < this.to.x) {
  14064. // console.log(7)
  14065. xVia = this.from.x + factor * dx;
  14066. yVia = this.from.y + factor * dx;
  14067. yVia = this.to.y < yVia ? this.to.y : yVia;
  14068. }
  14069. else if (this.from.x > this.to.x) {
  14070. // console.log(8)
  14071. xVia = this.from.x - factor * dx;
  14072. yVia = this.from.y + factor * dx;
  14073. yVia = this.to.y < yVia ? this.to.y : yVia;
  14074. }
  14075. }
  14076. }
  14077. }
  14078. return {x:xVia, y:yVia};
  14079. }
  14080. /**
  14081. * Draw a line between two nodes
  14082. * @param {CanvasRenderingContext2D} ctx
  14083. * @private
  14084. */
  14085. Edge.prototype._line = function (ctx) {
  14086. // draw a straight line
  14087. ctx.beginPath();
  14088. ctx.moveTo(this.from.x, this.from.y);
  14089. if (this.options.smoothCurves.enabled == true) {
  14090. if (this.options.smoothCurves.dynamic == false) {
  14091. var via = this._getViaCoordinates();
  14092. if (via.x == null) {
  14093. ctx.lineTo(this.to.x, this.to.y);
  14094. ctx.stroke();
  14095. return null;
  14096. }
  14097. else {
  14098. // this.via.x = via.x;
  14099. // this.via.y = via.y;
  14100. ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
  14101. ctx.stroke();
  14102. return via;
  14103. }
  14104. }
  14105. else {
  14106. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  14107. ctx.stroke();
  14108. return this.via;
  14109. }
  14110. }
  14111. else {
  14112. ctx.lineTo(this.to.x, this.to.y);
  14113. ctx.stroke();
  14114. return null;
  14115. }
  14116. };
  14117. /**
  14118. * Draw a line from a node to itself, a circle
  14119. * @param {CanvasRenderingContext2D} ctx
  14120. * @param {Number} x
  14121. * @param {Number} y
  14122. * @param {Number} radius
  14123. * @private
  14124. */
  14125. Edge.prototype._circle = function (ctx, x, y, radius) {
  14126. // draw a circle
  14127. ctx.beginPath();
  14128. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  14129. ctx.stroke();
  14130. };
  14131. /**
  14132. * Draw label with white background and with the middle at (x, y)
  14133. * @param {CanvasRenderingContext2D} ctx
  14134. * @param {String} text
  14135. * @param {Number} x
  14136. * @param {Number} y
  14137. * @private
  14138. */
  14139. Edge.prototype._label = function (ctx, text, x, y) {
  14140. if (text) {
  14141. // TODO: cache the calculated size
  14142. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  14143. this.options.fontSize + "px " + this.options.fontFace;
  14144. ctx.fillStyle = this.options.fontFill;
  14145. var width = ctx.measureText(text).width;
  14146. var height = this.options.fontSize;
  14147. var left = x - width / 2;
  14148. var top = y - height / 2;
  14149. ctx.fillRect(left, top, width, height);
  14150. // draw text
  14151. ctx.fillStyle = this.options.fontColor || "black";
  14152. ctx.textAlign = "left";
  14153. ctx.textBaseline = "top";
  14154. ctx.fillText(text, left, top);
  14155. }
  14156. };
  14157. /**
  14158. * Redraw a edge as a dashed line
  14159. * Draw this edge in the given canvas
  14160. * @author David Jordan
  14161. * @date 2012-08-08
  14162. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  14163. * @param {CanvasRenderingContext2D} ctx
  14164. * @private
  14165. */
  14166. Edge.prototype._drawDashLine = function(ctx) {
  14167. // set style
  14168. if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight;}
  14169. else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover;}
  14170. else {ctx.strokeStyle = this.options.color.color;}
  14171. ctx.lineWidth = this._getLineWidth();
  14172. var via = null;
  14173. // only firefox and chrome support this method, else we use the legacy one.
  14174. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  14175. // configure the dash pattern
  14176. var pattern = [0];
  14177. if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
  14178. pattern = [this.options.dash.length,this.options.dash.gap];
  14179. }
  14180. else {
  14181. pattern = [5,5];
  14182. }
  14183. // set dash settings for chrome or firefox
  14184. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  14185. ctx.setLineDash(pattern);
  14186. ctx.lineDashOffset = 0;
  14187. } else { //Firefox
  14188. ctx.mozDash = pattern;
  14189. ctx.mozDashOffset = 0;
  14190. }
  14191. // draw the line
  14192. via = this._line(ctx);
  14193. // restore the dash settings.
  14194. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  14195. ctx.setLineDash([0]);
  14196. ctx.lineDashOffset = 0;
  14197. } else { //Firefox
  14198. ctx.mozDash = [0];
  14199. ctx.mozDashOffset = 0;
  14200. }
  14201. }
  14202. else { // unsupporting smooth lines
  14203. // draw dashed line
  14204. ctx.beginPath();
  14205. ctx.lineCap = 'round';
  14206. if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  14207. {
  14208. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  14209. [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
  14210. }
  14211. 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
  14212. {
  14213. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  14214. [this.options.dash.length,this.options.dash.gap]);
  14215. }
  14216. else //If all else fails draw a line
  14217. {
  14218. ctx.moveTo(this.from.x, this.from.y);
  14219. ctx.lineTo(this.to.x, this.to.y);
  14220. }
  14221. ctx.stroke();
  14222. }
  14223. // draw label
  14224. if (this.label) {
  14225. var point;
  14226. if (this.options.smoothCurves.enabled == true && via != null) {
  14227. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  14228. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  14229. point = {x:midpointX, y:midpointY};
  14230. }
  14231. else {
  14232. point = this._pointOnLine(0.5);
  14233. }
  14234. this._label(ctx, this.label, point.x, point.y);
  14235. }
  14236. };
  14237. /**
  14238. * Get a point on a line
  14239. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  14240. * @return {Object} point
  14241. * @private
  14242. */
  14243. Edge.prototype._pointOnLine = function (percentage) {
  14244. return {
  14245. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  14246. y: (1 - percentage) * this.from.y + percentage * this.to.y
  14247. }
  14248. };
  14249. /**
  14250. * Get a point on a circle
  14251. * @param {Number} x
  14252. * @param {Number} y
  14253. * @param {Number} radius
  14254. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  14255. * @return {Object} point
  14256. * @private
  14257. */
  14258. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  14259. var angle = (percentage - 3/8) * 2 * Math.PI;
  14260. return {
  14261. x: x + radius * Math.cos(angle),
  14262. y: y - radius * Math.sin(angle)
  14263. }
  14264. };
  14265. /**
  14266. * Redraw a edge as a line with an arrow halfway the line
  14267. * Draw this edge in the given canvas
  14268. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  14269. * @param {CanvasRenderingContext2D} ctx
  14270. * @private
  14271. */
  14272. Edge.prototype._drawArrowCenter = function(ctx) {
  14273. var point;
  14274. // set style
  14275. if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
  14276. else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
  14277. else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
  14278. ctx.lineWidth = this._getLineWidth();
  14279. if (this.from != this.to) {
  14280. // draw line
  14281. var via = this._line(ctx);
  14282. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  14283. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  14284. // draw an arrow halfway the line
  14285. if (this.options.smoothCurves.enabled == true && via != null) {
  14286. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  14287. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  14288. point = {x:midpointX, y:midpointY};
  14289. }
  14290. else {
  14291. point = this._pointOnLine(0.5);
  14292. }
  14293. ctx.arrow(point.x, point.y, angle, length);
  14294. ctx.fill();
  14295. ctx.stroke();
  14296. // draw label
  14297. if (this.label) {
  14298. this._label(ctx, this.label, point.x, point.y);
  14299. }
  14300. }
  14301. else {
  14302. // draw circle
  14303. var x, y;
  14304. var radius = 0.25 * Math.max(100,this.physics.springLength);
  14305. var node = this.from;
  14306. if (!node.width) {
  14307. node.resize(ctx);
  14308. }
  14309. if (node.width > node.height) {
  14310. x = node.x + node.width * 0.5;
  14311. y = node.y - radius;
  14312. }
  14313. else {
  14314. x = node.x + radius;
  14315. y = node.y - node.height * 0.5;
  14316. }
  14317. this._circle(ctx, x, y, radius);
  14318. // draw all arrows
  14319. var angle = 0.2 * Math.PI;
  14320. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  14321. point = this._pointOnCircle(x, y, radius, 0.5);
  14322. ctx.arrow(point.x, point.y, angle, length);
  14323. ctx.fill();
  14324. ctx.stroke();
  14325. // draw label
  14326. if (this.label) {
  14327. point = this._pointOnCircle(x, y, radius, 0.5);
  14328. this._label(ctx, this.label, point.x, point.y);
  14329. }
  14330. }
  14331. };
  14332. /**
  14333. * Redraw a edge as a line with an arrow
  14334. * Draw this edge in the given canvas
  14335. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  14336. * @param {CanvasRenderingContext2D} ctx
  14337. * @private
  14338. */
  14339. Edge.prototype._drawArrow = function(ctx) {
  14340. // set style
  14341. if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
  14342. else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
  14343. else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
  14344. ctx.lineWidth = this._getLineWidth();
  14345. var angle, length;
  14346. //draw a line
  14347. if (this.from != this.to) {
  14348. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  14349. var dx = (this.to.x - this.from.x);
  14350. var dy = (this.to.y - this.from.y);
  14351. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  14352. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  14353. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  14354. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  14355. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  14356. var via;
  14357. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
  14358. via = this.via;
  14359. }
  14360. else if (this.options.smoothCurves.enabled == true) {
  14361. via = this._getViaCoordinates();
  14362. }
  14363. if (this.options.smoothCurves.enabled == true && via.x != null) {
  14364. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  14365. dx = (this.to.x - via.x);
  14366. dy = (this.to.y - via.y);
  14367. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  14368. }
  14369. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  14370. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  14371. var xTo,yTo;
  14372. if (this.options.smoothCurves.enabled == true && via.x != null) {
  14373. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  14374. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  14375. }
  14376. else {
  14377. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  14378. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  14379. }
  14380. ctx.beginPath();
  14381. ctx.moveTo(xFrom,yFrom);
  14382. if (this.options.smoothCurves.enabled == true && via.x != null) {
  14383. ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
  14384. }
  14385. else {
  14386. ctx.lineTo(xTo, yTo);
  14387. }
  14388. ctx.stroke();
  14389. // draw arrow at the end of the line
  14390. length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  14391. ctx.arrow(xTo, yTo, angle, length);
  14392. ctx.fill();
  14393. ctx.stroke();
  14394. // draw label
  14395. if (this.label) {
  14396. var point;
  14397. if (this.options.smoothCurves.enabled == true && via != null) {
  14398. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  14399. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  14400. point = {x:midpointX, y:midpointY};
  14401. }
  14402. else {
  14403. point = this._pointOnLine(0.5);
  14404. }
  14405. this._label(ctx, this.label, point.x, point.y);
  14406. }
  14407. }
  14408. else {
  14409. // draw circle
  14410. var node = this.from;
  14411. var x, y, arrow;
  14412. var radius = 0.25 * Math.max(100,this.physics.springLength);
  14413. if (!node.width) {
  14414. node.resize(ctx);
  14415. }
  14416. if (node.width > node.height) {
  14417. x = node.x + node.width * 0.5;
  14418. y = node.y - radius;
  14419. arrow = {
  14420. x: x,
  14421. y: node.y,
  14422. angle: 0.9 * Math.PI
  14423. };
  14424. }
  14425. else {
  14426. x = node.x + radius;
  14427. y = node.y - node.height * 0.5;
  14428. arrow = {
  14429. x: node.x,
  14430. y: y,
  14431. angle: 0.6 * Math.PI
  14432. };
  14433. }
  14434. ctx.beginPath();
  14435. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  14436. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  14437. ctx.stroke();
  14438. // draw all arrows
  14439. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  14440. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  14441. ctx.fill();
  14442. ctx.stroke();
  14443. // draw label
  14444. if (this.label) {
  14445. point = this._pointOnCircle(x, y, radius, 0.5);
  14446. this._label(ctx, this.label, point.x, point.y);
  14447. }
  14448. }
  14449. };
  14450. /**
  14451. * Calculate the distance between a point (x3,y3) and a line segment from
  14452. * (x1,y1) to (x2,y2).
  14453. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  14454. * @param {number} x1
  14455. * @param {number} y1
  14456. * @param {number} x2
  14457. * @param {number} y2
  14458. * @param {number} x3
  14459. * @param {number} y3
  14460. * @private
  14461. */
  14462. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  14463. if (this.from != this.to) {
  14464. if (this.options.smoothCurves.enabled == true) {
  14465. var xVia, yVia;
  14466. if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
  14467. xVia = this.via.x;
  14468. yVia = this.via.y;
  14469. }
  14470. else {
  14471. var via = this._getViaCoordinates();
  14472. xVia = via.x;
  14473. yVia = via.y;
  14474. }
  14475. var minDistance = 1e9;
  14476. var distance;
  14477. var i,t,x,y, lastX, lastY;
  14478. for (i = 0; i < 10; i++) {
  14479. t = 0.1*i;
  14480. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
  14481. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
  14482. if (i > 0) {
  14483. distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
  14484. minDistance = distance < minDistance ? distance : minDistance;
  14485. }
  14486. lastX = x; lastY = y;
  14487. }
  14488. return minDistance
  14489. }
  14490. else {
  14491. return this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
  14492. }
  14493. }
  14494. else {
  14495. var x, y, dx, dy;
  14496. var radius = this.physics.springLength / 4;
  14497. var node = this.from;
  14498. if (!node.width) {
  14499. node.resize(ctx);
  14500. }
  14501. if (node.width > node.height) {
  14502. x = node.x + node.width / 2;
  14503. y = node.y - radius;
  14504. }
  14505. else {
  14506. x = node.x + radius;
  14507. y = node.y - node.height / 2;
  14508. }
  14509. dx = x - x3;
  14510. dy = y - y3;
  14511. return Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
  14512. }
  14513. };
  14514. Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
  14515. var px = x2-x1,
  14516. py = y2-y1,
  14517. something = px*px + py*py,
  14518. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  14519. if (u > 1) {
  14520. u = 1;
  14521. }
  14522. else if (u < 0) {
  14523. u = 0;
  14524. }
  14525. var x = x1 + u * px,
  14526. y = y1 + u * py,
  14527. dx = x - x3,
  14528. dy = y - y3;
  14529. //# Note: If the actual distance does not matter,
  14530. //# if you only want to compare what this function
  14531. //# returns to other results of this function, you
  14532. //# can just return the squared distance instead
  14533. //# (i.e. remove the sqrt) to gain a little performance
  14534. return Math.sqrt(dx*dx + dy*dy);
  14535. }
  14536. /**
  14537. * This allows the zoom level of the network to influence the rendering
  14538. *
  14539. * @param scale
  14540. */
  14541. Edge.prototype.setScale = function(scale) {
  14542. this.networkScaleInv = 1.0/scale;
  14543. };
  14544. Edge.prototype.select = function() {
  14545. this.selected = true;
  14546. };
  14547. Edge.prototype.unselect = function() {
  14548. this.selected = false;
  14549. };
  14550. Edge.prototype.positionBezierNode = function() {
  14551. if (this.via !== null && this.from !== null && this.to !== null) {
  14552. this.via.x = 0.5 * (this.from.x + this.to.x);
  14553. this.via.y = 0.5 * (this.from.y + this.to.y);
  14554. }
  14555. };
  14556. /**
  14557. * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true.
  14558. * @param ctx
  14559. */
  14560. Edge.prototype._drawControlNodes = function(ctx) {
  14561. if (this.controlNodesEnabled == true) {
  14562. if (this.controlNodes.from === null && this.controlNodes.to === null) {
  14563. var nodeIdFrom = "edgeIdFrom:".concat(this.id);
  14564. var nodeIdTo = "edgeIdTo:".concat(this.id);
  14565. var constants = {
  14566. nodes:{group:'', radius:8},
  14567. physics:{damping:0},
  14568. clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
  14569. };
  14570. this.controlNodes.from = new Node(
  14571. {id:nodeIdFrom,
  14572. shape:'dot',
  14573. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  14574. },{},{},constants);
  14575. this.controlNodes.to = new Node(
  14576. {id:nodeIdTo,
  14577. shape:'dot',
  14578. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  14579. },{},{},constants);
  14580. }
  14581. if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
  14582. this.controlNodes.positions = this.getControlNodePositions(ctx);
  14583. this.controlNodes.from.x = this.controlNodes.positions.from.x;
  14584. this.controlNodes.from.y = this.controlNodes.positions.from.y;
  14585. this.controlNodes.to.x = this.controlNodes.positions.to.x;
  14586. this.controlNodes.to.y = this.controlNodes.positions.to.y;
  14587. }
  14588. this.controlNodes.from.draw(ctx);
  14589. this.controlNodes.to.draw(ctx);
  14590. }
  14591. else {
  14592. this.controlNodes = {from:null, to:null, positions:{}};
  14593. }
  14594. };
  14595. /**
  14596. * Enable control nodes.
  14597. * @private
  14598. */
  14599. Edge.prototype._enableControlNodes = function() {
  14600. this.controlNodesEnabled = true;
  14601. };
  14602. /**
  14603. * disable control nodes
  14604. * @private
  14605. */
  14606. Edge.prototype._disableControlNodes = function() {
  14607. this.controlNodesEnabled = false;
  14608. };
  14609. /**
  14610. * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
  14611. * @param x
  14612. * @param y
  14613. * @returns {null}
  14614. * @private
  14615. */
  14616. Edge.prototype._getSelectedControlNode = function(x,y) {
  14617. var positions = this.controlNodes.positions;
  14618. var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
  14619. var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
  14620. if (fromDistance < 15) {
  14621. this.connectedNode = this.from;
  14622. this.from = this.controlNodes.from;
  14623. return this.controlNodes.from;
  14624. }
  14625. else if (toDistance < 15) {
  14626. this.connectedNode = this.to;
  14627. this.to = this.controlNodes.to;
  14628. return this.controlNodes.to;
  14629. }
  14630. else {
  14631. return null;
  14632. }
  14633. };
  14634. /**
  14635. * this resets the control nodes to their original position.
  14636. * @private
  14637. */
  14638. Edge.prototype._restoreControlNodes = function() {
  14639. if (this.controlNodes.from.selected == true) {
  14640. this.from = this.connectedNode;
  14641. this.connectedNode = null;
  14642. this.controlNodes.from.unselect();
  14643. }
  14644. if (this.controlNodes.to.selected == true) {
  14645. this.to = this.connectedNode;
  14646. this.connectedNode = null;
  14647. this.controlNodes.to.unselect();
  14648. }
  14649. };
  14650. /**
  14651. * this calculates the position of the control nodes on the edges of the parent nodes.
  14652. *
  14653. * @param ctx
  14654. * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
  14655. */
  14656. Edge.prototype.getControlNodePositions = function(ctx) {
  14657. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  14658. var dx = (this.to.x - this.from.x);
  14659. var dy = (this.to.y - this.from.y);
  14660. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  14661. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  14662. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  14663. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  14664. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  14665. var via;
  14666. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
  14667. via = this.via;
  14668. }
  14669. else if (this.options.smoothCurves.enabled == true) {
  14670. via = this._getViaCoordinates();
  14671. }
  14672. if (this.options.smoothCurves.enabled == true && via.x != null) {
  14673. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  14674. dx = (this.to.x - via.x);
  14675. dy = (this.to.y - via.y);
  14676. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  14677. }
  14678. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  14679. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  14680. var xTo,yTo;
  14681. if (this.options.smoothCurves.enabled == true && via.x != null) {
  14682. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  14683. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  14684. }
  14685. else {
  14686. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  14687. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  14688. }
  14689. return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
  14690. };
  14691. module.exports = Edge;
  14692. /***/ },
  14693. /* 34 */
  14694. /***/ function(module, exports, __webpack_require__) {
  14695. var util = __webpack_require__(1);
  14696. /**
  14697. * @class Groups
  14698. * This class can store groups and properties specific for groups.
  14699. */
  14700. function Groups() {
  14701. this.clear();
  14702. this.defaultIndex = 0;
  14703. }
  14704. /**
  14705. * default constants for group colors
  14706. */
  14707. Groups.DEFAULT = [
  14708. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  14709. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  14710. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  14711. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green
  14712. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  14713. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  14714. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange
  14715. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  14716. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  14717. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  14718. ];
  14719. /**
  14720. * Clear all groups
  14721. */
  14722. Groups.prototype.clear = function () {
  14723. this.groups = {};
  14724. this.groups.length = function()
  14725. {
  14726. var i = 0;
  14727. for ( var p in this ) {
  14728. if (this.hasOwnProperty(p)) {
  14729. i++;
  14730. }
  14731. }
  14732. return i;
  14733. }
  14734. };
  14735. /**
  14736. * get group properties of a groupname. If groupname is not found, a new group
  14737. * is added.
  14738. * @param {*} groupname Can be a number, string, Date, etc.
  14739. * @return {Object} group The created group, containing all group properties
  14740. */
  14741. Groups.prototype.get = function (groupname) {
  14742. var group = this.groups[groupname];
  14743. if (group == undefined) {
  14744. // create new group
  14745. var index = this.defaultIndex % Groups.DEFAULT.length;
  14746. this.defaultIndex++;
  14747. group = {};
  14748. group.color = Groups.DEFAULT[index];
  14749. this.groups[groupname] = group;
  14750. }
  14751. return group;
  14752. };
  14753. /**
  14754. * Add a custom group style
  14755. * @param {String} groupname
  14756. * @param {Object} style An object containing borderColor,
  14757. * backgroundColor, etc.
  14758. * @return {Object} group The created group object
  14759. */
  14760. Groups.prototype.add = function (groupname, style) {
  14761. this.groups[groupname] = style;
  14762. if (style.color) {
  14763. style.color = util.parseColor(style.color);
  14764. }
  14765. return style;
  14766. };
  14767. module.exports = Groups;
  14768. /***/ },
  14769. /* 35 */
  14770. /***/ function(module, exports, __webpack_require__) {
  14771. /**
  14772. * @class Images
  14773. * This class loads images and keeps them stored.
  14774. */
  14775. function Images() {
  14776. this.images = {};
  14777. this.callback = undefined;
  14778. }
  14779. /**
  14780. * Set an onload callback function. This will be called each time an image
  14781. * is loaded
  14782. * @param {function} callback
  14783. */
  14784. Images.prototype.setOnloadCallback = function(callback) {
  14785. this.callback = callback;
  14786. };
  14787. /**
  14788. *
  14789. * @param {string} url Url of the image
  14790. * @return {Image} img The image object
  14791. */
  14792. Images.prototype.load = function(url) {
  14793. var img = this.images[url];
  14794. if (img == undefined) {
  14795. // create the image
  14796. var images = this;
  14797. img = new Image();
  14798. this.images[url] = img;
  14799. img.onload = function() {
  14800. if (images.callback) {
  14801. images.callback(this);
  14802. }
  14803. };
  14804. img.src = url;
  14805. }
  14806. return img;
  14807. };
  14808. module.exports = Images;
  14809. /***/ },
  14810. /* 36 */
  14811. /***/ function(module, exports, __webpack_require__) {
  14812. var util = __webpack_require__(1);
  14813. /**
  14814. * @class Node
  14815. * A node. A node can be connected to other nodes via one or multiple edges.
  14816. * @param {object} properties An object containing properties for the node. All
  14817. * properties are optional, except for the id.
  14818. * {number} id Id of the node. Required
  14819. * {string} label Text label for the node
  14820. * {number} x Horizontal position of the node
  14821. * {number} y Vertical position of the node
  14822. * {string} shape Node shape, available:
  14823. * "database", "circle", "ellipse",
  14824. * "box", "image", "text", "dot",
  14825. * "star", "triangle", "triangleDown",
  14826. * "square"
  14827. * {string} image An image url
  14828. * {string} title An title text, can be HTML
  14829. * {anytype} group A group name or number
  14830. * @param {Network.Images} imagelist A list with images. Only needed
  14831. * when the node has an image
  14832. * @param {Network.Groups} grouplist A list with groups. Needed for
  14833. * retrieving group properties
  14834. * @param {Object} constants An object with default values for
  14835. * example for the color
  14836. *
  14837. */
  14838. function Node(properties, imagelist, grouplist, networkConstants) {
  14839. var constants = util.selectiveBridgeObject(['nodes'],networkConstants);
  14840. this.options = constants.nodes;
  14841. this.selected = false;
  14842. this.hover = false;
  14843. this.edges = []; // all edges connected to this node
  14844. this.dynamicEdges = [];
  14845. this.reroutedEdges = {};
  14846. this.fontDrawThreshold = 3;
  14847. // set defaults for the properties
  14848. this.id = undefined;
  14849. this.x = null;
  14850. this.y = null;
  14851. this.xFixed = false;
  14852. this.yFixed = false;
  14853. this.horizontalAlignLeft = true; // these are for the navigation controls
  14854. this.verticalAlignTop = true; // these are for the navigation controls
  14855. this.baseRadiusValue = networkConstants.nodes.radius;
  14856. this.radiusFixed = false;
  14857. this.level = -1;
  14858. this.preassignedLevel = false;
  14859. this.imagelist = imagelist;
  14860. this.grouplist = grouplist;
  14861. // physics properties
  14862. this.fx = 0.0; // external force x
  14863. this.fy = 0.0; // external force y
  14864. this.vx = 0.0; // velocity x
  14865. this.vy = 0.0; // velocity y
  14866. this.damping = networkConstants.physics.damping; // written every time gravity is calculated
  14867. this.fixedData = {x:null,y:null};
  14868. this.setProperties(properties, constants);
  14869. // creating the variables for clustering
  14870. this.resetCluster();
  14871. this.dynamicEdgesLength = 0;
  14872. this.clusterSession = 0;
  14873. this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width;
  14874. this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height;
  14875. this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius;
  14876. this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements;
  14877. this.growthIndicator = 0;
  14878. // variables to tell the node about the network.
  14879. this.networkScaleInv = 1;
  14880. this.networkScale = 1;
  14881. this.canvasTopLeft = {"x": -300, "y": -300};
  14882. this.canvasBottomRight = {"x": 300, "y": 300};
  14883. this.parentEdgeId = null;
  14884. }
  14885. /**
  14886. * (re)setting the clustering variables and objects
  14887. */
  14888. Node.prototype.resetCluster = function() {
  14889. // clustering variables
  14890. this.formationScale = undefined; // this is used to determine when to open the cluster
  14891. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  14892. this.containedNodes = {};
  14893. this.containedEdges = {};
  14894. this.clusterSessions = [];
  14895. };
  14896. /**
  14897. * Attach a edge to the node
  14898. * @param {Edge} edge
  14899. */
  14900. Node.prototype.attachEdge = function(edge) {
  14901. if (this.edges.indexOf(edge) == -1) {
  14902. this.edges.push(edge);
  14903. }
  14904. if (this.dynamicEdges.indexOf(edge) == -1) {
  14905. this.dynamicEdges.push(edge);
  14906. }
  14907. this.dynamicEdgesLength = this.dynamicEdges.length;
  14908. };
  14909. /**
  14910. * Detach a edge from the node
  14911. * @param {Edge} edge
  14912. */
  14913. Node.prototype.detachEdge = function(edge) {
  14914. var index = this.edges.indexOf(edge);
  14915. if (index != -1) {
  14916. this.edges.splice(index, 1);
  14917. this.dynamicEdges.splice(index, 1);
  14918. }
  14919. this.dynamicEdgesLength = this.dynamicEdges.length;
  14920. };
  14921. /**
  14922. * Set or overwrite properties for the node
  14923. * @param {Object} properties an object with properties
  14924. * @param {Object} constants and object with default, global properties
  14925. */
  14926. Node.prototype.setProperties = function(properties, constants) {
  14927. if (!properties) {
  14928. return;
  14929. }
  14930. var fields = ['borderWidth','borderWidthSelected','shape','image','radius','fontColor',
  14931. 'fontSize','fontFace','group','mass'
  14932. ];
  14933. util.selectiveDeepExtend(fields, this.options, properties);
  14934. this.originalLabel = undefined;
  14935. // basic properties
  14936. if (properties.id !== undefined) {this.id = properties.id;}
  14937. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  14938. if (properties.title !== undefined) {this.title = properties.title;}
  14939. if (properties.x !== undefined) {this.x = properties.x;}
  14940. if (properties.y !== undefined) {this.y = properties.y;}
  14941. if (properties.value !== undefined) {this.value = properties.value;}
  14942. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  14943. // navigation controls properties
  14944. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  14945. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  14946. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  14947. if (this.id === undefined) {
  14948. throw "Node must have an id";
  14949. }
  14950. // console.log(this.options);
  14951. // copy group properties
  14952. if (this.options.group !== undefined && this.options.group != "") {
  14953. var groupObj = this.grouplist.get(this.options.group);
  14954. for (var prop in groupObj) {
  14955. if (groupObj.hasOwnProperty(prop)) {
  14956. this.options[prop] = groupObj[prop];
  14957. }
  14958. }
  14959. }
  14960. // individual shape properties
  14961. if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;}
  14962. if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);}
  14963. if (this.options.image!== undefined && this.options.image!= "") {
  14964. if (this.imagelist) {
  14965. this.imageObj = this.imagelist.load(this.options.image);
  14966. }
  14967. else {
  14968. throw "No imagelist provided";
  14969. }
  14970. }
  14971. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  14972. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  14973. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  14974. if (this.options.shape == 'image') {
  14975. this.options.radiusMin = constants.nodes.widthMin;
  14976. this.options.radiusMax = constants.nodes.widthMax;
  14977. }
  14978. // choose draw method depending on the shape
  14979. switch (this.options.shape) {
  14980. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  14981. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  14982. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  14983. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  14984. // TODO: add diamond shape
  14985. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  14986. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  14987. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  14988. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  14989. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  14990. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  14991. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  14992. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  14993. }
  14994. // reset the size of the node, this can be changed
  14995. this._reset();
  14996. };
  14997. /**
  14998. * select this node
  14999. */
  15000. Node.prototype.select = function() {
  15001. this.selected = true;
  15002. this._reset();
  15003. };
  15004. /**
  15005. * unselect this node
  15006. */
  15007. Node.prototype.unselect = function() {
  15008. this.selected = false;
  15009. this._reset();
  15010. };
  15011. /**
  15012. * Reset the calculated size of the node, forces it to recalculate its size
  15013. */
  15014. Node.prototype.clearSizeCache = function() {
  15015. this._reset();
  15016. };
  15017. /**
  15018. * Reset the calculated size of the node, forces it to recalculate its size
  15019. * @private
  15020. */
  15021. Node.prototype._reset = function() {
  15022. this.width = undefined;
  15023. this.height = undefined;
  15024. };
  15025. /**
  15026. * get the title of this node.
  15027. * @return {string} title The title of the node, or undefined when no title
  15028. * has been set.
  15029. */
  15030. Node.prototype.getTitle = function() {
  15031. return typeof this.title === "function" ? this.title() : this.title;
  15032. };
  15033. /**
  15034. * Calculate the distance to the border of the Node
  15035. * @param {CanvasRenderingContext2D} ctx
  15036. * @param {Number} angle Angle in radians
  15037. * @returns {number} distance Distance to the border in pixels
  15038. */
  15039. Node.prototype.distanceToBorder = function (ctx, angle) {
  15040. var borderWidth = 1;
  15041. if (!this.width) {
  15042. this.resize(ctx);
  15043. }
  15044. switch (this.options.shape) {
  15045. case 'circle':
  15046. case 'dot':
  15047. return this.options.radius+ borderWidth;
  15048. case 'ellipse':
  15049. var a = this.width / 2;
  15050. var b = this.height / 2;
  15051. var w = (Math.sin(angle) * a);
  15052. var h = (Math.cos(angle) * b);
  15053. return a * b / Math.sqrt(w * w + h * h);
  15054. // TODO: implement distanceToBorder for database
  15055. // TODO: implement distanceToBorder for triangle
  15056. // TODO: implement distanceToBorder for triangleDown
  15057. case 'box':
  15058. case 'image':
  15059. case 'text':
  15060. default:
  15061. if (this.width) {
  15062. return Math.min(
  15063. Math.abs(this.width / 2 / Math.cos(angle)),
  15064. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  15065. // TODO: reckon with border radius too in case of box
  15066. }
  15067. else {
  15068. return 0;
  15069. }
  15070. }
  15071. // TODO: implement calculation of distance to border for all shapes
  15072. };
  15073. /**
  15074. * Set forces acting on the node
  15075. * @param {number} fx Force in horizontal direction
  15076. * @param {number} fy Force in vertical direction
  15077. */
  15078. Node.prototype._setForce = function(fx, fy) {
  15079. this.fx = fx;
  15080. this.fy = fy;
  15081. };
  15082. /**
  15083. * Add forces acting on the node
  15084. * @param {number} fx Force in horizontal direction
  15085. * @param {number} fy Force in vertical direction
  15086. * @private
  15087. */
  15088. Node.prototype._addForce = function(fx, fy) {
  15089. this.fx += fx;
  15090. this.fy += fy;
  15091. };
  15092. /**
  15093. * Perform one discrete step for the node
  15094. * @param {number} interval Time interval in seconds
  15095. */
  15096. Node.prototype.discreteStep = function(interval) {
  15097. if (!this.xFixed) {
  15098. var dx = this.damping * this.vx; // damping force
  15099. var ax = (this.fx - dx) / this.options.mass; // acceleration
  15100. this.vx += ax * interval; // velocity
  15101. this.x += this.vx * interval; // position
  15102. }
  15103. if (!this.yFixed) {
  15104. var dy = this.damping * this.vy; // damping force
  15105. var ay = (this.fy - dy) / this.options.mass; // acceleration
  15106. this.vy += ay * interval; // velocity
  15107. this.y += this.vy * interval; // position
  15108. }
  15109. };
  15110. /**
  15111. * Perform one discrete step for the node
  15112. * @param {number} interval Time interval in seconds
  15113. * @param {number} maxVelocity The speed limit imposed on the velocity
  15114. */
  15115. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  15116. if (!this.xFixed) {
  15117. var dx = this.damping * this.vx; // damping force
  15118. var ax = (this.fx - dx) / this.options.mass; // acceleration
  15119. this.vx += ax * interval; // velocity
  15120. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  15121. this.x += this.vx * interval; // position
  15122. }
  15123. else {
  15124. this.fx = 0;
  15125. }
  15126. if (!this.yFixed) {
  15127. var dy = this.damping * this.vy; // damping force
  15128. var ay = (this.fy - dy) / this.options.mass; // acceleration
  15129. this.vy += ay * interval; // velocity
  15130. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  15131. this.y += this.vy * interval; // position
  15132. }
  15133. else {
  15134. this.fy = 0;
  15135. }
  15136. };
  15137. /**
  15138. * Check if this node has a fixed x and y position
  15139. * @return {boolean} true if fixed, false if not
  15140. */
  15141. Node.prototype.isFixed = function() {
  15142. return (this.xFixed && this.yFixed);
  15143. };
  15144. /**
  15145. * Check if this node is moving
  15146. * @param {number} vmin the minimum velocity considered as "moving"
  15147. * @return {boolean} true if moving, false if it has no velocity
  15148. */
  15149. // TODO: replace this method with calculating the kinetic energy
  15150. Node.prototype.isMoving = function(vmin) {
  15151. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  15152. };
  15153. /**
  15154. * check if this node is selecte
  15155. * @return {boolean} selected True if node is selected, else false
  15156. */
  15157. Node.prototype.isSelected = function() {
  15158. return this.selected;
  15159. };
  15160. /**
  15161. * Retrieve the value of the node. Can be undefined
  15162. * @return {Number} value
  15163. */
  15164. Node.prototype.getValue = function() {
  15165. return this.value;
  15166. };
  15167. /**
  15168. * Calculate the distance from the nodes location to the given location (x,y)
  15169. * @param {Number} x
  15170. * @param {Number} y
  15171. * @return {Number} value
  15172. */
  15173. Node.prototype.getDistance = function(x, y) {
  15174. var dx = this.x - x,
  15175. dy = this.y - y;
  15176. return Math.sqrt(dx * dx + dy * dy);
  15177. };
  15178. /**
  15179. * Adjust the value range of the node. The node will adjust it's radius
  15180. * based on its value.
  15181. * @param {Number} min
  15182. * @param {Number} max
  15183. */
  15184. Node.prototype.setValueRange = function(min, max) {
  15185. if (!this.radiusFixed && this.value !== undefined) {
  15186. if (max == min) {
  15187. this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2;
  15188. }
  15189. else {
  15190. var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min);
  15191. this.options.radius= (this.value - min) * scale + this.options.radiusMin;
  15192. }
  15193. }
  15194. this.baseRadiusValue = this.options.radius;
  15195. };
  15196. /**
  15197. * Draw this node in the given canvas
  15198. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  15199. * @param {CanvasRenderingContext2D} ctx
  15200. */
  15201. Node.prototype.draw = function(ctx) {
  15202. throw "Draw method not initialized for node";
  15203. };
  15204. /**
  15205. * Recalculate the size of this node in the given canvas
  15206. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  15207. * @param {CanvasRenderingContext2D} ctx
  15208. */
  15209. Node.prototype.resize = function(ctx) {
  15210. throw "Resize method not initialized for node";
  15211. };
  15212. /**
  15213. * Check if this object is overlapping with the provided object
  15214. * @param {Object} obj an object with parameters left, top, right, bottom
  15215. * @return {boolean} True if location is located on node
  15216. */
  15217. Node.prototype.isOverlappingWith = function(obj) {
  15218. return (this.left < obj.right &&
  15219. this.left + this.width > obj.left &&
  15220. this.top < obj.bottom &&
  15221. this.top + this.height > obj.top);
  15222. };
  15223. Node.prototype._resizeImage = function (ctx) {
  15224. // TODO: pre calculate the image size
  15225. if (!this.width || !this.height) { // undefined or 0
  15226. var width, height;
  15227. if (this.value) {
  15228. this.options.radius= this.baseRadiusValue;
  15229. var scale = this.imageObj.height / this.imageObj.width;
  15230. if (scale !== undefined) {
  15231. width = this.options.radius|| this.imageObj.width;
  15232. height = this.options.radius* scale || this.imageObj.height;
  15233. }
  15234. else {
  15235. width = 0;
  15236. height = 0;
  15237. }
  15238. }
  15239. else {
  15240. width = this.imageObj.width;
  15241. height = this.imageObj.height;
  15242. }
  15243. this.width = width;
  15244. this.height = height;
  15245. this.growthIndicator = 0;
  15246. if (this.width > 0 && this.height > 0) {
  15247. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  15248. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  15249. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  15250. this.growthIndicator = this.width - width;
  15251. }
  15252. }
  15253. };
  15254. Node.prototype._drawImage = function (ctx) {
  15255. this._resizeImage(ctx);
  15256. this.left = this.x - this.width / 2;
  15257. this.top = this.y - this.height / 2;
  15258. var yLabel;
  15259. if (this.imageObj.width != 0 ) {
  15260. // draw the shade
  15261. if (this.clusterSize > 1) {
  15262. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  15263. lineWidth *= this.networkScaleInv;
  15264. lineWidth = Math.min(0.2 * this.width,lineWidth);
  15265. ctx.globalAlpha = 0.5;
  15266. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  15267. }
  15268. // draw the image
  15269. ctx.globalAlpha = 1.0;
  15270. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  15271. yLabel = this.y + this.height / 2;
  15272. }
  15273. else {
  15274. // image still loading... just draw the label for now
  15275. yLabel = this.y;
  15276. }
  15277. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  15278. };
  15279. Node.prototype._resizeBox = function (ctx) {
  15280. if (!this.width) {
  15281. var margin = 5;
  15282. var textSize = this.getTextSize(ctx);
  15283. this.width = textSize.width + 2 * margin;
  15284. this.height = textSize.height + 2 * margin;
  15285. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  15286. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  15287. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  15288. // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  15289. }
  15290. };
  15291. Node.prototype._drawBox = function (ctx) {
  15292. this._resizeBox(ctx);
  15293. this.left = this.x - this.width / 2;
  15294. this.top = this.y - this.height / 2;
  15295. var clusterLineWidth = 2.5;
  15296. var borderWidth = this.options.borderWidth;
  15297. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  15298. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  15299. // draw the outer border
  15300. if (this.clusterSize > 1) {
  15301. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15302. ctx.lineWidth *= this.networkScaleInv;
  15303. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15304. 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);
  15305. ctx.stroke();
  15306. }
  15307. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15308. ctx.lineWidth *= this.networkScaleInv;
  15309. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15310. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.options.color.background;
  15311. ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius);
  15312. ctx.fill();
  15313. ctx.stroke();
  15314. this._label(ctx, this.label, this.x, this.y);
  15315. };
  15316. Node.prototype._resizeDatabase = function (ctx) {
  15317. if (!this.width) {
  15318. var margin = 5;
  15319. var textSize = this.getTextSize(ctx);
  15320. var size = textSize.width + 2 * margin;
  15321. this.width = size;
  15322. this.height = size;
  15323. // scaling used for clustering
  15324. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  15325. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  15326. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  15327. this.growthIndicator = this.width - size;
  15328. }
  15329. };
  15330. Node.prototype._drawDatabase = function (ctx) {
  15331. this._resizeDatabase(ctx);
  15332. this.left = this.x - this.width / 2;
  15333. this.top = this.y - this.height / 2;
  15334. var clusterLineWidth = 2.5;
  15335. var borderWidth = this.options.borderWidth;
  15336. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  15337. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  15338. // draw the outer border
  15339. if (this.clusterSize > 1) {
  15340. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15341. ctx.lineWidth *= this.networkScaleInv;
  15342. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15343. 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);
  15344. ctx.stroke();
  15345. }
  15346. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15347. ctx.lineWidth *= this.networkScaleInv;
  15348. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15349. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  15350. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  15351. ctx.fill();
  15352. ctx.stroke();
  15353. this._label(ctx, this.label, this.x, this.y);
  15354. };
  15355. Node.prototype._resizeCircle = function (ctx) {
  15356. if (!this.width) {
  15357. var margin = 5;
  15358. var textSize = this.getTextSize(ctx);
  15359. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  15360. this.options.radius= diameter / 2;
  15361. this.width = diameter;
  15362. this.height = diameter;
  15363. // scaling used for clustering
  15364. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  15365. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  15366. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  15367. this.growthIndicator = this.options.radius- 0.5*diameter;
  15368. }
  15369. };
  15370. Node.prototype._drawCircle = function (ctx) {
  15371. this._resizeCircle(ctx);
  15372. this.left = this.x - this.width / 2;
  15373. this.top = this.y - this.height / 2;
  15374. var clusterLineWidth = 2.5;
  15375. var borderWidth = this.options.borderWidth;
  15376. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  15377. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  15378. // draw the outer border
  15379. if (this.clusterSize > 1) {
  15380. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15381. ctx.lineWidth *= this.networkScaleInv;
  15382. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15383. ctx.circle(this.x, this.y, this.options.radius+2*ctx.lineWidth);
  15384. ctx.stroke();
  15385. }
  15386. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15387. ctx.lineWidth *= this.networkScaleInv;
  15388. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15389. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  15390. ctx.circle(this.x, this.y, this.options.radius);
  15391. ctx.fill();
  15392. ctx.stroke();
  15393. this._label(ctx, this.label, this.x, this.y);
  15394. };
  15395. Node.prototype._resizeEllipse = function (ctx) {
  15396. if (!this.width) {
  15397. var textSize = this.getTextSize(ctx);
  15398. this.width = textSize.width * 1.5;
  15399. this.height = textSize.height * 2;
  15400. if (this.width < this.height) {
  15401. this.width = this.height;
  15402. }
  15403. var defaultSize = this.width;
  15404. // scaling used for clustering
  15405. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  15406. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  15407. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  15408. this.growthIndicator = this.width - defaultSize;
  15409. }
  15410. };
  15411. Node.prototype._drawEllipse = function (ctx) {
  15412. this._resizeEllipse(ctx);
  15413. this.left = this.x - this.width / 2;
  15414. this.top = this.y - this.height / 2;
  15415. var clusterLineWidth = 2.5;
  15416. var borderWidth = this.options.borderWidth;
  15417. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  15418. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  15419. // draw the outer border
  15420. if (this.clusterSize > 1) {
  15421. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15422. ctx.lineWidth *= this.networkScaleInv;
  15423. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15424. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  15425. ctx.stroke();
  15426. }
  15427. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15428. ctx.lineWidth *= this.networkScaleInv;
  15429. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15430. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  15431. ctx.ellipse(this.left, this.top, this.width, this.height);
  15432. ctx.fill();
  15433. ctx.stroke();
  15434. this._label(ctx, this.label, this.x, this.y);
  15435. };
  15436. Node.prototype._drawDot = function (ctx) {
  15437. this._drawShape(ctx, 'circle');
  15438. };
  15439. Node.prototype._drawTriangle = function (ctx) {
  15440. this._drawShape(ctx, 'triangle');
  15441. };
  15442. Node.prototype._drawTriangleDown = function (ctx) {
  15443. this._drawShape(ctx, 'triangleDown');
  15444. };
  15445. Node.prototype._drawSquare = function (ctx) {
  15446. this._drawShape(ctx, 'square');
  15447. };
  15448. Node.prototype._drawStar = function (ctx) {
  15449. this._drawShape(ctx, 'star');
  15450. };
  15451. Node.prototype._resizeShape = function (ctx) {
  15452. if (!this.width) {
  15453. this.options.radius= this.baseRadiusValue;
  15454. var size = 2 * this.options.radius;
  15455. this.width = size;
  15456. this.height = size;
  15457. // scaling used for clustering
  15458. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  15459. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  15460. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  15461. this.growthIndicator = this.width - size;
  15462. }
  15463. };
  15464. Node.prototype._drawShape = function (ctx, shape) {
  15465. this._resizeShape(ctx);
  15466. this.left = this.x - this.width / 2;
  15467. this.top = this.y - this.height / 2;
  15468. var clusterLineWidth = 2.5;
  15469. var borderWidth = this.options.borderWidth;
  15470. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  15471. var radiusMultiplier = 2;
  15472. // choose draw method depending on the shape
  15473. switch (shape) {
  15474. case 'dot': radiusMultiplier = 2; break;
  15475. case 'square': radiusMultiplier = 2; break;
  15476. case 'triangle': radiusMultiplier = 3; break;
  15477. case 'triangleDown': radiusMultiplier = 3; break;
  15478. case 'star': radiusMultiplier = 4; break;
  15479. }
  15480. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  15481. // draw the outer border
  15482. if (this.clusterSize > 1) {
  15483. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15484. ctx.lineWidth *= this.networkScaleInv;
  15485. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15486. ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth);
  15487. ctx.stroke();
  15488. }
  15489. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  15490. ctx.lineWidth *= this.networkScaleInv;
  15491. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  15492. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  15493. ctx[shape](this.x, this.y, this.options.radius);
  15494. ctx.fill();
  15495. ctx.stroke();
  15496. if (this.label) {
  15497. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true);
  15498. }
  15499. };
  15500. Node.prototype._resizeText = function (ctx) {
  15501. if (!this.width) {
  15502. var margin = 5;
  15503. var textSize = this.getTextSize(ctx);
  15504. this.width = textSize.width + 2 * margin;
  15505. this.height = textSize.height + 2 * margin;
  15506. // scaling used for clustering
  15507. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  15508. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  15509. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  15510. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  15511. }
  15512. };
  15513. Node.prototype._drawText = function (ctx) {
  15514. this._resizeText(ctx);
  15515. this.left = this.x - this.width / 2;
  15516. this.top = this.y - this.height / 2;
  15517. this._label(ctx, this.label, this.x, this.y);
  15518. };
  15519. Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) {
  15520. if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) {
  15521. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  15522. ctx.fillStyle = this.options.fontColor || "black";
  15523. ctx.textAlign = align || "center";
  15524. ctx.textBaseline = baseline || "middle";
  15525. var lines = text.split('\n');
  15526. var lineCount = lines.length;
  15527. var fontSize = (Number(this.options.fontSize) + 4);
  15528. var yLine = y + (1 - lineCount) / 2 * fontSize;
  15529. if (labelUnderNode == true) {
  15530. yLine = y + (1 - lineCount) / (2 * fontSize);
  15531. }
  15532. for (var i = 0; i < lineCount; i++) {
  15533. ctx.fillText(lines[i], x, yLine);
  15534. yLine += fontSize;
  15535. }
  15536. }
  15537. };
  15538. Node.prototype.getTextSize = function(ctx) {
  15539. if (this.label !== undefined) {
  15540. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  15541. var lines = this.label.split('\n'),
  15542. height = (Number(this.options.fontSize) + 4) * lines.length,
  15543. width = 0;
  15544. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  15545. width = Math.max(width, ctx.measureText(lines[i]).width);
  15546. }
  15547. return {"width": width, "height": height};
  15548. }
  15549. else {
  15550. return {"width": 0, "height": 0};
  15551. }
  15552. };
  15553. /**
  15554. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  15555. * there is a safety margin of 0.3 * width;
  15556. *
  15557. * @returns {boolean}
  15558. */
  15559. Node.prototype.inArea = function() {
  15560. if (this.width !== undefined) {
  15561. return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x &&
  15562. this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x &&
  15563. this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y &&
  15564. this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y);
  15565. }
  15566. else {
  15567. return true;
  15568. }
  15569. };
  15570. /**
  15571. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  15572. * @returns {boolean}
  15573. */
  15574. Node.prototype.inView = function() {
  15575. return (this.x >= this.canvasTopLeft.x &&
  15576. this.x < this.canvasBottomRight.x &&
  15577. this.y >= this.canvasTopLeft.y &&
  15578. this.y < this.canvasBottomRight.y);
  15579. };
  15580. /**
  15581. * This allows the zoom level of the network to influence the rendering
  15582. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  15583. *
  15584. * @param scale
  15585. * @param canvasTopLeft
  15586. * @param canvasBottomRight
  15587. */
  15588. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  15589. this.networkScaleInv = 1.0/scale;
  15590. this.networkScale = scale;
  15591. this.canvasTopLeft = canvasTopLeft;
  15592. this.canvasBottomRight = canvasBottomRight;
  15593. };
  15594. /**
  15595. * This allows the zoom level of the network to influence the rendering
  15596. *
  15597. * @param scale
  15598. */
  15599. Node.prototype.setScale = function(scale) {
  15600. this.networkScaleInv = 1.0/scale;
  15601. this.networkScale = scale;
  15602. };
  15603. /**
  15604. * set the velocity at 0. Is called when this node is contained in another during clustering
  15605. */
  15606. Node.prototype.clearVelocity = function() {
  15607. this.vx = 0;
  15608. this.vy = 0;
  15609. };
  15610. /**
  15611. * Basic preservation of (kinectic) energy
  15612. *
  15613. * @param massBeforeClustering
  15614. */
  15615. Node.prototype.updateVelocity = function(massBeforeClustering) {
  15616. var energyBefore = this.vx * this.vx * massBeforeClustering;
  15617. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  15618. this.vx = Math.sqrt(energyBefore/this.options.mass);
  15619. energyBefore = this.vy * this.vy * massBeforeClustering;
  15620. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  15621. this.vy = Math.sqrt(energyBefore/this.options.mass);
  15622. };
  15623. module.exports = Node;
  15624. /***/ },
  15625. /* 37 */
  15626. /***/ function(module, exports, __webpack_require__) {
  15627. /**
  15628. * Popup is a class to create a popup window with some text
  15629. * @param {Element} container The container object.
  15630. * @param {Number} [x]
  15631. * @param {Number} [y]
  15632. * @param {String} [text]
  15633. * @param {Object} [style] An object containing borderColor,
  15634. * backgroundColor, etc.
  15635. */
  15636. function Popup(container, x, y, text, style) {
  15637. if (container) {
  15638. this.container = container;
  15639. }
  15640. else {
  15641. this.container = document.body;
  15642. }
  15643. // x, y and text are optional, see if a style object was passed in their place
  15644. if (style === undefined) {
  15645. if (typeof x === "object") {
  15646. style = x;
  15647. x = undefined;
  15648. } else if (typeof text === "object") {
  15649. style = text;
  15650. text = undefined;
  15651. } else {
  15652. // for backwards compatibility, in case clients other than Network are creating Popup directly
  15653. style = {
  15654. fontColor: 'black',
  15655. fontSize: 14, // px
  15656. fontFace: 'verdana',
  15657. color: {
  15658. border: '#666',
  15659. background: '#FFFFC6'
  15660. }
  15661. }
  15662. }
  15663. }
  15664. this.x = 0;
  15665. this.y = 0;
  15666. this.padding = 5;
  15667. if (x !== undefined && y !== undefined ) {
  15668. this.setPosition(x, y);
  15669. }
  15670. if (text !== undefined) {
  15671. this.setText(text);
  15672. }
  15673. // create the frame
  15674. this.frame = document.createElement("div");
  15675. var styleAttr = this.frame.style;
  15676. styleAttr.position = "absolute";
  15677. styleAttr.visibility = "hidden";
  15678. styleAttr.border = "1px solid " + style.color.border;
  15679. styleAttr.color = style.fontColor;
  15680. styleAttr.fontSize = style.fontSize + "px";
  15681. styleAttr.fontFamily = style.fontFace;
  15682. styleAttr.padding = this.padding + "px";
  15683. styleAttr.backgroundColor = style.color.background;
  15684. styleAttr.borderRadius = "3px";
  15685. styleAttr.MozBorderRadius = "3px";
  15686. styleAttr.WebkitBorderRadius = "3px";
  15687. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  15688. styleAttr.whiteSpace = "nowrap";
  15689. this.container.appendChild(this.frame);
  15690. }
  15691. /**
  15692. * @param {number} x Horizontal position of the popup window
  15693. * @param {number} y Vertical position of the popup window
  15694. */
  15695. Popup.prototype.setPosition = function(x, y) {
  15696. this.x = parseInt(x);
  15697. this.y = parseInt(y);
  15698. };
  15699. /**
  15700. * Set the text for the popup window. This can be HTML code
  15701. * @param {string} text
  15702. */
  15703. Popup.prototype.setText = function(text) {
  15704. this.frame.innerHTML = text;
  15705. };
  15706. /**
  15707. * Show the popup window
  15708. * @param {boolean} show Optional. Show or hide the window
  15709. */
  15710. Popup.prototype.show = function (show) {
  15711. if (show === undefined) {
  15712. show = true;
  15713. }
  15714. if (show) {
  15715. var height = this.frame.clientHeight;
  15716. var width = this.frame.clientWidth;
  15717. var maxHeight = this.frame.parentNode.clientHeight;
  15718. var maxWidth = this.frame.parentNode.clientWidth;
  15719. var top = (this.y - height);
  15720. if (top + height + this.padding > maxHeight) {
  15721. top = maxHeight - height - this.padding;
  15722. }
  15723. if (top < this.padding) {
  15724. top = this.padding;
  15725. }
  15726. var left = this.x;
  15727. if (left + width + this.padding > maxWidth) {
  15728. left = maxWidth - width - this.padding;
  15729. }
  15730. if (left < this.padding) {
  15731. left = this.padding;
  15732. }
  15733. this.frame.style.left = left + "px";
  15734. this.frame.style.top = top + "px";
  15735. this.frame.style.visibility = "visible";
  15736. }
  15737. else {
  15738. this.hide();
  15739. }
  15740. };
  15741. /**
  15742. * Hide the popup window
  15743. */
  15744. Popup.prototype.hide = function () {
  15745. this.frame.style.visibility = "hidden";
  15746. };
  15747. module.exports = Popup;
  15748. /***/ },
  15749. /* 38 */
  15750. /***/ function(module, exports, __webpack_require__) {
  15751. /**
  15752. * Parse a text source containing data in DOT language into a JSON object.
  15753. * The object contains two lists: one with nodes and one with edges.
  15754. *
  15755. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  15756. *
  15757. * @param {String} data Text containing a graph in DOT-notation
  15758. * @return {Object} graph An object containing two parameters:
  15759. * {Object[]} nodes
  15760. * {Object[]} edges
  15761. */
  15762. function parseDOT (data) {
  15763. dot = data;
  15764. return parseGraph();
  15765. }
  15766. // token types enumeration
  15767. var TOKENTYPE = {
  15768. NULL : 0,
  15769. DELIMITER : 1,
  15770. IDENTIFIER: 2,
  15771. UNKNOWN : 3
  15772. };
  15773. // map with all delimiters
  15774. var DELIMITERS = {
  15775. '{': true,
  15776. '}': true,
  15777. '[': true,
  15778. ']': true,
  15779. ';': true,
  15780. '=': true,
  15781. ',': true,
  15782. '->': true,
  15783. '--': true
  15784. };
  15785. var dot = ''; // current dot file
  15786. var index = 0; // current index in dot file
  15787. var c = ''; // current token character in expr
  15788. var token = ''; // current token
  15789. var tokenType = TOKENTYPE.NULL; // type of the token
  15790. /**
  15791. * Get the first character from the dot file.
  15792. * The character is stored into the char c. If the end of the dot file is
  15793. * reached, the function puts an empty string in c.
  15794. */
  15795. function first() {
  15796. index = 0;
  15797. c = dot.charAt(0);
  15798. }
  15799. /**
  15800. * Get the next character from the dot file.
  15801. * The character is stored into the char c. If the end of the dot file is
  15802. * reached, the function puts an empty string in c.
  15803. */
  15804. function next() {
  15805. index++;
  15806. c = dot.charAt(index);
  15807. }
  15808. /**
  15809. * Preview the next character from the dot file.
  15810. * @return {String} cNext
  15811. */
  15812. function nextPreview() {
  15813. return dot.charAt(index + 1);
  15814. }
  15815. /**
  15816. * Test whether given character is alphabetic or numeric
  15817. * @param {String} c
  15818. * @return {Boolean} isAlphaNumeric
  15819. */
  15820. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  15821. function isAlphaNumeric(c) {
  15822. return regexAlphaNumeric.test(c);
  15823. }
  15824. /**
  15825. * Merge all properties of object b into object b
  15826. * @param {Object} a
  15827. * @param {Object} b
  15828. * @return {Object} a
  15829. */
  15830. function merge (a, b) {
  15831. if (!a) {
  15832. a = {};
  15833. }
  15834. if (b) {
  15835. for (var name in b) {
  15836. if (b.hasOwnProperty(name)) {
  15837. a[name] = b[name];
  15838. }
  15839. }
  15840. }
  15841. return a;
  15842. }
  15843. /**
  15844. * Set a value in an object, where the provided parameter name can be a
  15845. * path with nested parameters. For example:
  15846. *
  15847. * var obj = {a: 2};
  15848. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  15849. *
  15850. * @param {Object} obj
  15851. * @param {String} path A parameter name or dot-separated parameter path,
  15852. * like "color.highlight.border".
  15853. * @param {*} value
  15854. */
  15855. function setValue(obj, path, value) {
  15856. var keys = path.split('.');
  15857. var o = obj;
  15858. while (keys.length) {
  15859. var key = keys.shift();
  15860. if (keys.length) {
  15861. // this isn't the end point
  15862. if (!o[key]) {
  15863. o[key] = {};
  15864. }
  15865. o = o[key];
  15866. }
  15867. else {
  15868. // this is the end point
  15869. o[key] = value;
  15870. }
  15871. }
  15872. }
  15873. /**
  15874. * Add a node to a graph object. If there is already a node with
  15875. * the same id, their attributes will be merged.
  15876. * @param {Object} graph
  15877. * @param {Object} node
  15878. */
  15879. function addNode(graph, node) {
  15880. var i, len;
  15881. var current = null;
  15882. // find root graph (in case of subgraph)
  15883. var graphs = [graph]; // list with all graphs from current graph to root graph
  15884. var root = graph;
  15885. while (root.parent) {
  15886. graphs.push(root.parent);
  15887. root = root.parent;
  15888. }
  15889. // find existing node (at root level) by its id
  15890. if (root.nodes) {
  15891. for (i = 0, len = root.nodes.length; i < len; i++) {
  15892. if (node.id === root.nodes[i].id) {
  15893. current = root.nodes[i];
  15894. break;
  15895. }
  15896. }
  15897. }
  15898. if (!current) {
  15899. // this is a new node
  15900. current = {
  15901. id: node.id
  15902. };
  15903. if (graph.node) {
  15904. // clone default attributes
  15905. current.attr = merge(current.attr, graph.node);
  15906. }
  15907. }
  15908. // add node to this (sub)graph and all its parent graphs
  15909. for (i = graphs.length - 1; i >= 0; i--) {
  15910. var g = graphs[i];
  15911. if (!g.nodes) {
  15912. g.nodes = [];
  15913. }
  15914. if (g.nodes.indexOf(current) == -1) {
  15915. g.nodes.push(current);
  15916. }
  15917. }
  15918. // merge attributes
  15919. if (node.attr) {
  15920. current.attr = merge(current.attr, node.attr);
  15921. }
  15922. }
  15923. /**
  15924. * Add an edge to a graph object
  15925. * @param {Object} graph
  15926. * @param {Object} edge
  15927. */
  15928. function addEdge(graph, edge) {
  15929. if (!graph.edges) {
  15930. graph.edges = [];
  15931. }
  15932. graph.edges.push(edge);
  15933. if (graph.edge) {
  15934. var attr = merge({}, graph.edge); // clone default attributes
  15935. edge.attr = merge(attr, edge.attr); // merge attributes
  15936. }
  15937. }
  15938. /**
  15939. * Create an edge to a graph object
  15940. * @param {Object} graph
  15941. * @param {String | Number | Object} from
  15942. * @param {String | Number | Object} to
  15943. * @param {String} type
  15944. * @param {Object | null} attr
  15945. * @return {Object} edge
  15946. */
  15947. function createEdge(graph, from, to, type, attr) {
  15948. var edge = {
  15949. from: from,
  15950. to: to,
  15951. type: type
  15952. };
  15953. if (graph.edge) {
  15954. edge.attr = merge({}, graph.edge); // clone default attributes
  15955. }
  15956. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  15957. return edge;
  15958. }
  15959. /**
  15960. * Get next token in the current dot file.
  15961. * The token and token type are available as token and tokenType
  15962. */
  15963. function getToken() {
  15964. tokenType = TOKENTYPE.NULL;
  15965. token = '';
  15966. // skip over whitespaces
  15967. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  15968. next();
  15969. }
  15970. do {
  15971. var isComment = false;
  15972. // skip comment
  15973. if (c == '#') {
  15974. // find the previous non-space character
  15975. var i = index - 1;
  15976. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  15977. i--;
  15978. }
  15979. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  15980. // the # is at the start of a line, this is indeed a line comment
  15981. while (c != '' && c != '\n') {
  15982. next();
  15983. }
  15984. isComment = true;
  15985. }
  15986. }
  15987. if (c == '/' && nextPreview() == '/') {
  15988. // skip line comment
  15989. while (c != '' && c != '\n') {
  15990. next();
  15991. }
  15992. isComment = true;
  15993. }
  15994. if (c == '/' && nextPreview() == '*') {
  15995. // skip block comment
  15996. while (c != '') {
  15997. if (c == '*' && nextPreview() == '/') {
  15998. // end of block comment found. skip these last two characters
  15999. next();
  16000. next();
  16001. break;
  16002. }
  16003. else {
  16004. next();
  16005. }
  16006. }
  16007. isComment = true;
  16008. }
  16009. // skip over whitespaces
  16010. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  16011. next();
  16012. }
  16013. }
  16014. while (isComment);
  16015. // check for end of dot file
  16016. if (c == '') {
  16017. // token is still empty
  16018. tokenType = TOKENTYPE.DELIMITER;
  16019. return;
  16020. }
  16021. // check for delimiters consisting of 2 characters
  16022. var c2 = c + nextPreview();
  16023. if (DELIMITERS[c2]) {
  16024. tokenType = TOKENTYPE.DELIMITER;
  16025. token = c2;
  16026. next();
  16027. next();
  16028. return;
  16029. }
  16030. // check for delimiters consisting of 1 character
  16031. if (DELIMITERS[c]) {
  16032. tokenType = TOKENTYPE.DELIMITER;
  16033. token = c;
  16034. next();
  16035. return;
  16036. }
  16037. // check for an identifier (number or string)
  16038. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  16039. if (isAlphaNumeric(c) || c == '-') {
  16040. token += c;
  16041. next();
  16042. while (isAlphaNumeric(c)) {
  16043. token += c;
  16044. next();
  16045. }
  16046. if (token == 'false') {
  16047. token = false; // convert to boolean
  16048. }
  16049. else if (token == 'true') {
  16050. token = true; // convert to boolean
  16051. }
  16052. else if (!isNaN(Number(token))) {
  16053. token = Number(token); // convert to number
  16054. }
  16055. tokenType = TOKENTYPE.IDENTIFIER;
  16056. return;
  16057. }
  16058. // check for a string enclosed by double quotes
  16059. if (c == '"') {
  16060. next();
  16061. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  16062. token += c;
  16063. if (c == '"') { // skip the escape character
  16064. next();
  16065. }
  16066. next();
  16067. }
  16068. if (c != '"') {
  16069. throw newSyntaxError('End of string " expected');
  16070. }
  16071. next();
  16072. tokenType = TOKENTYPE.IDENTIFIER;
  16073. return;
  16074. }
  16075. // something unknown is found, wrong characters, a syntax error
  16076. tokenType = TOKENTYPE.UNKNOWN;
  16077. while (c != '') {
  16078. token += c;
  16079. next();
  16080. }
  16081. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  16082. }
  16083. /**
  16084. * Parse a graph.
  16085. * @returns {Object} graph
  16086. */
  16087. function parseGraph() {
  16088. var graph = {};
  16089. first();
  16090. getToken();
  16091. // optional strict keyword
  16092. if (token == 'strict') {
  16093. graph.strict = true;
  16094. getToken();
  16095. }
  16096. // graph or digraph keyword
  16097. if (token == 'graph' || token == 'digraph') {
  16098. graph.type = token;
  16099. getToken();
  16100. }
  16101. // optional graph id
  16102. if (tokenType == TOKENTYPE.IDENTIFIER) {
  16103. graph.id = token;
  16104. getToken();
  16105. }
  16106. // open angle bracket
  16107. if (token != '{') {
  16108. throw newSyntaxError('Angle bracket { expected');
  16109. }
  16110. getToken();
  16111. // statements
  16112. parseStatements(graph);
  16113. // close angle bracket
  16114. if (token != '}') {
  16115. throw newSyntaxError('Angle bracket } expected');
  16116. }
  16117. getToken();
  16118. // end of file
  16119. if (token !== '') {
  16120. throw newSyntaxError('End of file expected');
  16121. }
  16122. getToken();
  16123. // remove temporary default properties
  16124. delete graph.node;
  16125. delete graph.edge;
  16126. delete graph.graph;
  16127. return graph;
  16128. }
  16129. /**
  16130. * Parse a list with statements.
  16131. * @param {Object} graph
  16132. */
  16133. function parseStatements (graph) {
  16134. while (token !== '' && token != '}') {
  16135. parseStatement(graph);
  16136. if (token == ';') {
  16137. getToken();
  16138. }
  16139. }
  16140. }
  16141. /**
  16142. * Parse a single statement. Can be a an attribute statement, node
  16143. * statement, a series of node statements and edge statements, or a
  16144. * parameter.
  16145. * @param {Object} graph
  16146. */
  16147. function parseStatement(graph) {
  16148. // parse subgraph
  16149. var subgraph = parseSubgraph(graph);
  16150. if (subgraph) {
  16151. // edge statements
  16152. parseEdge(graph, subgraph);
  16153. return;
  16154. }
  16155. // parse an attribute statement
  16156. var attr = parseAttributeStatement(graph);
  16157. if (attr) {
  16158. return;
  16159. }
  16160. // parse node
  16161. if (tokenType != TOKENTYPE.IDENTIFIER) {
  16162. throw newSyntaxError('Identifier expected');
  16163. }
  16164. var id = token; // id can be a string or a number
  16165. getToken();
  16166. if (token == '=') {
  16167. // id statement
  16168. getToken();
  16169. if (tokenType != TOKENTYPE.IDENTIFIER) {
  16170. throw newSyntaxError('Identifier expected');
  16171. }
  16172. graph[id] = token;
  16173. getToken();
  16174. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  16175. }
  16176. else {
  16177. parseNodeStatement(graph, id);
  16178. }
  16179. }
  16180. /**
  16181. * Parse a subgraph
  16182. * @param {Object} graph parent graph object
  16183. * @return {Object | null} subgraph
  16184. */
  16185. function parseSubgraph (graph) {
  16186. var subgraph = null;
  16187. // optional subgraph keyword
  16188. if (token == 'subgraph') {
  16189. subgraph = {};
  16190. subgraph.type = 'subgraph';
  16191. getToken();
  16192. // optional graph id
  16193. if (tokenType == TOKENTYPE.IDENTIFIER) {
  16194. subgraph.id = token;
  16195. getToken();
  16196. }
  16197. }
  16198. // open angle bracket
  16199. if (token == '{') {
  16200. getToken();
  16201. if (!subgraph) {
  16202. subgraph = {};
  16203. }
  16204. subgraph.parent = graph;
  16205. subgraph.node = graph.node;
  16206. subgraph.edge = graph.edge;
  16207. subgraph.graph = graph.graph;
  16208. // statements
  16209. parseStatements(subgraph);
  16210. // close angle bracket
  16211. if (token != '}') {
  16212. throw newSyntaxError('Angle bracket } expected');
  16213. }
  16214. getToken();
  16215. // remove temporary default properties
  16216. delete subgraph.node;
  16217. delete subgraph.edge;
  16218. delete subgraph.graph;
  16219. delete subgraph.parent;
  16220. // register at the parent graph
  16221. if (!graph.subgraphs) {
  16222. graph.subgraphs = [];
  16223. }
  16224. graph.subgraphs.push(subgraph);
  16225. }
  16226. return subgraph;
  16227. }
  16228. /**
  16229. * parse an attribute statement like "node [shape=circle fontSize=16]".
  16230. * Available keywords are 'node', 'edge', 'graph'.
  16231. * The previous list with default attributes will be replaced
  16232. * @param {Object} graph
  16233. * @returns {String | null} keyword Returns the name of the parsed attribute
  16234. * (node, edge, graph), or null if nothing
  16235. * is parsed.
  16236. */
  16237. function parseAttributeStatement (graph) {
  16238. // attribute statements
  16239. if (token == 'node') {
  16240. getToken();
  16241. // node attributes
  16242. graph.node = parseAttributeList();
  16243. return 'node';
  16244. }
  16245. else if (token == 'edge') {
  16246. getToken();
  16247. // edge attributes
  16248. graph.edge = parseAttributeList();
  16249. return 'edge';
  16250. }
  16251. else if (token == 'graph') {
  16252. getToken();
  16253. // graph attributes
  16254. graph.graph = parseAttributeList();
  16255. return 'graph';
  16256. }
  16257. return null;
  16258. }
  16259. /**
  16260. * parse a node statement
  16261. * @param {Object} graph
  16262. * @param {String | Number} id
  16263. */
  16264. function parseNodeStatement(graph, id) {
  16265. // node statement
  16266. var node = {
  16267. id: id
  16268. };
  16269. var attr = parseAttributeList();
  16270. if (attr) {
  16271. node.attr = attr;
  16272. }
  16273. addNode(graph, node);
  16274. // edge statements
  16275. parseEdge(graph, id);
  16276. }
  16277. /**
  16278. * Parse an edge or a series of edges
  16279. * @param {Object} graph
  16280. * @param {String | Number} from Id of the from node
  16281. */
  16282. function parseEdge(graph, from) {
  16283. while (token == '->' || token == '--') {
  16284. var to;
  16285. var type = token;
  16286. getToken();
  16287. var subgraph = parseSubgraph(graph);
  16288. if (subgraph) {
  16289. to = subgraph;
  16290. }
  16291. else {
  16292. if (tokenType != TOKENTYPE.IDENTIFIER) {
  16293. throw newSyntaxError('Identifier or subgraph expected');
  16294. }
  16295. to = token;
  16296. addNode(graph, {
  16297. id: to
  16298. });
  16299. getToken();
  16300. }
  16301. // parse edge attributes
  16302. var attr = parseAttributeList();
  16303. // create edge
  16304. var edge = createEdge(graph, from, to, type, attr);
  16305. addEdge(graph, edge);
  16306. from = to;
  16307. }
  16308. }
  16309. /**
  16310. * Parse a set with attributes,
  16311. * for example [label="1.000", shape=solid]
  16312. * @return {Object | null} attr
  16313. */
  16314. function parseAttributeList() {
  16315. var attr = null;
  16316. while (token == '[') {
  16317. getToken();
  16318. attr = {};
  16319. while (token !== '' && token != ']') {
  16320. if (tokenType != TOKENTYPE.IDENTIFIER) {
  16321. throw newSyntaxError('Attribute name expected');
  16322. }
  16323. var name = token;
  16324. getToken();
  16325. if (token != '=') {
  16326. throw newSyntaxError('Equal sign = expected');
  16327. }
  16328. getToken();
  16329. if (tokenType != TOKENTYPE.IDENTIFIER) {
  16330. throw newSyntaxError('Attribute value expected');
  16331. }
  16332. var value = token;
  16333. setValue(attr, name, value); // name can be a path
  16334. getToken();
  16335. if (token ==',') {
  16336. getToken();
  16337. }
  16338. }
  16339. if (token != ']') {
  16340. throw newSyntaxError('Bracket ] expected');
  16341. }
  16342. getToken();
  16343. }
  16344. return attr;
  16345. }
  16346. /**
  16347. * Create a syntax error with extra information on current token and index.
  16348. * @param {String} message
  16349. * @returns {SyntaxError} err
  16350. */
  16351. function newSyntaxError(message) {
  16352. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  16353. }
  16354. /**
  16355. * Chop off text after a maximum length
  16356. * @param {String} text
  16357. * @param {Number} maxLength
  16358. * @returns {String}
  16359. */
  16360. function chop (text, maxLength) {
  16361. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  16362. }
  16363. /**
  16364. * Execute a function fn for each pair of elements in two arrays
  16365. * @param {Array | *} array1
  16366. * @param {Array | *} array2
  16367. * @param {function} fn
  16368. */
  16369. function forEach2(array1, array2, fn) {
  16370. if (array1 instanceof Array) {
  16371. array1.forEach(function (elem1) {
  16372. if (array2 instanceof Array) {
  16373. array2.forEach(function (elem2) {
  16374. fn(elem1, elem2);
  16375. });
  16376. }
  16377. else {
  16378. fn(elem1, array2);
  16379. }
  16380. });
  16381. }
  16382. else {
  16383. if (array2 instanceof Array) {
  16384. array2.forEach(function (elem2) {
  16385. fn(array1, elem2);
  16386. });
  16387. }
  16388. else {
  16389. fn(array1, array2);
  16390. }
  16391. }
  16392. }
  16393. /**
  16394. * Convert a string containing a graph in DOT language into a map containing
  16395. * with nodes and edges in the format of graph.
  16396. * @param {String} data Text containing a graph in DOT-notation
  16397. * @return {Object} graphData
  16398. */
  16399. function DOTToGraph (data) {
  16400. // parse the DOT file
  16401. var dotData = parseDOT(data);
  16402. var graphData = {
  16403. nodes: [],
  16404. edges: [],
  16405. options: {}
  16406. };
  16407. // copy the nodes
  16408. if (dotData.nodes) {
  16409. dotData.nodes.forEach(function (dotNode) {
  16410. var graphNode = {
  16411. id: dotNode.id,
  16412. label: String(dotNode.label || dotNode.id)
  16413. };
  16414. merge(graphNode, dotNode.attr);
  16415. if (graphNode.image) {
  16416. graphNode.shape = 'image';
  16417. }
  16418. graphData.nodes.push(graphNode);
  16419. });
  16420. }
  16421. // copy the edges
  16422. if (dotData.edges) {
  16423. /**
  16424. * Convert an edge in DOT format to an edge with VisGraph format
  16425. * @param {Object} dotEdge
  16426. * @returns {Object} graphEdge
  16427. */
  16428. function convertEdge(dotEdge) {
  16429. var graphEdge = {
  16430. from: dotEdge.from,
  16431. to: dotEdge.to
  16432. };
  16433. merge(graphEdge, dotEdge.attr);
  16434. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  16435. return graphEdge;
  16436. }
  16437. dotData.edges.forEach(function (dotEdge) {
  16438. var from, to;
  16439. if (dotEdge.from instanceof Object) {
  16440. from = dotEdge.from.nodes;
  16441. }
  16442. else {
  16443. from = {
  16444. id: dotEdge.from
  16445. }
  16446. }
  16447. if (dotEdge.to instanceof Object) {
  16448. to = dotEdge.to.nodes;
  16449. }
  16450. else {
  16451. to = {
  16452. id: dotEdge.to
  16453. }
  16454. }
  16455. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  16456. dotEdge.from.edges.forEach(function (subEdge) {
  16457. var graphEdge = convertEdge(subEdge);
  16458. graphData.edges.push(graphEdge);
  16459. });
  16460. }
  16461. forEach2(from, to, function (from, to) {
  16462. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  16463. var graphEdge = convertEdge(subEdge);
  16464. graphData.edges.push(graphEdge);
  16465. });
  16466. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  16467. dotEdge.to.edges.forEach(function (subEdge) {
  16468. var graphEdge = convertEdge(subEdge);
  16469. graphData.edges.push(graphEdge);
  16470. });
  16471. }
  16472. });
  16473. }
  16474. // copy the options
  16475. if (dotData.attr) {
  16476. graphData.options = dotData.attr;
  16477. }
  16478. return graphData;
  16479. }
  16480. // exports
  16481. exports.parseDOT = parseDOT;
  16482. exports.DOTToGraph = DOTToGraph;
  16483. /***/ },
  16484. /* 39 */
  16485. /***/ function(module, exports, __webpack_require__) {
  16486. function parseGephi(gephiJSON, options) {
  16487. var edges = [];
  16488. var nodes = [];
  16489. this.options = {
  16490. edges: {
  16491. inheritColor: true
  16492. },
  16493. nodes: {
  16494. allowedToMove: false,
  16495. parseColor: false
  16496. }
  16497. };
  16498. if (options !== undefined) {
  16499. this.options.nodes['allowedToMove'] = options.allowedToMove | false;
  16500. this.options.nodes['parseColor'] = options.parseColor | false;
  16501. this.options.edges['inheritColor'] = options.inheritColor | true;
  16502. }
  16503. var gEdges = gephiJSON.edges;
  16504. var gNodes = gephiJSON.nodes;
  16505. for (var i = 0; i < gEdges.length; i++) {
  16506. var edge = {};
  16507. var gEdge = gEdges[i];
  16508. edge['id'] = gEdge.id;
  16509. edge['from'] = gEdge.source;
  16510. edge['to'] = gEdge.target;
  16511. edge['attributes'] = gEdge.attributes;
  16512. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  16513. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  16514. edge['color'] = gEdge.color;
  16515. edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
  16516. edges.push(edge);
  16517. }
  16518. for (var i = 0; i < gNodes.length; i++) {
  16519. var node = {};
  16520. var gNode = gNodes[i];
  16521. node['id'] = gNode.id;
  16522. node['attributes'] = gNode.attributes;
  16523. node['x'] = gNode.x;
  16524. node['y'] = gNode.y;
  16525. node['label'] = gNode.label;
  16526. if (this.options.nodes.parseColor == true) {
  16527. node['color'] = gNode.color;
  16528. }
  16529. else {
  16530. node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
  16531. }
  16532. node['radius'] = gNode.size;
  16533. node['allowedToMoveX'] = this.options.nodes.allowedToMove;
  16534. node['allowedToMoveY'] = this.options.nodes.allowedToMove;
  16535. nodes.push(node);
  16536. }
  16537. return {nodes:nodes, edges:edges};
  16538. }
  16539. exports.parseGephi = parseGephi;
  16540. /***/ },
  16541. /* 40 */
  16542. /***/ function(module, exports, __webpack_require__) {
  16543. // first check if moment.js is already loaded in the browser window, if so,
  16544. // use this instance. Else, load via commonjs.
  16545. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(48);
  16546. /***/ },
  16547. /* 41 */
  16548. /***/ function(module, exports, __webpack_require__) {
  16549. // Only load hammer.js when in a browser environment
  16550. // (loading hammer.js in a node.js environment gives errors)
  16551. if (typeof window !== 'undefined') {
  16552. module.exports = window['Hammer'] || __webpack_require__(49);
  16553. }
  16554. else {
  16555. module.exports = function () {
  16556. throw Error('hammer.js is only available in a browser, not in node.js.');
  16557. }
  16558. }
  16559. /***/ },
  16560. /* 42 */
  16561. /***/ function(module, exports, __webpack_require__) {
  16562. var Emitter = __webpack_require__(46);
  16563. var Hammer = __webpack_require__(41);
  16564. var util = __webpack_require__(1);
  16565. var DataSet = __webpack_require__(3);
  16566. var DataView = __webpack_require__(4);
  16567. var Range = __webpack_require__(15);
  16568. var TimeAxis = __webpack_require__(27);
  16569. var CurrentTime = __webpack_require__(19);
  16570. var CustomTime = __webpack_require__(20);
  16571. var ItemSet = __webpack_require__(24);
  16572. /**
  16573. * Create a timeline visualization
  16574. * @param {HTMLElement} container
  16575. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  16576. * @param {Object} [options] See Core.setOptions for the available options.
  16577. * @constructor
  16578. */
  16579. function Core () {}
  16580. // turn Core into an event emitter
  16581. Emitter(Core.prototype);
  16582. /**
  16583. * Create the main DOM for the Core: a root panel containing left, right,
  16584. * top, bottom, content, and background panel.
  16585. * @param {Element} container The container element where the Core will
  16586. * be attached.
  16587. * @private
  16588. */
  16589. Core.prototype._create = function (container) {
  16590. this.dom = {};
  16591. this.dom.root = document.createElement('div');
  16592. this.dom.background = document.createElement('div');
  16593. this.dom.backgroundVertical = document.createElement('div');
  16594. this.dom.backgroundHorizontal = document.createElement('div');
  16595. this.dom.centerContainer = document.createElement('div');
  16596. this.dom.leftContainer = document.createElement('div');
  16597. this.dom.rightContainer = document.createElement('div');
  16598. this.dom.center = document.createElement('div');
  16599. this.dom.left = document.createElement('div');
  16600. this.dom.right = document.createElement('div');
  16601. this.dom.top = document.createElement('div');
  16602. this.dom.bottom = document.createElement('div');
  16603. this.dom.shadowTop = document.createElement('div');
  16604. this.dom.shadowBottom = document.createElement('div');
  16605. this.dom.shadowTopLeft = document.createElement('div');
  16606. this.dom.shadowBottomLeft = document.createElement('div');
  16607. this.dom.shadowTopRight = document.createElement('div');
  16608. this.dom.shadowBottomRight = document.createElement('div');
  16609. this.dom.background.className = 'vispanel background';
  16610. this.dom.backgroundVertical.className = 'vispanel background vertical';
  16611. this.dom.backgroundHorizontal.className = 'vispanel background horizontal';
  16612. this.dom.centerContainer.className = 'vispanel center';
  16613. this.dom.leftContainer.className = 'vispanel left';
  16614. this.dom.rightContainer.className = 'vispanel right';
  16615. this.dom.top.className = 'vispanel top';
  16616. this.dom.bottom.className = 'vispanel bottom';
  16617. this.dom.left.className = 'content';
  16618. this.dom.center.className = 'content';
  16619. this.dom.right.className = 'content';
  16620. this.dom.shadowTop.className = 'shadow top';
  16621. this.dom.shadowBottom.className = 'shadow bottom';
  16622. this.dom.shadowTopLeft.className = 'shadow top';
  16623. this.dom.shadowBottomLeft.className = 'shadow bottom';
  16624. this.dom.shadowTopRight.className = 'shadow top';
  16625. this.dom.shadowBottomRight.className = 'shadow bottom';
  16626. this.dom.root.appendChild(this.dom.background);
  16627. this.dom.root.appendChild(this.dom.backgroundVertical);
  16628. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  16629. this.dom.root.appendChild(this.dom.centerContainer);
  16630. this.dom.root.appendChild(this.dom.leftContainer);
  16631. this.dom.root.appendChild(this.dom.rightContainer);
  16632. this.dom.root.appendChild(this.dom.top);
  16633. this.dom.root.appendChild(this.dom.bottom);
  16634. this.dom.centerContainer.appendChild(this.dom.center);
  16635. this.dom.leftContainer.appendChild(this.dom.left);
  16636. this.dom.rightContainer.appendChild(this.dom.right);
  16637. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  16638. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  16639. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  16640. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  16641. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  16642. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  16643. this.on('rangechange', this.redraw.bind(this));
  16644. this.on('change', this.redraw.bind(this));
  16645. this.on('touch', this._onTouch.bind(this));
  16646. this.on('pinch', this._onPinch.bind(this));
  16647. this.on('dragstart', this._onDragStart.bind(this));
  16648. this.on('drag', this._onDrag.bind(this));
  16649. // create event listeners for all interesting events, these events will be
  16650. // emitted via emitter
  16651. this.hammer = Hammer(this.dom.root, {
  16652. prevent_default: true
  16653. });
  16654. this.listeners = {};
  16655. var me = this;
  16656. var events = [
  16657. 'touch', 'pinch',
  16658. 'tap', 'doubletap', 'hold',
  16659. 'dragstart', 'drag', 'dragend',
  16660. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  16661. ];
  16662. events.forEach(function (event) {
  16663. var listener = function () {
  16664. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  16665. me.emit.apply(me, args);
  16666. };
  16667. me.hammer.on(event, listener);
  16668. me.listeners[event] = listener;
  16669. });
  16670. // size properties of each of the panels
  16671. this.props = {
  16672. root: {},
  16673. background: {},
  16674. centerContainer: {},
  16675. leftContainer: {},
  16676. rightContainer: {},
  16677. center: {},
  16678. left: {},
  16679. right: {},
  16680. top: {},
  16681. bottom: {},
  16682. border: {},
  16683. scrollTop: 0,
  16684. scrollTopMin: 0
  16685. };
  16686. this.touch = {}; // store state information needed for touch events
  16687. // attach the root panel to the provided container
  16688. if (!container) throw new Error('No container provided');
  16689. container.appendChild(this.dom.root);
  16690. };
  16691. /**
  16692. * Destroy the Core, clean up all DOM elements and event listeners.
  16693. */
  16694. Core.prototype.destroy = function () {
  16695. // unbind datasets
  16696. this.clear();
  16697. // remove all event listeners
  16698. this.off();
  16699. // stop checking for changed size
  16700. this._stopAutoResize();
  16701. // remove from DOM
  16702. if (this.dom.root.parentNode) {
  16703. this.dom.root.parentNode.removeChild(this.dom.root);
  16704. }
  16705. this.dom = null;
  16706. // cleanup hammer touch events
  16707. for (var event in this.listeners) {
  16708. if (this.listeners.hasOwnProperty(event)) {
  16709. delete this.listeners[event];
  16710. }
  16711. }
  16712. this.listeners = null;
  16713. this.hammer = null;
  16714. // give all components the opportunity to cleanup
  16715. this.components.forEach(function (component) {
  16716. component.destroy();
  16717. });
  16718. this.body = null;
  16719. };
  16720. /**
  16721. * Set a custom time bar
  16722. * @param {Date} time
  16723. */
  16724. Core.prototype.setCustomTime = function (time) {
  16725. if (!this.customTime) {
  16726. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  16727. }
  16728. this.customTime.setCustomTime(time);
  16729. };
  16730. /**
  16731. * Retrieve the current custom time.
  16732. * @return {Date} customTime
  16733. */
  16734. Core.prototype.getCustomTime = function() {
  16735. if (!this.customTime) {
  16736. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  16737. }
  16738. return this.customTime.getCustomTime();
  16739. };
  16740. /**
  16741. * Get the id's of the currently visible items.
  16742. * @returns {Array} The ids of the visible items
  16743. */
  16744. Core.prototype.getVisibleItems = function() {
  16745. return this.itemSet && this.itemSet.getVisibleItems() || [];
  16746. };
  16747. /**
  16748. * Clear the Core. By Default, items, groups and options are cleared.
  16749. * Example usage:
  16750. *
  16751. * timeline.clear(); // clear items, groups, and options
  16752. * timeline.clear({options: true}); // clear options only
  16753. *
  16754. * @param {Object} [what] Optionally specify what to clear. By default:
  16755. * {items: true, groups: true, options: true}
  16756. */
  16757. Core.prototype.clear = function(what) {
  16758. // clear items
  16759. if (!what || what.items) {
  16760. this.setItems(null);
  16761. }
  16762. // clear groups
  16763. if (!what || what.groups) {
  16764. this.setGroups(null);
  16765. }
  16766. // clear options of timeline and of each of the components
  16767. if (!what || what.options) {
  16768. this.components.forEach(function (component) {
  16769. component.setOptions(component.defaultOptions);
  16770. });
  16771. this.setOptions(this.defaultOptions); // this will also do a redraw
  16772. }
  16773. };
  16774. /**
  16775. * Set Core window such that it fits all items
  16776. */
  16777. Core.prototype.fit = function() {
  16778. // apply the data range as range
  16779. var dataRange = this.getItemRange();
  16780. // add 5% space on both sides
  16781. var start = dataRange.min;
  16782. var end = dataRange.max;
  16783. if (start != null && end != null) {
  16784. var interval = (end.valueOf() - start.valueOf());
  16785. if (interval <= 0) {
  16786. // prevent an empty interval
  16787. interval = 24 * 60 * 60 * 1000; // 1 day
  16788. }
  16789. start = new Date(start.valueOf() - interval * 0.05);
  16790. end = new Date(end.valueOf() + interval * 0.05);
  16791. }
  16792. // skip range set if there is no start and end date
  16793. if (start === null && end === null) {
  16794. return;
  16795. }
  16796. this.range.setRange(start, end);
  16797. };
  16798. /**
  16799. * Set the visible window. Both parameters are optional, you can change only
  16800. * start or only end. Syntax:
  16801. *
  16802. * TimeLine.setWindow(start, end)
  16803. * TimeLine.setWindow(range)
  16804. *
  16805. * Where start and end can be a Date, number, or string, and range is an
  16806. * object with properties start and end.
  16807. *
  16808. * @param {Date | Number | String | Object} [start] Start date of visible window
  16809. * @param {Date | Number | String} [end] End date of visible window
  16810. */
  16811. Core.prototype.setWindow = function(start, end) {
  16812. if (arguments.length == 1) {
  16813. var range = arguments[0];
  16814. this.range.setRange(range.start, range.end);
  16815. }
  16816. else {
  16817. this.range.setRange(start, end);
  16818. }
  16819. };
  16820. /**
  16821. * Get the visible window
  16822. * @return {{start: Date, end: Date}} Visible range
  16823. */
  16824. Core.prototype.getWindow = function() {
  16825. var range = this.range.getRange();
  16826. return {
  16827. start: new Date(range.start),
  16828. end: new Date(range.end)
  16829. };
  16830. };
  16831. /**
  16832. * Force a redraw of the Core. Can be useful to manually redraw when
  16833. * option autoResize=false
  16834. */
  16835. Core.prototype.redraw = function() {
  16836. var resized = false,
  16837. options = this.options,
  16838. props = this.props,
  16839. dom = this.dom;
  16840. if (!dom) return; // when destroyed
  16841. // update class names
  16842. dom.root.className = 'vis timeline root ' + options.orientation;
  16843. // update root width and height options
  16844. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  16845. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  16846. dom.root.style.width = util.option.asSize(options.width, '');
  16847. // calculate border widths
  16848. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  16849. props.border.right = props.border.left;
  16850. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  16851. props.border.bottom = props.border.top;
  16852. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  16853. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  16854. // calculate the heights. If any of the side panels is empty, we set the height to
  16855. // minus the border width, such that the border will be invisible
  16856. props.center.height = dom.center.offsetHeight;
  16857. props.left.height = dom.left.offsetHeight;
  16858. props.right.height = dom.right.offsetHeight;
  16859. props.top.height = dom.top.clientHeight || -props.border.top;
  16860. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  16861. // TODO: compensate borders when any of the panels is empty.
  16862. // apply auto height
  16863. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  16864. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  16865. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  16866. borderRootHeight + props.border.top + props.border.bottom;
  16867. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  16868. // calculate heights of the content panels
  16869. props.root.height = dom.root.offsetHeight;
  16870. props.background.height = props.root.height - borderRootHeight;
  16871. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  16872. borderRootHeight;
  16873. props.centerContainer.height = containerHeight;
  16874. props.leftContainer.height = containerHeight;
  16875. props.rightContainer.height = props.leftContainer.height;
  16876. // calculate the widths of the panels
  16877. props.root.width = dom.root.offsetWidth;
  16878. props.background.width = props.root.width - borderRootWidth;
  16879. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  16880. props.leftContainer.width = props.left.width;
  16881. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  16882. props.rightContainer.width = props.right.width;
  16883. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  16884. props.center.width = centerWidth;
  16885. props.centerContainer.width = centerWidth;
  16886. props.top.width = centerWidth;
  16887. props.bottom.width = centerWidth;
  16888. // resize the panels
  16889. dom.background.style.height = props.background.height + 'px';
  16890. dom.backgroundVertical.style.height = props.background.height + 'px';
  16891. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  16892. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  16893. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  16894. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  16895. dom.background.style.width = props.background.width + 'px';
  16896. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  16897. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  16898. dom.centerContainer.style.width = props.center.width + 'px';
  16899. dom.top.style.width = props.top.width + 'px';
  16900. dom.bottom.style.width = props.bottom.width + 'px';
  16901. // reposition the panels
  16902. dom.background.style.left = '0';
  16903. dom.background.style.top = '0';
  16904. dom.backgroundVertical.style.left = props.left.width + 'px';
  16905. dom.backgroundVertical.style.top = '0';
  16906. dom.backgroundHorizontal.style.left = '0';
  16907. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  16908. dom.centerContainer.style.left = props.left.width + 'px';
  16909. dom.centerContainer.style.top = props.top.height + 'px';
  16910. dom.leftContainer.style.left = '0';
  16911. dom.leftContainer.style.top = props.top.height + 'px';
  16912. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  16913. dom.rightContainer.style.top = props.top.height + 'px';
  16914. dom.top.style.left = props.left.width + 'px';
  16915. dom.top.style.top = '0';
  16916. dom.bottom.style.left = props.left.width + 'px';
  16917. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  16918. // update the scrollTop, feasible range for the offset can be changed
  16919. // when the height of the Core or of the contents of the center changed
  16920. this._updateScrollTop();
  16921. // reposition the scrollable contents
  16922. var offset = this.props.scrollTop;
  16923. if (options.orientation == 'bottom') {
  16924. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  16925. this.props.border.top - this.props.border.bottom, 0);
  16926. }
  16927. dom.center.style.left = '0';
  16928. dom.center.style.top = offset + 'px';
  16929. dom.left.style.left = '0';
  16930. dom.left.style.top = offset + 'px';
  16931. dom.right.style.left = '0';
  16932. dom.right.style.top = offset + 'px';
  16933. // show shadows when vertical scrolling is available
  16934. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  16935. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  16936. dom.shadowTop.style.visibility = visibilityTop;
  16937. dom.shadowBottom.style.visibility = visibilityBottom;
  16938. dom.shadowTopLeft.style.visibility = visibilityTop;
  16939. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  16940. dom.shadowTopRight.style.visibility = visibilityTop;
  16941. dom.shadowBottomRight.style.visibility = visibilityBottom;
  16942. // redraw all components
  16943. this.components.forEach(function (component) {
  16944. resized = component.redraw() || resized;
  16945. });
  16946. if (resized) {
  16947. // keep repainting until all sizes are settled
  16948. this.redraw();
  16949. }
  16950. };
  16951. // TODO: deprecated since version 1.1.0, remove some day
  16952. Core.prototype.repaint = function () {
  16953. throw new Error('Function repaint is deprecated. Use redraw instead.');
  16954. };
  16955. /**
  16956. * Convert a position on screen (pixels) to a datetime
  16957. * @param {int} x Position on the screen in pixels
  16958. * @return {Date} time The datetime the corresponds with given position x
  16959. * @private
  16960. */
  16961. // TODO: move this function to Range
  16962. Core.prototype._toTime = function(x) {
  16963. var conversion = this.range.conversion(this.props.center.width);
  16964. return new Date(x / conversion.scale + conversion.offset);
  16965. };
  16966. /**
  16967. * Convert a position on the global screen (pixels) to a datetime
  16968. * @param {int} x Position on the screen in pixels
  16969. * @return {Date} time The datetime the corresponds with given position x
  16970. * @private
  16971. */
  16972. // TODO: move this function to Range
  16973. Core.prototype._toGlobalTime = function(x) {
  16974. var conversion = this.range.conversion(this.props.root.width);
  16975. return new Date(x / conversion.scale + conversion.offset);
  16976. };
  16977. /**
  16978. * Convert a datetime (Date object) into a position on the screen
  16979. * @param {Date} time A date
  16980. * @return {int} x The position on the screen in pixels which corresponds
  16981. * with the given date.
  16982. * @private
  16983. */
  16984. // TODO: move this function to Range
  16985. Core.prototype._toScreen = function(time) {
  16986. var conversion = this.range.conversion(this.props.center.width);
  16987. return (time.valueOf() - conversion.offset) * conversion.scale;
  16988. };
  16989. /**
  16990. * Convert a datetime (Date object) into a position on the root
  16991. * This is used to get the pixel density estimate for the screen, not the center panel
  16992. * @param {Date} time A date
  16993. * @return {int} x The position on root in pixels which corresponds
  16994. * with the given date.
  16995. * @private
  16996. */
  16997. // TODO: move this function to Range
  16998. Core.prototype._toGlobalScreen = function(time) {
  16999. var conversion = this.range.conversion(this.props.root.width);
  17000. return (time.valueOf() - conversion.offset) * conversion.scale;
  17001. };
  17002. /**
  17003. * Initialize watching when option autoResize is true
  17004. * @private
  17005. */
  17006. Core.prototype._initAutoResize = function () {
  17007. if (this.options.autoResize == true) {
  17008. this._startAutoResize();
  17009. }
  17010. else {
  17011. this._stopAutoResize();
  17012. }
  17013. };
  17014. /**
  17015. * Watch for changes in the size of the container. On resize, the Panel will
  17016. * automatically redraw itself.
  17017. * @private
  17018. */
  17019. Core.prototype._startAutoResize = function () {
  17020. var me = this;
  17021. this._stopAutoResize();
  17022. this._onResize = function() {
  17023. if (me.options.autoResize != true) {
  17024. // stop watching when the option autoResize is changed to false
  17025. me._stopAutoResize();
  17026. return;
  17027. }
  17028. if (me.dom.root) {
  17029. // check whether the frame is resized
  17030. if ((me.dom.root.clientWidth != me.props.lastWidth) ||
  17031. (me.dom.root.clientHeight != me.props.lastHeight)) {
  17032. me.props.lastWidth = me.dom.root.clientWidth;
  17033. me.props.lastHeight = me.dom.root.clientHeight;
  17034. me.emit('change');
  17035. }
  17036. }
  17037. };
  17038. // add event listener to window resize
  17039. util.addEventListener(window, 'resize', this._onResize);
  17040. this.watchTimer = setInterval(this._onResize, 1000);
  17041. };
  17042. /**
  17043. * Stop watching for a resize of the frame.
  17044. * @private
  17045. */
  17046. Core.prototype._stopAutoResize = function () {
  17047. if (this.watchTimer) {
  17048. clearInterval(this.watchTimer);
  17049. this.watchTimer = undefined;
  17050. }
  17051. // remove event listener on window.resize
  17052. util.removeEventListener(window, 'resize', this._onResize);
  17053. this._onResize = null;
  17054. };
  17055. /**
  17056. * Start moving the timeline vertically
  17057. * @param {Event} event
  17058. * @private
  17059. */
  17060. Core.prototype._onTouch = function (event) {
  17061. this.touch.allowDragging = true;
  17062. };
  17063. /**
  17064. * Start moving the timeline vertically
  17065. * @param {Event} event
  17066. * @private
  17067. */
  17068. Core.prototype._onPinch = function (event) {
  17069. this.touch.allowDragging = false;
  17070. };
  17071. /**
  17072. * Start moving the timeline vertically
  17073. * @param {Event} event
  17074. * @private
  17075. */
  17076. Core.prototype._onDragStart = function (event) {
  17077. this.touch.initialScrollTop = this.props.scrollTop;
  17078. };
  17079. /**
  17080. * Move the timeline vertically
  17081. * @param {Event} event
  17082. * @private
  17083. */
  17084. Core.prototype._onDrag = function (event) {
  17085. // refuse to drag when we where pinching to prevent the timeline make a jump
  17086. // when releasing the fingers in opposite order from the touch screen
  17087. if (!this.touch.allowDragging) return;
  17088. var delta = event.gesture.deltaY;
  17089. var oldScrollTop = this._getScrollTop();
  17090. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  17091. if (newScrollTop != oldScrollTop) {
  17092. this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already
  17093. }
  17094. };
  17095. /**
  17096. * Apply a scrollTop
  17097. * @param {Number} scrollTop
  17098. * @returns {Number} scrollTop Returns the applied scrollTop
  17099. * @private
  17100. */
  17101. Core.prototype._setScrollTop = function (scrollTop) {
  17102. this.props.scrollTop = scrollTop;
  17103. this._updateScrollTop();
  17104. return this.props.scrollTop;
  17105. };
  17106. /**
  17107. * Update the current scrollTop when the height of the containers has been changed
  17108. * @returns {Number} scrollTop Returns the applied scrollTop
  17109. * @private
  17110. */
  17111. Core.prototype._updateScrollTop = function () {
  17112. // recalculate the scrollTopMin
  17113. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  17114. if (scrollTopMin != this.props.scrollTopMin) {
  17115. // in case of bottom orientation, change the scrollTop such that the contents
  17116. // do not move relative to the time axis at the bottom
  17117. if (this.options.orientation == 'bottom') {
  17118. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  17119. }
  17120. this.props.scrollTopMin = scrollTopMin;
  17121. }
  17122. // limit the scrollTop to the feasible scroll range
  17123. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  17124. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  17125. return this.props.scrollTop;
  17126. };
  17127. /**
  17128. * Get the current scrollTop
  17129. * @returns {number} scrollTop
  17130. * @private
  17131. */
  17132. Core.prototype._getScrollTop = function () {
  17133. return this.props.scrollTop;
  17134. };
  17135. module.exports = Core;
  17136. /***/ },
  17137. /* 43 */
  17138. /***/ function(module, exports, __webpack_require__) {
  17139. var Hammer = __webpack_require__(41);
  17140. /**
  17141. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  17142. * @param {Element} element
  17143. * @param {Event} event
  17144. */
  17145. exports.fakeGesture = function(element, event) {
  17146. var eventType = null;
  17147. // for hammer.js 1.0.5
  17148. // var gesture = Hammer.event.collectEventData(this, eventType, event);
  17149. // for hammer.js 1.0.6+
  17150. var touches = Hammer.event.getTouchList(event, eventType);
  17151. var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  17152. // on IE in standards mode, no touches are recognized by hammer.js,
  17153. // resulting in NaN values for center.pageX and center.pageY
  17154. if (isNaN(gesture.center.pageX)) {
  17155. gesture.center.pageX = event.pageX;
  17156. }
  17157. if (isNaN(gesture.center.pageY)) {
  17158. gesture.center.pageY = event.pageY;
  17159. }
  17160. return gesture;
  17161. };
  17162. /***/ },
  17163. /* 44 */
  17164. /***/ function(module, exports, __webpack_require__) {
  17165. /**
  17166. * Canvas shapes used by Network
  17167. */
  17168. if (typeof CanvasRenderingContext2D !== 'undefined') {
  17169. /**
  17170. * Draw a circle shape
  17171. */
  17172. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  17173. this.beginPath();
  17174. this.arc(x, y, r, 0, 2*Math.PI, false);
  17175. };
  17176. /**
  17177. * Draw a square shape
  17178. * @param {Number} x horizontal center
  17179. * @param {Number} y vertical center
  17180. * @param {Number} r size, width and height of the square
  17181. */
  17182. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  17183. this.beginPath();
  17184. this.rect(x - r, y - r, r * 2, r * 2);
  17185. };
  17186. /**
  17187. * Draw a triangle shape
  17188. * @param {Number} x horizontal center
  17189. * @param {Number} y vertical center
  17190. * @param {Number} r radius, half the length of the sides of the triangle
  17191. */
  17192. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  17193. // http://en.wikipedia.org/wiki/Equilateral_triangle
  17194. this.beginPath();
  17195. var s = r * 2;
  17196. var s2 = s / 2;
  17197. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  17198. var h = Math.sqrt(s * s - s2 * s2); // height
  17199. this.moveTo(x, y - (h - ir));
  17200. this.lineTo(x + s2, y + ir);
  17201. this.lineTo(x - s2, y + ir);
  17202. this.lineTo(x, y - (h - ir));
  17203. this.closePath();
  17204. };
  17205. /**
  17206. * Draw a triangle shape in downward orientation
  17207. * @param {Number} x horizontal center
  17208. * @param {Number} y vertical center
  17209. * @param {Number} r radius
  17210. */
  17211. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  17212. // http://en.wikipedia.org/wiki/Equilateral_triangle
  17213. this.beginPath();
  17214. var s = r * 2;
  17215. var s2 = s / 2;
  17216. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  17217. var h = Math.sqrt(s * s - s2 * s2); // height
  17218. this.moveTo(x, y + (h - ir));
  17219. this.lineTo(x + s2, y - ir);
  17220. this.lineTo(x - s2, y - ir);
  17221. this.lineTo(x, y + (h - ir));
  17222. this.closePath();
  17223. };
  17224. /**
  17225. * Draw a star shape, a star with 5 points
  17226. * @param {Number} x horizontal center
  17227. * @param {Number} y vertical center
  17228. * @param {Number} r radius, half the length of the sides of the triangle
  17229. */
  17230. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  17231. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  17232. this.beginPath();
  17233. for (var n = 0; n < 10; n++) {
  17234. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  17235. this.lineTo(
  17236. x + radius * Math.sin(n * 2 * Math.PI / 10),
  17237. y - radius * Math.cos(n * 2 * Math.PI / 10)
  17238. );
  17239. }
  17240. this.closePath();
  17241. };
  17242. /**
  17243. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  17244. */
  17245. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  17246. var r2d = Math.PI/180;
  17247. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  17248. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  17249. this.beginPath();
  17250. this.moveTo(x+r,y);
  17251. this.lineTo(x+w-r,y);
  17252. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  17253. this.lineTo(x+w,y+h-r);
  17254. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  17255. this.lineTo(x+r,y+h);
  17256. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  17257. this.lineTo(x,y+r);
  17258. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  17259. };
  17260. /**
  17261. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  17262. */
  17263. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  17264. var kappa = .5522848,
  17265. ox = (w / 2) * kappa, // control point offset horizontal
  17266. oy = (h / 2) * kappa, // control point offset vertical
  17267. xe = x + w, // x-end
  17268. ye = y + h, // y-end
  17269. xm = x + w / 2, // x-middle
  17270. ym = y + h / 2; // y-middle
  17271. this.beginPath();
  17272. this.moveTo(x, ym);
  17273. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  17274. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  17275. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  17276. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  17277. };
  17278. /**
  17279. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  17280. */
  17281. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  17282. var f = 1/3;
  17283. var wEllipse = w;
  17284. var hEllipse = h * f;
  17285. var kappa = .5522848,
  17286. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  17287. oy = (hEllipse / 2) * kappa, // control point offset vertical
  17288. xe = x + wEllipse, // x-end
  17289. ye = y + hEllipse, // y-end
  17290. xm = x + wEllipse / 2, // x-middle
  17291. ym = y + hEllipse / 2, // y-middle
  17292. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  17293. yeb = y + h; // y-end, bottom ellipse
  17294. this.beginPath();
  17295. this.moveTo(xe, ym);
  17296. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  17297. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  17298. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  17299. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  17300. this.lineTo(xe, ymb);
  17301. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  17302. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  17303. this.lineTo(x, ym);
  17304. };
  17305. /**
  17306. * Draw an arrow point (no line)
  17307. */
  17308. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  17309. // tail
  17310. var xt = x - length * Math.cos(angle);
  17311. var yt = y - length * Math.sin(angle);
  17312. // inner tail
  17313. // TODO: allow to customize different shapes
  17314. var xi = x - length * 0.9 * Math.cos(angle);
  17315. var yi = y - length * 0.9 * Math.sin(angle);
  17316. // left
  17317. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  17318. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  17319. // right
  17320. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  17321. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  17322. this.beginPath();
  17323. this.moveTo(x, y);
  17324. this.lineTo(xl, yl);
  17325. this.lineTo(xi, yi);
  17326. this.lineTo(xr, yr);
  17327. this.closePath();
  17328. };
  17329. /**
  17330. * Sets up the dashedLine functionality for drawing
  17331. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  17332. * @author David Jordan
  17333. * @date 2012-08-08
  17334. */
  17335. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  17336. if (!dashArray) dashArray=[10,5];
  17337. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  17338. var dashCount = dashArray.length;
  17339. this.moveTo(x, y);
  17340. var dx = (x2-x), dy = (y2-y);
  17341. var slope = dy/dx;
  17342. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  17343. var dashIndex=0, draw=true;
  17344. while (distRemaining>=0.1){
  17345. var dashLength = dashArray[dashIndex++%dashCount];
  17346. if (dashLength > distRemaining) dashLength = distRemaining;
  17347. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  17348. if (dx<0) xStep = -xStep;
  17349. x += xStep;
  17350. y += slope*xStep;
  17351. this[draw ? 'lineTo' : 'moveTo'](x,y);
  17352. distRemaining -= dashLength;
  17353. draw = !draw;
  17354. }
  17355. };
  17356. // TODO: add diamond shape
  17357. }
  17358. /***/ },
  17359. /* 45 */
  17360. /***/ function(module, exports, __webpack_require__) {
  17361. var PhysicsMixin = __webpack_require__(56);
  17362. var ClusterMixin = __webpack_require__(50);
  17363. var SectorsMixin = __webpack_require__(51);
  17364. var SelectionMixin = __webpack_require__(52);
  17365. var ManipulationMixin = __webpack_require__(53);
  17366. var NavigationMixin = __webpack_require__(54);
  17367. var HierarchicalLayoutMixin = __webpack_require__(55);
  17368. /**
  17369. * Load a mixin into the network object
  17370. *
  17371. * @param {Object} sourceVariable | this object has to contain functions.
  17372. * @private
  17373. */
  17374. exports._loadMixin = function (sourceVariable) {
  17375. for (var mixinFunction in sourceVariable) {
  17376. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  17377. this[mixinFunction] = sourceVariable[mixinFunction];
  17378. }
  17379. }
  17380. };
  17381. /**
  17382. * removes a mixin from the network object.
  17383. *
  17384. * @param {Object} sourceVariable | this object has to contain functions.
  17385. * @private
  17386. */
  17387. exports._clearMixin = function (sourceVariable) {
  17388. for (var mixinFunction in sourceVariable) {
  17389. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  17390. this[mixinFunction] = undefined;
  17391. }
  17392. }
  17393. };
  17394. /**
  17395. * Mixin the physics system and initialize the parameters required.
  17396. *
  17397. * @private
  17398. */
  17399. exports._loadPhysicsSystem = function () {
  17400. this._loadMixin(PhysicsMixin);
  17401. this._loadSelectedForceSolver();
  17402. if (this.constants.configurePhysics == true) {
  17403. this._loadPhysicsConfiguration();
  17404. }
  17405. };
  17406. /**
  17407. * Mixin the cluster system and initialize the parameters required.
  17408. *
  17409. * @private
  17410. */
  17411. exports._loadClusterSystem = function () {
  17412. this.clusterSession = 0;
  17413. this.hubThreshold = 5;
  17414. this._loadMixin(ClusterMixin);
  17415. };
  17416. /**
  17417. * Mixin the sector system and initialize the parameters required
  17418. *
  17419. * @private
  17420. */
  17421. exports._loadSectorSystem = function () {
  17422. this.sectors = {};
  17423. this.activeSector = ["default"];
  17424. this.sectors["active"] = {};
  17425. this.sectors["active"]["default"] = {"nodes": {},
  17426. "edges": {},
  17427. "nodeIndices": [],
  17428. "formationScale": 1.0,
  17429. "drawingNode": undefined };
  17430. this.sectors["frozen"] = {};
  17431. this.sectors["support"] = {"nodes": {},
  17432. "edges": {},
  17433. "nodeIndices": [],
  17434. "formationScale": 1.0,
  17435. "drawingNode": undefined };
  17436. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  17437. this._loadMixin(SectorsMixin);
  17438. };
  17439. /**
  17440. * Mixin the selection system and initialize the parameters required
  17441. *
  17442. * @private
  17443. */
  17444. exports._loadSelectionSystem = function () {
  17445. this.selectionObj = {nodes: {}, edges: {}};
  17446. this._loadMixin(SelectionMixin);
  17447. };
  17448. /**
  17449. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  17450. *
  17451. * @private
  17452. */
  17453. exports._loadManipulationSystem = function () {
  17454. // reset global variables -- these are used by the selection of nodes and edges.
  17455. this.blockConnectingEdgeSelection = false;
  17456. this.forceAppendSelection = false;
  17457. if (this.constants.dataManipulation.enabled == true) {
  17458. // load the manipulator HTML elements. All styling done in css.
  17459. if (this.manipulationDiv === undefined) {
  17460. this.manipulationDiv = document.createElement('div');
  17461. this.manipulationDiv.className = 'network-manipulationDiv';
  17462. this.manipulationDiv.id = 'network-manipulationDiv';
  17463. if (this.editMode == true) {
  17464. this.manipulationDiv.style.display = "block";
  17465. }
  17466. else {
  17467. this.manipulationDiv.style.display = "none";
  17468. }
  17469. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  17470. }
  17471. if (this.editModeDiv === undefined) {
  17472. this.editModeDiv = document.createElement('div');
  17473. this.editModeDiv.className = 'network-manipulation-editMode';
  17474. this.editModeDiv.id = 'network-manipulation-editMode';
  17475. if (this.editMode == true) {
  17476. this.editModeDiv.style.display = "none";
  17477. }
  17478. else {
  17479. this.editModeDiv.style.display = "block";
  17480. }
  17481. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  17482. }
  17483. if (this.closeDiv === undefined) {
  17484. this.closeDiv = document.createElement('div');
  17485. this.closeDiv.className = 'network-manipulation-closeDiv';
  17486. this.closeDiv.id = 'network-manipulation-closeDiv';
  17487. this.closeDiv.style.display = this.manipulationDiv.style.display;
  17488. this.containerElement.insertBefore(this.closeDiv, this.frame);
  17489. }
  17490. // load the manipulation functions
  17491. this._loadMixin(ManipulationMixin);
  17492. // create the manipulator toolbar
  17493. this._createManipulatorBar();
  17494. }
  17495. else {
  17496. if (this.manipulationDiv !== undefined) {
  17497. // removes all the bindings and overloads
  17498. this._createManipulatorBar();
  17499. // remove the manipulation divs
  17500. this.containerElement.removeChild(this.manipulationDiv);
  17501. this.containerElement.removeChild(this.editModeDiv);
  17502. this.containerElement.removeChild(this.closeDiv);
  17503. this.manipulationDiv = undefined;
  17504. this.editModeDiv = undefined;
  17505. this.closeDiv = undefined;
  17506. // remove the mixin functions
  17507. this._clearMixin(ManipulationMixin);
  17508. }
  17509. }
  17510. };
  17511. /**
  17512. * Mixin the navigation (User Interface) system and initialize the parameters required
  17513. *
  17514. * @private
  17515. */
  17516. exports._loadNavigationControls = function () {
  17517. this._loadMixin(NavigationMixin);
  17518. // the clean function removes the button divs, this is done to remove the bindings.
  17519. this._cleanNavigation();
  17520. if (this.constants.navigation.enabled == true) {
  17521. this._loadNavigationElements();
  17522. }
  17523. };
  17524. /**
  17525. * Mixin the hierarchical layout system.
  17526. *
  17527. * @private
  17528. */
  17529. exports._loadHierarchySystem = function () {
  17530. this._loadMixin(HierarchicalLayoutMixin);
  17531. };
  17532. /***/ },
  17533. /* 46 */
  17534. /***/ function(module, exports, __webpack_require__) {
  17535. /**
  17536. * Expose `Emitter`.
  17537. */
  17538. module.exports = Emitter;
  17539. /**
  17540. * Initialize a new `Emitter`.
  17541. *
  17542. * @api public
  17543. */
  17544. function Emitter(obj) {
  17545. if (obj) return mixin(obj);
  17546. };
  17547. /**
  17548. * Mixin the emitter properties.
  17549. *
  17550. * @param {Object} obj
  17551. * @return {Object}
  17552. * @api private
  17553. */
  17554. function mixin(obj) {
  17555. for (var key in Emitter.prototype) {
  17556. obj[key] = Emitter.prototype[key];
  17557. }
  17558. return obj;
  17559. }
  17560. /**
  17561. * Listen on the given `event` with `fn`.
  17562. *
  17563. * @param {String} event
  17564. * @param {Function} fn
  17565. * @return {Emitter}
  17566. * @api public
  17567. */
  17568. Emitter.prototype.on =
  17569. Emitter.prototype.addEventListener = function(event, fn){
  17570. this._callbacks = this._callbacks || {};
  17571. (this._callbacks[event] = this._callbacks[event] || [])
  17572. .push(fn);
  17573. return this;
  17574. };
  17575. /**
  17576. * Adds an `event` listener that will be invoked a single
  17577. * time then automatically removed.
  17578. *
  17579. * @param {String} event
  17580. * @param {Function} fn
  17581. * @return {Emitter}
  17582. * @api public
  17583. */
  17584. Emitter.prototype.once = function(event, fn){
  17585. var self = this;
  17586. this._callbacks = this._callbacks || {};
  17587. function on() {
  17588. self.off(event, on);
  17589. fn.apply(this, arguments);
  17590. }
  17591. on.fn = fn;
  17592. this.on(event, on);
  17593. return this;
  17594. };
  17595. /**
  17596. * Remove the given callback for `event` or all
  17597. * registered callbacks.
  17598. *
  17599. * @param {String} event
  17600. * @param {Function} fn
  17601. * @return {Emitter}
  17602. * @api public
  17603. */
  17604. Emitter.prototype.off =
  17605. Emitter.prototype.removeListener =
  17606. Emitter.prototype.removeAllListeners =
  17607. Emitter.prototype.removeEventListener = function(event, fn){
  17608. this._callbacks = this._callbacks || {};
  17609. // all
  17610. if (0 == arguments.length) {
  17611. this._callbacks = {};
  17612. return this;
  17613. }
  17614. // specific event
  17615. var callbacks = this._callbacks[event];
  17616. if (!callbacks) return this;
  17617. // remove all handlers
  17618. if (1 == arguments.length) {
  17619. delete this._callbacks[event];
  17620. return this;
  17621. }
  17622. // remove specific handler
  17623. var cb;
  17624. for (var i = 0; i < callbacks.length; i++) {
  17625. cb = callbacks[i];
  17626. if (cb === fn || cb.fn === fn) {
  17627. callbacks.splice(i, 1);
  17628. break;
  17629. }
  17630. }
  17631. return this;
  17632. };
  17633. /**
  17634. * Emit `event` with the given args.
  17635. *
  17636. * @param {String} event
  17637. * @param {Mixed} ...
  17638. * @return {Emitter}
  17639. */
  17640. Emitter.prototype.emit = function(event){
  17641. this._callbacks = this._callbacks || {};
  17642. var args = [].slice.call(arguments, 1)
  17643. , callbacks = this._callbacks[event];
  17644. if (callbacks) {
  17645. callbacks = callbacks.slice(0);
  17646. for (var i = 0, len = callbacks.length; i < len; ++i) {
  17647. callbacks[i].apply(this, args);
  17648. }
  17649. }
  17650. return this;
  17651. };
  17652. /**
  17653. * Return array of callbacks for `event`.
  17654. *
  17655. * @param {String} event
  17656. * @return {Array}
  17657. * @api public
  17658. */
  17659. Emitter.prototype.listeners = function(event){
  17660. this._callbacks = this._callbacks || {};
  17661. return this._callbacks[event] || [];
  17662. };
  17663. /**
  17664. * Check if this emitter has `event` handlers.
  17665. *
  17666. * @param {String} event
  17667. * @return {Boolean}
  17668. * @api public
  17669. */
  17670. Emitter.prototype.hasListeners = function(event){
  17671. return !! this.listeners(event).length;
  17672. };
  17673. /***/ },
  17674. /* 47 */
  17675. /***/ function(module, exports, __webpack_require__) {
  17676. /**
  17677. * Copyright 2012 Craig Campbell
  17678. *
  17679. * Licensed under the Apache License, Version 2.0 (the "License");
  17680. * you may not use this file except in compliance with the License.
  17681. * You may obtain a copy of the License at
  17682. *
  17683. * http://www.apache.org/licenses/LICENSE-2.0
  17684. *
  17685. * Unless required by applicable law or agreed to in writing, software
  17686. * distributed under the License is distributed on an "AS IS" BASIS,
  17687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17688. * See the License for the specific language governing permissions and
  17689. * limitations under the License.
  17690. *
  17691. * Mousetrap is a simple keyboard shortcut library for Javascript with
  17692. * no external dependencies
  17693. *
  17694. * @version 1.1.2
  17695. * @url craig.is/killing/mice
  17696. */
  17697. /**
  17698. * mapping of special keycodes to their corresponding keys
  17699. *
  17700. * everything in this dictionary cannot use keypress events
  17701. * so it has to be here to map to the correct keycodes for
  17702. * keyup/keydown events
  17703. *
  17704. * @type {Object}
  17705. */
  17706. var _MAP = {
  17707. 8: 'backspace',
  17708. 9: 'tab',
  17709. 13: 'enter',
  17710. 16: 'shift',
  17711. 17: 'ctrl',
  17712. 18: 'alt',
  17713. 20: 'capslock',
  17714. 27: 'esc',
  17715. 32: 'space',
  17716. 33: 'pageup',
  17717. 34: 'pagedown',
  17718. 35: 'end',
  17719. 36: 'home',
  17720. 37: 'left',
  17721. 38: 'up',
  17722. 39: 'right',
  17723. 40: 'down',
  17724. 45: 'ins',
  17725. 46: 'del',
  17726. 91: 'meta',
  17727. 93: 'meta',
  17728. 224: 'meta'
  17729. },
  17730. /**
  17731. * mapping for special characters so they can support
  17732. *
  17733. * this dictionary is only used incase you want to bind a
  17734. * keyup or keydown event to one of these keys
  17735. *
  17736. * @type {Object}
  17737. */
  17738. _KEYCODE_MAP = {
  17739. 106: '*',
  17740. 107: '+',
  17741. 109: '-',
  17742. 110: '.',
  17743. 111 : '/',
  17744. 186: ';',
  17745. 187: '=',
  17746. 188: ',',
  17747. 189: '-',
  17748. 190: '.',
  17749. 191: '/',
  17750. 192: '`',
  17751. 219: '[',
  17752. 220: '\\',
  17753. 221: ']',
  17754. 222: '\''
  17755. },
  17756. /**
  17757. * this is a mapping of keys that require shift on a US keypad
  17758. * back to the non shift equivelents
  17759. *
  17760. * this is so you can use keyup events with these keys
  17761. *
  17762. * note that this will only work reliably on US keyboards
  17763. *
  17764. * @type {Object}
  17765. */
  17766. _SHIFT_MAP = {
  17767. '~': '`',
  17768. '!': '1',
  17769. '@': '2',
  17770. '#': '3',
  17771. '$': '4',
  17772. '%': '5',
  17773. '^': '6',
  17774. '&': '7',
  17775. '*': '8',
  17776. '(': '9',
  17777. ')': '0',
  17778. '_': '-',
  17779. '+': '=',
  17780. ':': ';',
  17781. '\"': '\'',
  17782. '<': ',',
  17783. '>': '.',
  17784. '?': '/',
  17785. '|': '\\'
  17786. },
  17787. /**
  17788. * this is a list of special strings you can use to map
  17789. * to modifier keys when you specify your keyboard shortcuts
  17790. *
  17791. * @type {Object}
  17792. */
  17793. _SPECIAL_ALIASES = {
  17794. 'option': 'alt',
  17795. 'command': 'meta',
  17796. 'return': 'enter',
  17797. 'escape': 'esc'
  17798. },
  17799. /**
  17800. * variable to store the flipped version of _MAP from above
  17801. * needed to check if we should use keypress or not when no action
  17802. * is specified
  17803. *
  17804. * @type {Object|undefined}
  17805. */
  17806. _REVERSE_MAP,
  17807. /**
  17808. * a list of all the callbacks setup via Mousetrap.bind()
  17809. *
  17810. * @type {Object}
  17811. */
  17812. _callbacks = {},
  17813. /**
  17814. * direct map of string combinations to callbacks used for trigger()
  17815. *
  17816. * @type {Object}
  17817. */
  17818. _direct_map = {},
  17819. /**
  17820. * keeps track of what level each sequence is at since multiple
  17821. * sequences can start out with the same sequence
  17822. *
  17823. * @type {Object}
  17824. */
  17825. _sequence_levels = {},
  17826. /**
  17827. * variable to store the setTimeout call
  17828. *
  17829. * @type {null|number}
  17830. */
  17831. _reset_timer,
  17832. /**
  17833. * temporary state where we will ignore the next keyup
  17834. *
  17835. * @type {boolean|string}
  17836. */
  17837. _ignore_next_keyup = false,
  17838. /**
  17839. * are we currently inside of a sequence?
  17840. * type of action ("keyup" or "keydown" or "keypress") or false
  17841. *
  17842. * @type {boolean|string}
  17843. */
  17844. _inside_sequence = false;
  17845. /**
  17846. * loop through the f keys, f1 to f19 and add them to the map
  17847. * programatically
  17848. */
  17849. for (var i = 1; i < 20; ++i) {
  17850. _MAP[111 + i] = 'f' + i;
  17851. }
  17852. /**
  17853. * loop through to map numbers on the numeric keypad
  17854. */
  17855. for (i = 0; i <= 9; ++i) {
  17856. _MAP[i + 96] = i;
  17857. }
  17858. /**
  17859. * cross browser add event method
  17860. *
  17861. * @param {Element|HTMLDocument} object
  17862. * @param {string} type
  17863. * @param {Function} callback
  17864. * @returns void
  17865. */
  17866. function _addEvent(object, type, callback) {
  17867. if (object.addEventListener) {
  17868. return object.addEventListener(type, callback, false);
  17869. }
  17870. object.attachEvent('on' + type, callback);
  17871. }
  17872. /**
  17873. * takes the event and returns the key character
  17874. *
  17875. * @param {Event} e
  17876. * @return {string}
  17877. */
  17878. function _characterFromEvent(e) {
  17879. // for keypress events we should return the character as is
  17880. if (e.type == 'keypress') {
  17881. return String.fromCharCode(e.which);
  17882. }
  17883. // for non keypress events the special maps are needed
  17884. if (_MAP[e.which]) {
  17885. return _MAP[e.which];
  17886. }
  17887. if (_KEYCODE_MAP[e.which]) {
  17888. return _KEYCODE_MAP[e.which];
  17889. }
  17890. // if it is not in the special map
  17891. return String.fromCharCode(e.which).toLowerCase();
  17892. }
  17893. /**
  17894. * should we stop this event before firing off callbacks
  17895. *
  17896. * @param {Event} e
  17897. * @return {boolean}
  17898. */
  17899. function _stop(e) {
  17900. var element = e.target || e.srcElement,
  17901. tag_name = element.tagName;
  17902. // if the element has the class "mousetrap" then no need to stop
  17903. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  17904. return false;
  17905. }
  17906. // stop for input, select, and textarea
  17907. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  17908. }
  17909. /**
  17910. * checks if two arrays are equal
  17911. *
  17912. * @param {Array} modifiers1
  17913. * @param {Array} modifiers2
  17914. * @returns {boolean}
  17915. */
  17916. function _modifiersMatch(modifiers1, modifiers2) {
  17917. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  17918. }
  17919. /**
  17920. * resets all sequence counters except for the ones passed in
  17921. *
  17922. * @param {Object} do_not_reset
  17923. * @returns void
  17924. */
  17925. function _resetSequences(do_not_reset) {
  17926. do_not_reset = do_not_reset || {};
  17927. var active_sequences = false,
  17928. key;
  17929. for (key in _sequence_levels) {
  17930. if (do_not_reset[key]) {
  17931. active_sequences = true;
  17932. continue;
  17933. }
  17934. _sequence_levels[key] = 0;
  17935. }
  17936. if (!active_sequences) {
  17937. _inside_sequence = false;
  17938. }
  17939. }
  17940. /**
  17941. * finds all callbacks that match based on the keycode, modifiers,
  17942. * and action
  17943. *
  17944. * @param {string} character
  17945. * @param {Array} modifiers
  17946. * @param {string} action
  17947. * @param {boolean=} remove - should we remove any matches
  17948. * @param {string=} combination
  17949. * @returns {Array}
  17950. */
  17951. function _getMatches(character, modifiers, action, remove, combination) {
  17952. var i,
  17953. callback,
  17954. matches = [];
  17955. // if there are no events related to this keycode
  17956. if (!_callbacks[character]) {
  17957. return [];
  17958. }
  17959. // if a modifier key is coming up on its own we should allow it
  17960. if (action == 'keyup' && _isModifier(character)) {
  17961. modifiers = [character];
  17962. }
  17963. // loop through all callbacks for the key that was pressed
  17964. // and see if any of them match
  17965. for (i = 0; i < _callbacks[character].length; ++i) {
  17966. callback = _callbacks[character][i];
  17967. // if this is a sequence but it is not at the right level
  17968. // then move onto the next match
  17969. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  17970. continue;
  17971. }
  17972. // if the action we are looking for doesn't match the action we got
  17973. // then we should keep going
  17974. if (action != callback.action) {
  17975. continue;
  17976. }
  17977. // if this is a keypress event that means that we need to only
  17978. // look at the character, otherwise check the modifiers as
  17979. // well
  17980. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  17981. // remove is used so if you change your mind and call bind a
  17982. // second time with a new function the first one is overwritten
  17983. if (remove && callback.combo == combination) {
  17984. _callbacks[character].splice(i, 1);
  17985. }
  17986. matches.push(callback);
  17987. }
  17988. }
  17989. return matches;
  17990. }
  17991. /**
  17992. * takes a key event and figures out what the modifiers are
  17993. *
  17994. * @param {Event} e
  17995. * @returns {Array}
  17996. */
  17997. function _eventModifiers(e) {
  17998. var modifiers = [];
  17999. if (e.shiftKey) {
  18000. modifiers.push('shift');
  18001. }
  18002. if (e.altKey) {
  18003. modifiers.push('alt');
  18004. }
  18005. if (e.ctrlKey) {
  18006. modifiers.push('ctrl');
  18007. }
  18008. if (e.metaKey) {
  18009. modifiers.push('meta');
  18010. }
  18011. return modifiers;
  18012. }
  18013. /**
  18014. * actually calls the callback function
  18015. *
  18016. * if your callback function returns false this will use the jquery
  18017. * convention - prevent default and stop propogation on the event
  18018. *
  18019. * @param {Function} callback
  18020. * @param {Event} e
  18021. * @returns void
  18022. */
  18023. function _fireCallback(callback, e) {
  18024. if (callback(e) === false) {
  18025. if (e.preventDefault) {
  18026. e.preventDefault();
  18027. }
  18028. if (e.stopPropagation) {
  18029. e.stopPropagation();
  18030. }
  18031. e.returnValue = false;
  18032. e.cancelBubble = true;
  18033. }
  18034. }
  18035. /**
  18036. * handles a character key event
  18037. *
  18038. * @param {string} character
  18039. * @param {Event} e
  18040. * @returns void
  18041. */
  18042. function _handleCharacter(character, e) {
  18043. // if this event should not happen stop here
  18044. if (_stop(e)) {
  18045. return;
  18046. }
  18047. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  18048. i,
  18049. do_not_reset = {},
  18050. processed_sequence_callback = false;
  18051. // loop through matching callbacks for this key event
  18052. for (i = 0; i < callbacks.length; ++i) {
  18053. // fire for all sequence callbacks
  18054. // this is because if for example you have multiple sequences
  18055. // bound such as "g i" and "g t" they both need to fire the
  18056. // callback for matching g cause otherwise you can only ever
  18057. // match the first one
  18058. if (callbacks[i].seq) {
  18059. processed_sequence_callback = true;
  18060. // keep a list of which sequences were matches for later
  18061. do_not_reset[callbacks[i].seq] = 1;
  18062. _fireCallback(callbacks[i].callback, e);
  18063. continue;
  18064. }
  18065. // if there were no sequence matches but we are still here
  18066. // that means this is a regular match so we should fire that
  18067. if (!processed_sequence_callback && !_inside_sequence) {
  18068. _fireCallback(callbacks[i].callback, e);
  18069. }
  18070. }
  18071. // if you are inside of a sequence and the key you are pressing
  18072. // is not a modifier key then we should reset all sequences
  18073. // that were not matched by this key event
  18074. if (e.type == _inside_sequence && !_isModifier(character)) {
  18075. _resetSequences(do_not_reset);
  18076. }
  18077. }
  18078. /**
  18079. * handles a keydown event
  18080. *
  18081. * @param {Event} e
  18082. * @returns void
  18083. */
  18084. function _handleKey(e) {
  18085. // normalize e.which for key events
  18086. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  18087. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  18088. var character = _characterFromEvent(e);
  18089. // no character found then stop
  18090. if (!character) {
  18091. return;
  18092. }
  18093. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  18094. _ignore_next_keyup = false;
  18095. return;
  18096. }
  18097. _handleCharacter(character, e);
  18098. }
  18099. /**
  18100. * determines if the keycode specified is a modifier key or not
  18101. *
  18102. * @param {string} key
  18103. * @returns {boolean}
  18104. */
  18105. function _isModifier(key) {
  18106. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  18107. }
  18108. /**
  18109. * called to set a 1 second timeout on the specified sequence
  18110. *
  18111. * this is so after each key press in the sequence you have 1 second
  18112. * to press the next key before you have to start over
  18113. *
  18114. * @returns void
  18115. */
  18116. function _resetSequenceTimer() {
  18117. clearTimeout(_reset_timer);
  18118. _reset_timer = setTimeout(_resetSequences, 1000);
  18119. }
  18120. /**
  18121. * reverses the map lookup so that we can look for specific keys
  18122. * to see what can and can't use keypress
  18123. *
  18124. * @return {Object}
  18125. */
  18126. function _getReverseMap() {
  18127. if (!_REVERSE_MAP) {
  18128. _REVERSE_MAP = {};
  18129. for (var key in _MAP) {
  18130. // pull out the numeric keypad from here cause keypress should
  18131. // be able to detect the keys from the character
  18132. if (key > 95 && key < 112) {
  18133. continue;
  18134. }
  18135. if (_MAP.hasOwnProperty(key)) {
  18136. _REVERSE_MAP[_MAP[key]] = key;
  18137. }
  18138. }
  18139. }
  18140. return _REVERSE_MAP;
  18141. }
  18142. /**
  18143. * picks the best action based on the key combination
  18144. *
  18145. * @param {string} key - character for key
  18146. * @param {Array} modifiers
  18147. * @param {string=} action passed in
  18148. */
  18149. function _pickBestAction(key, modifiers, action) {
  18150. // if no action was picked in we should try to pick the one
  18151. // that we think would work best for this key
  18152. if (!action) {
  18153. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  18154. }
  18155. // modifier keys don't work as expected with keypress,
  18156. // switch to keydown
  18157. if (action == 'keypress' && modifiers.length) {
  18158. action = 'keydown';
  18159. }
  18160. return action;
  18161. }
  18162. /**
  18163. * binds a key sequence to an event
  18164. *
  18165. * @param {string} combo - combo specified in bind call
  18166. * @param {Array} keys
  18167. * @param {Function} callback
  18168. * @param {string=} action
  18169. * @returns void
  18170. */
  18171. function _bindSequence(combo, keys, callback, action) {
  18172. // start off by adding a sequence level record for this combination
  18173. // and setting the level to 0
  18174. _sequence_levels[combo] = 0;
  18175. // if there is no action pick the best one for the first key
  18176. // in the sequence
  18177. if (!action) {
  18178. action = _pickBestAction(keys[0], []);
  18179. }
  18180. /**
  18181. * callback to increase the sequence level for this sequence and reset
  18182. * all other sequences that were active
  18183. *
  18184. * @param {Event} e
  18185. * @returns void
  18186. */
  18187. var _increaseSequence = function(e) {
  18188. _inside_sequence = action;
  18189. ++_sequence_levels[combo];
  18190. _resetSequenceTimer();
  18191. },
  18192. /**
  18193. * wraps the specified callback inside of another function in order
  18194. * to reset all sequence counters as soon as this sequence is done
  18195. *
  18196. * @param {Event} e
  18197. * @returns void
  18198. */
  18199. _callbackAndReset = function(e) {
  18200. _fireCallback(callback, e);
  18201. // we should ignore the next key up if the action is key down
  18202. // or keypress. this is so if you finish a sequence and
  18203. // release the key the final key will not trigger a keyup
  18204. if (action !== 'keyup') {
  18205. _ignore_next_keyup = _characterFromEvent(e);
  18206. }
  18207. // weird race condition if a sequence ends with the key
  18208. // another sequence begins with
  18209. setTimeout(_resetSequences, 10);
  18210. },
  18211. i;
  18212. // loop through keys one at a time and bind the appropriate callback
  18213. // function. for any key leading up to the final one it should
  18214. // increase the sequence. after the final, it should reset all sequences
  18215. for (i = 0; i < keys.length; ++i) {
  18216. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  18217. }
  18218. }
  18219. /**
  18220. * binds a single keyboard combination
  18221. *
  18222. * @param {string} combination
  18223. * @param {Function} callback
  18224. * @param {string=} action
  18225. * @param {string=} sequence_name - name of sequence if part of sequence
  18226. * @param {number=} level - what part of the sequence the command is
  18227. * @returns void
  18228. */
  18229. function _bindSingle(combination, callback, action, sequence_name, level) {
  18230. // make sure multiple spaces in a row become a single space
  18231. combination = combination.replace(/\s+/g, ' ');
  18232. var sequence = combination.split(' '),
  18233. i,
  18234. key,
  18235. keys,
  18236. modifiers = [];
  18237. // if this pattern is a sequence of keys then run through this method
  18238. // to reprocess each pattern one key at a time
  18239. if (sequence.length > 1) {
  18240. return _bindSequence(combination, sequence, callback, action);
  18241. }
  18242. // take the keys from this pattern and figure out what the actual
  18243. // pattern is all about
  18244. keys = combination === '+' ? ['+'] : combination.split('+');
  18245. for (i = 0; i < keys.length; ++i) {
  18246. key = keys[i];
  18247. // normalize key names
  18248. if (_SPECIAL_ALIASES[key]) {
  18249. key = _SPECIAL_ALIASES[key];
  18250. }
  18251. // if this is not a keypress event then we should
  18252. // be smart about using shift keys
  18253. // this will only work for US keyboards however
  18254. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  18255. key = _SHIFT_MAP[key];
  18256. modifiers.push('shift');
  18257. }
  18258. // if this key is a modifier then add it to the list of modifiers
  18259. if (_isModifier(key)) {
  18260. modifiers.push(key);
  18261. }
  18262. }
  18263. // depending on what the key combination is
  18264. // we will try to pick the best event for it
  18265. action = _pickBestAction(key, modifiers, action);
  18266. // make sure to initialize array if this is the first time
  18267. // a callback is added for this key
  18268. if (!_callbacks[key]) {
  18269. _callbacks[key] = [];
  18270. }
  18271. // remove an existing match if there is one
  18272. _getMatches(key, modifiers, action, !sequence_name, combination);
  18273. // add this call back to the array
  18274. // if it is a sequence put it at the beginning
  18275. // if not put it at the end
  18276. //
  18277. // this is important because the way these are processed expects
  18278. // the sequence ones to come first
  18279. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  18280. callback: callback,
  18281. modifiers: modifiers,
  18282. action: action,
  18283. seq: sequence_name,
  18284. level: level,
  18285. combo: combination
  18286. });
  18287. }
  18288. /**
  18289. * binds multiple combinations to the same callback
  18290. *
  18291. * @param {Array} combinations
  18292. * @param {Function} callback
  18293. * @param {string|undefined} action
  18294. * @returns void
  18295. */
  18296. function _bindMultiple(combinations, callback, action) {
  18297. for (var i = 0; i < combinations.length; ++i) {
  18298. _bindSingle(combinations[i], callback, action);
  18299. }
  18300. }
  18301. // start!
  18302. _addEvent(document, 'keypress', _handleKey);
  18303. _addEvent(document, 'keydown', _handleKey);
  18304. _addEvent(document, 'keyup', _handleKey);
  18305. var mousetrap = {
  18306. /**
  18307. * binds an event to mousetrap
  18308. *
  18309. * can be a single key, a combination of keys separated with +,
  18310. * a comma separated list of keys, an array of keys, or
  18311. * a sequence of keys separated by spaces
  18312. *
  18313. * be sure to list the modifier keys first to make sure that the
  18314. * correct key ends up getting bound (the last key in the pattern)
  18315. *
  18316. * @param {string|Array} keys
  18317. * @param {Function} callback
  18318. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  18319. * @returns void
  18320. */
  18321. bind: function(keys, callback, action) {
  18322. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  18323. _direct_map[keys + ':' + action] = callback;
  18324. return this;
  18325. },
  18326. /**
  18327. * unbinds an event to mousetrap
  18328. *
  18329. * the unbinding sets the callback function of the specified key combo
  18330. * to an empty function and deletes the corresponding key in the
  18331. * _direct_map dict.
  18332. *
  18333. * the keycombo+action has to be exactly the same as
  18334. * it was defined in the bind method
  18335. *
  18336. * TODO: actually remove this from the _callbacks dictionary instead
  18337. * of binding an empty function
  18338. *
  18339. * @param {string|Array} keys
  18340. * @param {string} action
  18341. * @returns void
  18342. */
  18343. unbind: function(keys, action) {
  18344. if (_direct_map[keys + ':' + action]) {
  18345. delete _direct_map[keys + ':' + action];
  18346. this.bind(keys, function() {}, action);
  18347. }
  18348. return this;
  18349. },
  18350. /**
  18351. * triggers an event that has already been bound
  18352. *
  18353. * @param {string} keys
  18354. * @param {string=} action
  18355. * @returns void
  18356. */
  18357. trigger: function(keys, action) {
  18358. _direct_map[keys + ':' + action]();
  18359. return this;
  18360. },
  18361. /**
  18362. * resets the library back to its initial state. this is useful
  18363. * if you want to clear out the current keyboard shortcuts and bind
  18364. * new ones - for example if you switch to another page
  18365. *
  18366. * @returns void
  18367. */
  18368. reset: function() {
  18369. _callbacks = {};
  18370. _direct_map = {};
  18371. return this;
  18372. }
  18373. };
  18374. module.exports = mousetrap;
  18375. /***/ },
  18376. /* 48 */
  18377. /***/ function(module, exports, __webpack_require__) {
  18378. var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {//! moment.js
  18379. //! version : 2.8.1
  18380. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  18381. //! license : MIT
  18382. //! momentjs.com
  18383. (function (undefined) {
  18384. /************************************
  18385. Constants
  18386. ************************************/
  18387. var moment,
  18388. VERSION = '2.8.1',
  18389. // the global-scope this is NOT the global object in Node.js
  18390. globalScope = typeof global !== 'undefined' ? global : this,
  18391. oldGlobalMoment,
  18392. round = Math.round,
  18393. i,
  18394. YEAR = 0,
  18395. MONTH = 1,
  18396. DATE = 2,
  18397. HOUR = 3,
  18398. MINUTE = 4,
  18399. SECOND = 5,
  18400. MILLISECOND = 6,
  18401. // internal storage for locale config files
  18402. locales = {},
  18403. // extra moment internal properties (plugins register props here)
  18404. momentProperties = [],
  18405. // check for nodeJS
  18406. hasModule = (typeof module !== 'undefined' && module.exports),
  18407. // ASP.NET json date format regex
  18408. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  18409. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  18410. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  18411. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  18412. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  18413. // format tokens
  18414. 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|zz?|ZZ?|.)/g,
  18415. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  18416. // parsing token regexes
  18417. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  18418. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  18419. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  18420. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  18421. parseTokenDigits = /\d+/, // nonzero number of digits
  18422. 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.
  18423. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  18424. parseTokenT = /T/i, // T (ISO separator)
  18425. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  18426. parseTokenOrdinal = /\d{1,2}/,
  18427. //strict parsing regexes
  18428. parseTokenOneDigit = /\d/, // 0 - 9
  18429. parseTokenTwoDigits = /\d\d/, // 00 - 99
  18430. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  18431. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  18432. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  18433. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  18434. // iso 8601 regex
  18435. // 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)
  18436. 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)?)?$/,
  18437. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  18438. isoDates = [
  18439. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  18440. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  18441. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  18442. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  18443. ['YYYY-DDD', /\d{4}-\d{3}/]
  18444. ],
  18445. // iso time formats and regexes
  18446. isoTimes = [
  18447. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  18448. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  18449. ['HH:mm', /(T| )\d\d:\d\d/],
  18450. ['HH', /(T| )\d\d/]
  18451. ],
  18452. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  18453. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  18454. // getter and setter names
  18455. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  18456. unitMillisecondFactors = {
  18457. 'Milliseconds' : 1,
  18458. 'Seconds' : 1e3,
  18459. 'Minutes' : 6e4,
  18460. 'Hours' : 36e5,
  18461. 'Days' : 864e5,
  18462. 'Months' : 2592e6,
  18463. 'Years' : 31536e6
  18464. },
  18465. unitAliases = {
  18466. ms : 'millisecond',
  18467. s : 'second',
  18468. m : 'minute',
  18469. h : 'hour',
  18470. d : 'day',
  18471. D : 'date',
  18472. w : 'week',
  18473. W : 'isoWeek',
  18474. M : 'month',
  18475. Q : 'quarter',
  18476. y : 'year',
  18477. DDD : 'dayOfYear',
  18478. e : 'weekday',
  18479. E : 'isoWeekday',
  18480. gg: 'weekYear',
  18481. GG: 'isoWeekYear'
  18482. },
  18483. camelFunctions = {
  18484. dayofyear : 'dayOfYear',
  18485. isoweekday : 'isoWeekday',
  18486. isoweek : 'isoWeek',
  18487. weekyear : 'weekYear',
  18488. isoweekyear : 'isoWeekYear'
  18489. },
  18490. // format function strings
  18491. formatFunctions = {},
  18492. // default relative time thresholds
  18493. relativeTimeThresholds = {
  18494. s: 45, // seconds to minute
  18495. m: 45, // minutes to hour
  18496. h: 22, // hours to day
  18497. d: 26, // days to month
  18498. M: 11 // months to year
  18499. },
  18500. // tokens to ordinalize and pad
  18501. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  18502. paddedTokens = 'M D H h m s w W'.split(' '),
  18503. formatTokenFunctions = {
  18504. M : function () {
  18505. return this.month() + 1;
  18506. },
  18507. MMM : function (format) {
  18508. return this.localeData().monthsShort(this, format);
  18509. },
  18510. MMMM : function (format) {
  18511. return this.localeData().months(this, format);
  18512. },
  18513. D : function () {
  18514. return this.date();
  18515. },
  18516. DDD : function () {
  18517. return this.dayOfYear();
  18518. },
  18519. d : function () {
  18520. return this.day();
  18521. },
  18522. dd : function (format) {
  18523. return this.localeData().weekdaysMin(this, format);
  18524. },
  18525. ddd : function (format) {
  18526. return this.localeData().weekdaysShort(this, format);
  18527. },
  18528. dddd : function (format) {
  18529. return this.localeData().weekdays(this, format);
  18530. },
  18531. w : function () {
  18532. return this.week();
  18533. },
  18534. W : function () {
  18535. return this.isoWeek();
  18536. },
  18537. YY : function () {
  18538. return leftZeroFill(this.year() % 100, 2);
  18539. },
  18540. YYYY : function () {
  18541. return leftZeroFill(this.year(), 4);
  18542. },
  18543. YYYYY : function () {
  18544. return leftZeroFill(this.year(), 5);
  18545. },
  18546. YYYYYY : function () {
  18547. var y = this.year(), sign = y >= 0 ? '+' : '-';
  18548. return sign + leftZeroFill(Math.abs(y), 6);
  18549. },
  18550. gg : function () {
  18551. return leftZeroFill(this.weekYear() % 100, 2);
  18552. },
  18553. gggg : function () {
  18554. return leftZeroFill(this.weekYear(), 4);
  18555. },
  18556. ggggg : function () {
  18557. return leftZeroFill(this.weekYear(), 5);
  18558. },
  18559. GG : function () {
  18560. return leftZeroFill(this.isoWeekYear() % 100, 2);
  18561. },
  18562. GGGG : function () {
  18563. return leftZeroFill(this.isoWeekYear(), 4);
  18564. },
  18565. GGGGG : function () {
  18566. return leftZeroFill(this.isoWeekYear(), 5);
  18567. },
  18568. e : function () {
  18569. return this.weekday();
  18570. },
  18571. E : function () {
  18572. return this.isoWeekday();
  18573. },
  18574. a : function () {
  18575. return this.localeData().meridiem(this.hours(), this.minutes(), true);
  18576. },
  18577. A : function () {
  18578. return this.localeData().meridiem(this.hours(), this.minutes(), false);
  18579. },
  18580. H : function () {
  18581. return this.hours();
  18582. },
  18583. h : function () {
  18584. return this.hours() % 12 || 12;
  18585. },
  18586. m : function () {
  18587. return this.minutes();
  18588. },
  18589. s : function () {
  18590. return this.seconds();
  18591. },
  18592. S : function () {
  18593. return toInt(this.milliseconds() / 100);
  18594. },
  18595. SS : function () {
  18596. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  18597. },
  18598. SSS : function () {
  18599. return leftZeroFill(this.milliseconds(), 3);
  18600. },
  18601. SSSS : function () {
  18602. return leftZeroFill(this.milliseconds(), 3);
  18603. },
  18604. Z : function () {
  18605. var a = -this.zone(),
  18606. b = '+';
  18607. if (a < 0) {
  18608. a = -a;
  18609. b = '-';
  18610. }
  18611. return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2);
  18612. },
  18613. ZZ : function () {
  18614. var a = -this.zone(),
  18615. b = '+';
  18616. if (a < 0) {
  18617. a = -a;
  18618. b = '-';
  18619. }
  18620. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  18621. },
  18622. z : function () {
  18623. return this.zoneAbbr();
  18624. },
  18625. zz : function () {
  18626. return this.zoneName();
  18627. },
  18628. X : function () {
  18629. return this.unix();
  18630. },
  18631. Q : function () {
  18632. return this.quarter();
  18633. }
  18634. },
  18635. deprecations = {},
  18636. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  18637. // Pick the first defined of two or three arguments. dfl comes from
  18638. // default.
  18639. function dfl(a, b, c) {
  18640. switch (arguments.length) {
  18641. case 2: return a != null ? a : b;
  18642. case 3: return a != null ? a : b != null ? b : c;
  18643. default: throw new Error('Implement me');
  18644. }
  18645. }
  18646. function defaultParsingFlags() {
  18647. // We need to deep clone this object, and es5 standard is not very
  18648. // helpful.
  18649. return {
  18650. empty : false,
  18651. unusedTokens : [],
  18652. unusedInput : [],
  18653. overflow : -2,
  18654. charsLeftOver : 0,
  18655. nullInput : false,
  18656. invalidMonth : null,
  18657. invalidFormat : false,
  18658. userInvalidated : false,
  18659. iso: false
  18660. };
  18661. }
  18662. function printMsg(msg) {
  18663. if (moment.suppressDeprecationWarnings === false &&
  18664. typeof console !== 'undefined' && console.warn) {
  18665. console.warn("Deprecation warning: " + msg);
  18666. }
  18667. }
  18668. function deprecate(msg, fn) {
  18669. var firstTime = true;
  18670. return extend(function () {
  18671. if (firstTime) {
  18672. printMsg(msg);
  18673. firstTime = false;
  18674. }
  18675. return fn.apply(this, arguments);
  18676. }, fn);
  18677. }
  18678. function deprecateSimple(name, msg) {
  18679. if (!deprecations[name]) {
  18680. printMsg(msg);
  18681. deprecations[name] = true;
  18682. }
  18683. }
  18684. function padToken(func, count) {
  18685. return function (a) {
  18686. return leftZeroFill(func.call(this, a), count);
  18687. };
  18688. }
  18689. function ordinalizeToken(func, period) {
  18690. return function (a) {
  18691. return this.localeData().ordinal(func.call(this, a), period);
  18692. };
  18693. }
  18694. while (ordinalizeTokens.length) {
  18695. i = ordinalizeTokens.pop();
  18696. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  18697. }
  18698. while (paddedTokens.length) {
  18699. i = paddedTokens.pop();
  18700. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  18701. }
  18702. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  18703. /************************************
  18704. Constructors
  18705. ************************************/
  18706. function Locale() {
  18707. }
  18708. // Moment prototype object
  18709. function Moment(config, skipOverflow) {
  18710. if (skipOverflow !== false) {
  18711. checkOverflow(config);
  18712. }
  18713. copyConfig(this, config);
  18714. this._d = new Date(+config._d);
  18715. }
  18716. // Duration Constructor
  18717. function Duration(duration) {
  18718. var normalizedInput = normalizeObjectUnits(duration),
  18719. years = normalizedInput.year || 0,
  18720. quarters = normalizedInput.quarter || 0,
  18721. months = normalizedInput.month || 0,
  18722. weeks = normalizedInput.week || 0,
  18723. days = normalizedInput.day || 0,
  18724. hours = normalizedInput.hour || 0,
  18725. minutes = normalizedInput.minute || 0,
  18726. seconds = normalizedInput.second || 0,
  18727. milliseconds = normalizedInput.millisecond || 0;
  18728. // representation for dateAddRemove
  18729. this._milliseconds = +milliseconds +
  18730. seconds * 1e3 + // 1000
  18731. minutes * 6e4 + // 1000 * 60
  18732. hours * 36e5; // 1000 * 60 * 60
  18733. // Because of dateAddRemove treats 24 hours as different from a
  18734. // day when working around DST, we need to store them separately
  18735. this._days = +days +
  18736. weeks * 7;
  18737. // It is impossible translate months into days without knowing
  18738. // which months you are are talking about, so we have to store
  18739. // it separately.
  18740. this._months = +months +
  18741. quarters * 3 +
  18742. years * 12;
  18743. this._data = {};
  18744. this._locale = moment.localeData();
  18745. this._bubble();
  18746. }
  18747. /************************************
  18748. Helpers
  18749. ************************************/
  18750. function extend(a, b) {
  18751. for (var i in b) {
  18752. if (b.hasOwnProperty(i)) {
  18753. a[i] = b[i];
  18754. }
  18755. }
  18756. if (b.hasOwnProperty('toString')) {
  18757. a.toString = b.toString;
  18758. }
  18759. if (b.hasOwnProperty('valueOf')) {
  18760. a.valueOf = b.valueOf;
  18761. }
  18762. return a;
  18763. }
  18764. function copyConfig(to, from) {
  18765. var i, prop, val;
  18766. if (typeof from._isAMomentObject !== 'undefined') {
  18767. to._isAMomentObject = from._isAMomentObject;
  18768. }
  18769. if (typeof from._i !== 'undefined') {
  18770. to._i = from._i;
  18771. }
  18772. if (typeof from._f !== 'undefined') {
  18773. to._f = from._f;
  18774. }
  18775. if (typeof from._l !== 'undefined') {
  18776. to._l = from._l;
  18777. }
  18778. if (typeof from._strict !== 'undefined') {
  18779. to._strict = from._strict;
  18780. }
  18781. if (typeof from._tzm !== 'undefined') {
  18782. to._tzm = from._tzm;
  18783. }
  18784. if (typeof from._isUTC !== 'undefined') {
  18785. to._isUTC = from._isUTC;
  18786. }
  18787. if (typeof from._offset !== 'undefined') {
  18788. to._offset = from._offset;
  18789. }
  18790. if (typeof from._pf !== 'undefined') {
  18791. to._pf = from._pf;
  18792. }
  18793. if (typeof from._locale !== 'undefined') {
  18794. to._locale = from._locale;
  18795. }
  18796. if (momentProperties.length > 0) {
  18797. for (i in momentProperties) {
  18798. prop = momentProperties[i];
  18799. val = from[prop];
  18800. if (typeof val !== 'undefined') {
  18801. to[prop] = val;
  18802. }
  18803. }
  18804. }
  18805. return to;
  18806. }
  18807. function absRound(number) {
  18808. if (number < 0) {
  18809. return Math.ceil(number);
  18810. } else {
  18811. return Math.floor(number);
  18812. }
  18813. }
  18814. // left zero fill a number
  18815. // see http://jsperf.com/left-zero-filling for performance comparison
  18816. function leftZeroFill(number, targetLength, forceSign) {
  18817. var output = '' + Math.abs(number),
  18818. sign = number >= 0;
  18819. while (output.length < targetLength) {
  18820. output = '0' + output;
  18821. }
  18822. return (sign ? (forceSign ? '+' : '') : '-') + output;
  18823. }
  18824. function positiveMomentsDifference(base, other) {
  18825. var res = {milliseconds: 0, months: 0};
  18826. res.months = other.month() - base.month() +
  18827. (other.year() - base.year()) * 12;
  18828. if (base.clone().add(res.months, 'M').isAfter(other)) {
  18829. --res.months;
  18830. }
  18831. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  18832. return res;
  18833. }
  18834. function momentsDifference(base, other) {
  18835. var res;
  18836. other = makeAs(other, base);
  18837. if (base.isBefore(other)) {
  18838. res = positiveMomentsDifference(base, other);
  18839. } else {
  18840. res = positiveMomentsDifference(other, base);
  18841. res.milliseconds = -res.milliseconds;
  18842. res.months = -res.months;
  18843. }
  18844. return res;
  18845. }
  18846. // TODO: remove 'name' arg after deprecation is removed
  18847. function createAdder(direction, name) {
  18848. return function (val, period) {
  18849. var dur, tmp;
  18850. //invert the arguments, but complain about it
  18851. if (period !== null && !isNaN(+period)) {
  18852. deprecateSimple(name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period).");
  18853. tmp = val; val = period; period = tmp;
  18854. }
  18855. val = typeof val === 'string' ? +val : val;
  18856. dur = moment.duration(val, period);
  18857. addOrSubtractDurationFromMoment(this, dur, direction);
  18858. return this;
  18859. };
  18860. }
  18861. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  18862. var milliseconds = duration._milliseconds,
  18863. days = duration._days,
  18864. months = duration._months;
  18865. updateOffset = updateOffset == null ? true : updateOffset;
  18866. if (milliseconds) {
  18867. mom._d.setTime(+mom._d + milliseconds * isAdding);
  18868. }
  18869. if (days) {
  18870. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  18871. }
  18872. if (months) {
  18873. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  18874. }
  18875. if (updateOffset) {
  18876. moment.updateOffset(mom, days || months);
  18877. }
  18878. }
  18879. // check if is an array
  18880. function isArray(input) {
  18881. return Object.prototype.toString.call(input) === '[object Array]';
  18882. }
  18883. function isDate(input) {
  18884. return Object.prototype.toString.call(input) === '[object Date]' ||
  18885. input instanceof Date;
  18886. }
  18887. // compare two arrays, return the number of differences
  18888. function compareArrays(array1, array2, dontConvert) {
  18889. var len = Math.min(array1.length, array2.length),
  18890. lengthDiff = Math.abs(array1.length - array2.length),
  18891. diffs = 0,
  18892. i;
  18893. for (i = 0; i < len; i++) {
  18894. if ((dontConvert && array1[i] !== array2[i]) ||
  18895. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  18896. diffs++;
  18897. }
  18898. }
  18899. return diffs + lengthDiff;
  18900. }
  18901. function normalizeUnits(units) {
  18902. if (units) {
  18903. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  18904. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  18905. }
  18906. return units;
  18907. }
  18908. function normalizeObjectUnits(inputObject) {
  18909. var normalizedInput = {},
  18910. normalizedProp,
  18911. prop;
  18912. for (prop in inputObject) {
  18913. if (inputObject.hasOwnProperty(prop)) {
  18914. normalizedProp = normalizeUnits(prop);
  18915. if (normalizedProp) {
  18916. normalizedInput[normalizedProp] = inputObject[prop];
  18917. }
  18918. }
  18919. }
  18920. return normalizedInput;
  18921. }
  18922. function makeList(field) {
  18923. var count, setter;
  18924. if (field.indexOf('week') === 0) {
  18925. count = 7;
  18926. setter = 'day';
  18927. }
  18928. else if (field.indexOf('month') === 0) {
  18929. count = 12;
  18930. setter = 'month';
  18931. }
  18932. else {
  18933. return;
  18934. }
  18935. moment[field] = function (format, index) {
  18936. var i, getter,
  18937. method = moment._locale[field],
  18938. results = [];
  18939. if (typeof format === 'number') {
  18940. index = format;
  18941. format = undefined;
  18942. }
  18943. getter = function (i) {
  18944. var m = moment().utc().set(setter, i);
  18945. return method.call(moment._locale, m, format || '');
  18946. };
  18947. if (index != null) {
  18948. return getter(index);
  18949. }
  18950. else {
  18951. for (i = 0; i < count; i++) {
  18952. results.push(getter(i));
  18953. }
  18954. return results;
  18955. }
  18956. };
  18957. }
  18958. function toInt(argumentForCoercion) {
  18959. var coercedNumber = +argumentForCoercion,
  18960. value = 0;
  18961. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  18962. if (coercedNumber >= 0) {
  18963. value = Math.floor(coercedNumber);
  18964. } else {
  18965. value = Math.ceil(coercedNumber);
  18966. }
  18967. }
  18968. return value;
  18969. }
  18970. function daysInMonth(year, month) {
  18971. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  18972. }
  18973. function weeksInYear(year, dow, doy) {
  18974. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  18975. }
  18976. function daysInYear(year) {
  18977. return isLeapYear(year) ? 366 : 365;
  18978. }
  18979. function isLeapYear(year) {
  18980. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  18981. }
  18982. function checkOverflow(m) {
  18983. var overflow;
  18984. if (m._a && m._pf.overflow === -2) {
  18985. overflow =
  18986. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  18987. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  18988. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  18989. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  18990. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  18991. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  18992. -1;
  18993. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  18994. overflow = DATE;
  18995. }
  18996. m._pf.overflow = overflow;
  18997. }
  18998. }
  18999. function isValid(m) {
  19000. if (m._isValid == null) {
  19001. m._isValid = !isNaN(m._d.getTime()) &&
  19002. m._pf.overflow < 0 &&
  19003. !m._pf.empty &&
  19004. !m._pf.invalidMonth &&
  19005. !m._pf.nullInput &&
  19006. !m._pf.invalidFormat &&
  19007. !m._pf.userInvalidated;
  19008. if (m._strict) {
  19009. m._isValid = m._isValid &&
  19010. m._pf.charsLeftOver === 0 &&
  19011. m._pf.unusedTokens.length === 0;
  19012. }
  19013. }
  19014. return m._isValid;
  19015. }
  19016. function normalizeLocale(key) {
  19017. return key ? key.toLowerCase().replace('_', '-') : key;
  19018. }
  19019. // pick the locale from the array
  19020. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  19021. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  19022. function chooseLocale(names) {
  19023. var i = 0, j, next, locale, split;
  19024. while (i < names.length) {
  19025. split = normalizeLocale(names[i]).split('-');
  19026. j = split.length;
  19027. next = normalizeLocale(names[i + 1]);
  19028. next = next ? next.split('-') : null;
  19029. while (j > 0) {
  19030. locale = loadLocale(split.slice(0, j).join('-'));
  19031. if (locale) {
  19032. return locale;
  19033. }
  19034. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  19035. //the next array item is better than a shallower substring of this one
  19036. break;
  19037. }
  19038. j--;
  19039. }
  19040. i++;
  19041. }
  19042. return null;
  19043. }
  19044. function loadLocale(name) {
  19045. var oldLocale = null;
  19046. if (!locales[name] && hasModule) {
  19047. try {
  19048. oldLocale = moment.locale();
  19049. !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
  19050. // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales
  19051. moment.locale(oldLocale);
  19052. } catch (e) { }
  19053. }
  19054. return locales[name];
  19055. }
  19056. // Return a moment from input, that is local/utc/zone equivalent to model.
  19057. function makeAs(input, model) {
  19058. return model._isUTC ? moment(input).zone(model._offset || 0) :
  19059. moment(input).local();
  19060. }
  19061. /************************************
  19062. Locale
  19063. ************************************/
  19064. extend(Locale.prototype, {
  19065. set : function (config) {
  19066. var prop, i;
  19067. for (i in config) {
  19068. prop = config[i];
  19069. if (typeof prop === 'function') {
  19070. this[i] = prop;
  19071. } else {
  19072. this['_' + i] = prop;
  19073. }
  19074. }
  19075. },
  19076. _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
  19077. months : function (m) {
  19078. return this._months[m.month()];
  19079. },
  19080. _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
  19081. monthsShort : function (m) {
  19082. return this._monthsShort[m.month()];
  19083. },
  19084. monthsParse : function (monthName) {
  19085. var i, mom, regex;
  19086. if (!this._monthsParse) {
  19087. this._monthsParse = [];
  19088. }
  19089. for (i = 0; i < 12; i++) {
  19090. // make the regex if we don't have it already
  19091. if (!this._monthsParse[i]) {
  19092. mom = moment.utc([2000, i]);
  19093. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  19094. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  19095. }
  19096. // test the regex
  19097. if (this._monthsParse[i].test(monthName)) {
  19098. return i;
  19099. }
  19100. }
  19101. },
  19102. _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
  19103. weekdays : function (m) {
  19104. return this._weekdays[m.day()];
  19105. },
  19106. _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  19107. weekdaysShort : function (m) {
  19108. return this._weekdaysShort[m.day()];
  19109. },
  19110. _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  19111. weekdaysMin : function (m) {
  19112. return this._weekdaysMin[m.day()];
  19113. },
  19114. weekdaysParse : function (weekdayName) {
  19115. var i, mom, regex;
  19116. if (!this._weekdaysParse) {
  19117. this._weekdaysParse = [];
  19118. }
  19119. for (i = 0; i < 7; i++) {
  19120. // make the regex if we don't have it already
  19121. if (!this._weekdaysParse[i]) {
  19122. mom = moment([2000, 1]).day(i);
  19123. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  19124. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  19125. }
  19126. // test the regex
  19127. if (this._weekdaysParse[i].test(weekdayName)) {
  19128. return i;
  19129. }
  19130. }
  19131. },
  19132. _longDateFormat : {
  19133. LT : 'h:mm A',
  19134. L : 'MM/DD/YYYY',
  19135. LL : 'MMMM D, YYYY',
  19136. LLL : 'MMMM D, YYYY LT',
  19137. LLLL : 'dddd, MMMM D, YYYY LT'
  19138. },
  19139. longDateFormat : function (key) {
  19140. var output = this._longDateFormat[key];
  19141. if (!output && this._longDateFormat[key.toUpperCase()]) {
  19142. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  19143. return val.slice(1);
  19144. });
  19145. this._longDateFormat[key] = output;
  19146. }
  19147. return output;
  19148. },
  19149. isPM : function (input) {
  19150. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  19151. // Using charAt should be more compatible.
  19152. return ((input + '').toLowerCase().charAt(0) === 'p');
  19153. },
  19154. _meridiemParse : /[ap]\.?m?\.?/i,
  19155. meridiem : function (hours, minutes, isLower) {
  19156. if (hours > 11) {
  19157. return isLower ? 'pm' : 'PM';
  19158. } else {
  19159. return isLower ? 'am' : 'AM';
  19160. }
  19161. },
  19162. _calendar : {
  19163. sameDay : '[Today at] LT',
  19164. nextDay : '[Tomorrow at] LT',
  19165. nextWeek : 'dddd [at] LT',
  19166. lastDay : '[Yesterday at] LT',
  19167. lastWeek : '[Last] dddd [at] LT',
  19168. sameElse : 'L'
  19169. },
  19170. calendar : function (key, mom) {
  19171. var output = this._calendar[key];
  19172. return typeof output === 'function' ? output.apply(mom) : output;
  19173. },
  19174. _relativeTime : {
  19175. future : 'in %s',
  19176. past : '%s ago',
  19177. s : 'a few seconds',
  19178. m : 'a minute',
  19179. mm : '%d minutes',
  19180. h : 'an hour',
  19181. hh : '%d hours',
  19182. d : 'a day',
  19183. dd : '%d days',
  19184. M : 'a month',
  19185. MM : '%d months',
  19186. y : 'a year',
  19187. yy : '%d years'
  19188. },
  19189. relativeTime : function (number, withoutSuffix, string, isFuture) {
  19190. var output = this._relativeTime[string];
  19191. return (typeof output === 'function') ?
  19192. output(number, withoutSuffix, string, isFuture) :
  19193. output.replace(/%d/i, number);
  19194. },
  19195. pastFuture : function (diff, output) {
  19196. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  19197. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  19198. },
  19199. ordinal : function (number) {
  19200. return this._ordinal.replace('%d', number);
  19201. },
  19202. _ordinal : '%d',
  19203. preparse : function (string) {
  19204. return string;
  19205. },
  19206. postformat : function (string) {
  19207. return string;
  19208. },
  19209. week : function (mom) {
  19210. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  19211. },
  19212. _week : {
  19213. dow : 0, // Sunday is the first day of the week.
  19214. doy : 6 // The week that contains Jan 1st is the first week of the year.
  19215. },
  19216. _invalidDate: 'Invalid date',
  19217. invalidDate: function () {
  19218. return this._invalidDate;
  19219. }
  19220. });
  19221. /************************************
  19222. Formatting
  19223. ************************************/
  19224. function removeFormattingTokens(input) {
  19225. if (input.match(/\[[\s\S]/)) {
  19226. return input.replace(/^\[|\]$/g, '');
  19227. }
  19228. return input.replace(/\\/g, '');
  19229. }
  19230. function makeFormatFunction(format) {
  19231. var array = format.match(formattingTokens), i, length;
  19232. for (i = 0, length = array.length; i < length; i++) {
  19233. if (formatTokenFunctions[array[i]]) {
  19234. array[i] = formatTokenFunctions[array[i]];
  19235. } else {
  19236. array[i] = removeFormattingTokens(array[i]);
  19237. }
  19238. }
  19239. return function (mom) {
  19240. var output = '';
  19241. for (i = 0; i < length; i++) {
  19242. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  19243. }
  19244. return output;
  19245. };
  19246. }
  19247. // format date using native date object
  19248. function formatMoment(m, format) {
  19249. if (!m.isValid()) {
  19250. return m.localeData().invalidDate();
  19251. }
  19252. format = expandFormat(format, m.localeData());
  19253. if (!formatFunctions[format]) {
  19254. formatFunctions[format] = makeFormatFunction(format);
  19255. }
  19256. return formatFunctions[format](m);
  19257. }
  19258. function expandFormat(format, locale) {
  19259. var i = 5;
  19260. function replaceLongDateFormatTokens(input) {
  19261. return locale.longDateFormat(input) || input;
  19262. }
  19263. localFormattingTokens.lastIndex = 0;
  19264. while (i >= 0 && localFormattingTokens.test(format)) {
  19265. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  19266. localFormattingTokens.lastIndex = 0;
  19267. i -= 1;
  19268. }
  19269. return format;
  19270. }
  19271. /************************************
  19272. Parsing
  19273. ************************************/
  19274. // get the regex to find the next token
  19275. function getParseRegexForToken(token, config) {
  19276. var a, strict = config._strict;
  19277. switch (token) {
  19278. case 'Q':
  19279. return parseTokenOneDigit;
  19280. case 'DDDD':
  19281. return parseTokenThreeDigits;
  19282. case 'YYYY':
  19283. case 'GGGG':
  19284. case 'gggg':
  19285. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  19286. case 'Y':
  19287. case 'G':
  19288. case 'g':
  19289. return parseTokenSignedNumber;
  19290. case 'YYYYYY':
  19291. case 'YYYYY':
  19292. case 'GGGGG':
  19293. case 'ggggg':
  19294. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  19295. case 'S':
  19296. if (strict) {
  19297. return parseTokenOneDigit;
  19298. }
  19299. /* falls through */
  19300. case 'SS':
  19301. if (strict) {
  19302. return parseTokenTwoDigits;
  19303. }
  19304. /* falls through */
  19305. case 'SSS':
  19306. if (strict) {
  19307. return parseTokenThreeDigits;
  19308. }
  19309. /* falls through */
  19310. case 'DDD':
  19311. return parseTokenOneToThreeDigits;
  19312. case 'MMM':
  19313. case 'MMMM':
  19314. case 'dd':
  19315. case 'ddd':
  19316. case 'dddd':
  19317. return parseTokenWord;
  19318. case 'a':
  19319. case 'A':
  19320. return config._locale._meridiemParse;
  19321. case 'X':
  19322. return parseTokenTimestampMs;
  19323. case 'Z':
  19324. case 'ZZ':
  19325. return parseTokenTimezone;
  19326. case 'T':
  19327. return parseTokenT;
  19328. case 'SSSS':
  19329. return parseTokenDigits;
  19330. case 'MM':
  19331. case 'DD':
  19332. case 'YY':
  19333. case 'GG':
  19334. case 'gg':
  19335. case 'HH':
  19336. case 'hh':
  19337. case 'mm':
  19338. case 'ss':
  19339. case 'ww':
  19340. case 'WW':
  19341. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  19342. case 'M':
  19343. case 'D':
  19344. case 'd':
  19345. case 'H':
  19346. case 'h':
  19347. case 'm':
  19348. case 's':
  19349. case 'w':
  19350. case 'W':
  19351. case 'e':
  19352. case 'E':
  19353. return parseTokenOneOrTwoDigits;
  19354. case 'Do':
  19355. return parseTokenOrdinal;
  19356. default :
  19357. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i'));
  19358. return a;
  19359. }
  19360. }
  19361. function timezoneMinutesFromString(string) {
  19362. string = string || '';
  19363. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  19364. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  19365. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  19366. minutes = +(parts[1] * 60) + toInt(parts[2]);
  19367. return parts[0] === '+' ? -minutes : minutes;
  19368. }
  19369. // function to convert string input to date
  19370. function addTimeToArrayFromToken(token, input, config) {
  19371. var a, datePartArray = config._a;
  19372. switch (token) {
  19373. // QUARTER
  19374. case 'Q':
  19375. if (input != null) {
  19376. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  19377. }
  19378. break;
  19379. // MONTH
  19380. case 'M' : // fall through to MM
  19381. case 'MM' :
  19382. if (input != null) {
  19383. datePartArray[MONTH] = toInt(input) - 1;
  19384. }
  19385. break;
  19386. case 'MMM' : // fall through to MMMM
  19387. case 'MMMM' :
  19388. a = config._locale.monthsParse(input);
  19389. // if we didn't find a month name, mark the date as invalid.
  19390. if (a != null) {
  19391. datePartArray[MONTH] = a;
  19392. } else {
  19393. config._pf.invalidMonth = input;
  19394. }
  19395. break;
  19396. // DAY OF MONTH
  19397. case 'D' : // fall through to DD
  19398. case 'DD' :
  19399. if (input != null) {
  19400. datePartArray[DATE] = toInt(input);
  19401. }
  19402. break;
  19403. case 'Do' :
  19404. if (input != null) {
  19405. datePartArray[DATE] = toInt(parseInt(input, 10));
  19406. }
  19407. break;
  19408. // DAY OF YEAR
  19409. case 'DDD' : // fall through to DDDD
  19410. case 'DDDD' :
  19411. if (input != null) {
  19412. config._dayOfYear = toInt(input);
  19413. }
  19414. break;
  19415. // YEAR
  19416. case 'YY' :
  19417. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  19418. break;
  19419. case 'YYYY' :
  19420. case 'YYYYY' :
  19421. case 'YYYYYY' :
  19422. datePartArray[YEAR] = toInt(input);
  19423. break;
  19424. // AM / PM
  19425. case 'a' : // fall through to A
  19426. case 'A' :
  19427. config._isPm = config._locale.isPM(input);
  19428. break;
  19429. // 24 HOUR
  19430. case 'H' : // fall through to hh
  19431. case 'HH' : // fall through to hh
  19432. case 'h' : // fall through to hh
  19433. case 'hh' :
  19434. datePartArray[HOUR] = toInt(input);
  19435. break;
  19436. // MINUTE
  19437. case 'm' : // fall through to mm
  19438. case 'mm' :
  19439. datePartArray[MINUTE] = toInt(input);
  19440. break;
  19441. // SECOND
  19442. case 's' : // fall through to ss
  19443. case 'ss' :
  19444. datePartArray[SECOND] = toInt(input);
  19445. break;
  19446. // MILLISECOND
  19447. case 'S' :
  19448. case 'SS' :
  19449. case 'SSS' :
  19450. case 'SSSS' :
  19451. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  19452. break;
  19453. // UNIX TIMESTAMP WITH MS
  19454. case 'X':
  19455. config._d = new Date(parseFloat(input) * 1000);
  19456. break;
  19457. // TIMEZONE
  19458. case 'Z' : // fall through to ZZ
  19459. case 'ZZ' :
  19460. config._useUTC = true;
  19461. config._tzm = timezoneMinutesFromString(input);
  19462. break;
  19463. // WEEKDAY - human
  19464. case 'dd':
  19465. case 'ddd':
  19466. case 'dddd':
  19467. a = config._locale.weekdaysParse(input);
  19468. // if we didn't get a weekday name, mark the date as invalid
  19469. if (a != null) {
  19470. config._w = config._w || {};
  19471. config._w['d'] = a;
  19472. } else {
  19473. config._pf.invalidWeekday = input;
  19474. }
  19475. break;
  19476. // WEEK, WEEK DAY - numeric
  19477. case 'w':
  19478. case 'ww':
  19479. case 'W':
  19480. case 'WW':
  19481. case 'd':
  19482. case 'e':
  19483. case 'E':
  19484. token = token.substr(0, 1);
  19485. /* falls through */
  19486. case 'gggg':
  19487. case 'GGGG':
  19488. case 'GGGGG':
  19489. token = token.substr(0, 2);
  19490. if (input) {
  19491. config._w = config._w || {};
  19492. config._w[token] = toInt(input);
  19493. }
  19494. break;
  19495. case 'gg':
  19496. case 'GG':
  19497. config._w = config._w || {};
  19498. config._w[token] = moment.parseTwoDigitYear(input);
  19499. }
  19500. }
  19501. function dayOfYearFromWeekInfo(config) {
  19502. var w, weekYear, week, weekday, dow, doy, temp;
  19503. w = config._w;
  19504. if (w.GG != null || w.W != null || w.E != null) {
  19505. dow = 1;
  19506. doy = 4;
  19507. // TODO: We need to take the current isoWeekYear, but that depends on
  19508. // how we interpret now (local, utc, fixed offset). So create
  19509. // a now version of current config (take local/utc/offset flags, and
  19510. // create now).
  19511. weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year);
  19512. week = dfl(w.W, 1);
  19513. weekday = dfl(w.E, 1);
  19514. } else {
  19515. dow = config._locale._week.dow;
  19516. doy = config._locale._week.doy;
  19517. weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year);
  19518. week = dfl(w.w, 1);
  19519. if (w.d != null) {
  19520. // weekday -- low day numbers are considered next week
  19521. weekday = w.d;
  19522. if (weekday < dow) {
  19523. ++week;
  19524. }
  19525. } else if (w.e != null) {
  19526. // local weekday -- counting starts from begining of week
  19527. weekday = w.e + dow;
  19528. } else {
  19529. // default to begining of week
  19530. weekday = dow;
  19531. }
  19532. }
  19533. temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
  19534. config._a[YEAR] = temp.year;
  19535. config._dayOfYear = temp.dayOfYear;
  19536. }
  19537. // convert an array to a date.
  19538. // the array should mirror the parameters below
  19539. // note: all values past the year are optional and will default to the lowest possible value.
  19540. // [year, month, day , hour, minute, second, millisecond]
  19541. function dateFromConfig(config) {
  19542. var i, date, input = [], currentDate, yearToUse;
  19543. if (config._d) {
  19544. return;
  19545. }
  19546. currentDate = currentDateArray(config);
  19547. //compute day of the year from weeks and weekdays
  19548. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  19549. dayOfYearFromWeekInfo(config);
  19550. }
  19551. //if the day of the year is set, figure out what it is
  19552. if (config._dayOfYear) {
  19553. yearToUse = dfl(config._a[YEAR], currentDate[YEAR]);
  19554. if (config._dayOfYear > daysInYear(yearToUse)) {
  19555. config._pf._overflowDayOfYear = true;
  19556. }
  19557. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  19558. config._a[MONTH] = date.getUTCMonth();
  19559. config._a[DATE] = date.getUTCDate();
  19560. }
  19561. // Default to current date.
  19562. // * if no year, month, day of month are given, default to today
  19563. // * if day of month is given, default month and year
  19564. // * if month is given, default only year
  19565. // * if year is given, don't default anything
  19566. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  19567. config._a[i] = input[i] = currentDate[i];
  19568. }
  19569. // Zero out whatever was not defaulted, including time
  19570. for (; i < 7; i++) {
  19571. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  19572. }
  19573. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  19574. // Apply timezone offset from input. The actual zone can be changed
  19575. // with parseZone.
  19576. if (config._tzm != null) {
  19577. config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm);
  19578. }
  19579. }
  19580. function dateFromObject(config) {
  19581. var normalizedInput;
  19582. if (config._d) {
  19583. return;
  19584. }
  19585. normalizedInput = normalizeObjectUnits(config._i);
  19586. config._a = [
  19587. normalizedInput.year,
  19588. normalizedInput.month,
  19589. normalizedInput.day,
  19590. normalizedInput.hour,
  19591. normalizedInput.minute,
  19592. normalizedInput.second,
  19593. normalizedInput.millisecond
  19594. ];
  19595. dateFromConfig(config);
  19596. }
  19597. function currentDateArray(config) {
  19598. var now = new Date();
  19599. if (config._useUTC) {
  19600. return [
  19601. now.getUTCFullYear(),
  19602. now.getUTCMonth(),
  19603. now.getUTCDate()
  19604. ];
  19605. } else {
  19606. return [now.getFullYear(), now.getMonth(), now.getDate()];
  19607. }
  19608. }
  19609. // date from string and format string
  19610. function makeDateFromStringAndFormat(config) {
  19611. if (config._f === moment.ISO_8601) {
  19612. parseISO(config);
  19613. return;
  19614. }
  19615. config._a = [];
  19616. config._pf.empty = true;
  19617. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  19618. var string = '' + config._i,
  19619. i, parsedInput, tokens, token, skipped,
  19620. stringLength = string.length,
  19621. totalParsedInputLength = 0;
  19622. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  19623. for (i = 0; i < tokens.length; i++) {
  19624. token = tokens[i];
  19625. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  19626. if (parsedInput) {
  19627. skipped = string.substr(0, string.indexOf(parsedInput));
  19628. if (skipped.length > 0) {
  19629. config._pf.unusedInput.push(skipped);
  19630. }
  19631. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  19632. totalParsedInputLength += parsedInput.length;
  19633. }
  19634. // don't parse if it's not a known token
  19635. if (formatTokenFunctions[token]) {
  19636. if (parsedInput) {
  19637. config._pf.empty = false;
  19638. }
  19639. else {
  19640. config._pf.unusedTokens.push(token);
  19641. }
  19642. addTimeToArrayFromToken(token, parsedInput, config);
  19643. }
  19644. else if (config._strict && !parsedInput) {
  19645. config._pf.unusedTokens.push(token);
  19646. }
  19647. }
  19648. // add remaining unparsed input length to the string
  19649. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  19650. if (string.length > 0) {
  19651. config._pf.unusedInput.push(string);
  19652. }
  19653. // handle am pm
  19654. if (config._isPm && config._a[HOUR] < 12) {
  19655. config._a[HOUR] += 12;
  19656. }
  19657. // if is 12 am, change hours to 0
  19658. if (config._isPm === false && config._a[HOUR] === 12) {
  19659. config._a[HOUR] = 0;
  19660. }
  19661. dateFromConfig(config);
  19662. checkOverflow(config);
  19663. }
  19664. function unescapeFormat(s) {
  19665. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  19666. return p1 || p2 || p3 || p4;
  19667. });
  19668. }
  19669. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  19670. function regexpEscape(s) {
  19671. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  19672. }
  19673. // date from string and array of format strings
  19674. function makeDateFromStringAndArray(config) {
  19675. var tempConfig,
  19676. bestMoment,
  19677. scoreToBeat,
  19678. i,
  19679. currentScore;
  19680. if (config._f.length === 0) {
  19681. config._pf.invalidFormat = true;
  19682. config._d = new Date(NaN);
  19683. return;
  19684. }
  19685. for (i = 0; i < config._f.length; i++) {
  19686. currentScore = 0;
  19687. tempConfig = copyConfig({}, config);
  19688. tempConfig._pf = defaultParsingFlags();
  19689. tempConfig._f = config._f[i];
  19690. makeDateFromStringAndFormat(tempConfig);
  19691. if (!isValid(tempConfig)) {
  19692. continue;
  19693. }
  19694. // if there is any input that was not parsed add a penalty for that format
  19695. currentScore += tempConfig._pf.charsLeftOver;
  19696. //or tokens
  19697. currentScore += tempConfig._pf.unusedTokens.length * 10;
  19698. tempConfig._pf.score = currentScore;
  19699. if (scoreToBeat == null || currentScore < scoreToBeat) {
  19700. scoreToBeat = currentScore;
  19701. bestMoment = tempConfig;
  19702. }
  19703. }
  19704. extend(config, bestMoment || tempConfig);
  19705. }
  19706. // date from iso format
  19707. function parseISO(config) {
  19708. var i, l,
  19709. string = config._i,
  19710. match = isoRegex.exec(string);
  19711. if (match) {
  19712. config._pf.iso = true;
  19713. for (i = 0, l = isoDates.length; i < l; i++) {
  19714. if (isoDates[i][1].exec(string)) {
  19715. // match[5] should be "T" or undefined
  19716. config._f = isoDates[i][0] + (match[6] || ' ');
  19717. break;
  19718. }
  19719. }
  19720. for (i = 0, l = isoTimes.length; i < l; i++) {
  19721. if (isoTimes[i][1].exec(string)) {
  19722. config._f += isoTimes[i][0];
  19723. break;
  19724. }
  19725. }
  19726. if (string.match(parseTokenTimezone)) {
  19727. config._f += 'Z';
  19728. }
  19729. makeDateFromStringAndFormat(config);
  19730. } else {
  19731. config._isValid = false;
  19732. }
  19733. }
  19734. // date from iso format or fallback
  19735. function makeDateFromString(config) {
  19736. parseISO(config);
  19737. if (config._isValid === false) {
  19738. delete config._isValid;
  19739. moment.createFromInputFallback(config);
  19740. }
  19741. }
  19742. function makeDateFromInput(config) {
  19743. var input = config._i, matched;
  19744. if (input === undefined) {
  19745. config._d = new Date();
  19746. } else if (isDate(input)) {
  19747. config._d = new Date(+input);
  19748. } else if ((matched = aspNetJsonRegex.exec(input)) !== null) {
  19749. config._d = new Date(+matched[1]);
  19750. } else if (typeof input === 'string') {
  19751. makeDateFromString(config);
  19752. } else if (isArray(input)) {
  19753. config._a = input.slice(0);
  19754. dateFromConfig(config);
  19755. } else if (typeof(input) === 'object') {
  19756. dateFromObject(config);
  19757. } else if (typeof(input) === 'number') {
  19758. // from milliseconds
  19759. config._d = new Date(input);
  19760. } else {
  19761. moment.createFromInputFallback(config);
  19762. }
  19763. }
  19764. function makeDate(y, m, d, h, M, s, ms) {
  19765. //can't just apply() to create a date:
  19766. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  19767. var date = new Date(y, m, d, h, M, s, ms);
  19768. //the date constructor doesn't accept years < 1970
  19769. if (y < 1970) {
  19770. date.setFullYear(y);
  19771. }
  19772. return date;
  19773. }
  19774. function makeUTCDate(y) {
  19775. var date = new Date(Date.UTC.apply(null, arguments));
  19776. if (y < 1970) {
  19777. date.setUTCFullYear(y);
  19778. }
  19779. return date;
  19780. }
  19781. function parseWeekday(input, locale) {
  19782. if (typeof input === 'string') {
  19783. if (!isNaN(input)) {
  19784. input = parseInt(input, 10);
  19785. }
  19786. else {
  19787. input = locale.weekdaysParse(input);
  19788. if (typeof input !== 'number') {
  19789. return null;
  19790. }
  19791. }
  19792. }
  19793. return input;
  19794. }
  19795. /************************************
  19796. Relative Time
  19797. ************************************/
  19798. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  19799. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  19800. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  19801. }
  19802. function relativeTime(posNegDuration, withoutSuffix, locale) {
  19803. var duration = moment.duration(posNegDuration).abs(),
  19804. seconds = round(duration.as('s')),
  19805. minutes = round(duration.as('m')),
  19806. hours = round(duration.as('h')),
  19807. days = round(duration.as('d')),
  19808. months = round(duration.as('M')),
  19809. years = round(duration.as('y')),
  19810. args = seconds < relativeTimeThresholds.s && ['s', seconds] ||
  19811. minutes === 1 && ['m'] ||
  19812. minutes < relativeTimeThresholds.m && ['mm', minutes] ||
  19813. hours === 1 && ['h'] ||
  19814. hours < relativeTimeThresholds.h && ['hh', hours] ||
  19815. days === 1 && ['d'] ||
  19816. days < relativeTimeThresholds.d && ['dd', days] ||
  19817. months === 1 && ['M'] ||
  19818. months < relativeTimeThresholds.M && ['MM', months] ||
  19819. years === 1 && ['y'] || ['yy', years];
  19820. args[2] = withoutSuffix;
  19821. args[3] = +posNegDuration > 0;
  19822. args[4] = locale;
  19823. return substituteTimeAgo.apply({}, args);
  19824. }
  19825. /************************************
  19826. Week of Year
  19827. ************************************/
  19828. // firstDayOfWeek 0 = sun, 6 = sat
  19829. // the day of the week that starts the week
  19830. // (usually sunday or monday)
  19831. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  19832. // the first week is the week that contains the first
  19833. // of this day of the week
  19834. // (eg. ISO weeks use thursday (4))
  19835. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  19836. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  19837. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  19838. adjustedMoment;
  19839. if (daysToDayOfWeek > end) {
  19840. daysToDayOfWeek -= 7;
  19841. }
  19842. if (daysToDayOfWeek < end - 7) {
  19843. daysToDayOfWeek += 7;
  19844. }
  19845. adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd');
  19846. return {
  19847. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  19848. year: adjustedMoment.year()
  19849. };
  19850. }
  19851. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  19852. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  19853. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  19854. d = d === 0 ? 7 : d;
  19855. weekday = weekday != null ? weekday : firstDayOfWeek;
  19856. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  19857. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  19858. return {
  19859. year: dayOfYear > 0 ? year : year - 1,
  19860. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  19861. };
  19862. }
  19863. /************************************
  19864. Top Level Functions
  19865. ************************************/
  19866. function makeMoment(config) {
  19867. var input = config._i,
  19868. format = config._f;
  19869. config._locale = config._locale || moment.localeData(config._l);
  19870. if (input === null || (format === undefined && input === '')) {
  19871. return moment.invalid({nullInput: true});
  19872. }
  19873. if (typeof input === 'string') {
  19874. config._i = input = config._locale.preparse(input);
  19875. }
  19876. if (moment.isMoment(input)) {
  19877. return new Moment(input, true);
  19878. } else if (format) {
  19879. if (isArray(format)) {
  19880. makeDateFromStringAndArray(config);
  19881. } else {
  19882. makeDateFromStringAndFormat(config);
  19883. }
  19884. } else {
  19885. makeDateFromInput(config);
  19886. }
  19887. return new Moment(config);
  19888. }
  19889. moment = function (input, format, locale, strict) {
  19890. var c;
  19891. if (typeof(locale) === "boolean") {
  19892. strict = locale;
  19893. locale = undefined;
  19894. }
  19895. // object construction must be done this way.
  19896. // https://github.com/moment/moment/issues/1423
  19897. c = {};
  19898. c._isAMomentObject = true;
  19899. c._i = input;
  19900. c._f = format;
  19901. c._l = locale;
  19902. c._strict = strict;
  19903. c._isUTC = false;
  19904. c._pf = defaultParsingFlags();
  19905. return makeMoment(c);
  19906. };
  19907. moment.suppressDeprecationWarnings = false;
  19908. moment.createFromInputFallback = deprecate(
  19909. 'moment construction falls back to js Date. This is ' +
  19910. 'discouraged and will be removed in upcoming major ' +
  19911. 'release. Please refer to ' +
  19912. 'https://github.com/moment/moment/issues/1407 for more info.',
  19913. function (config) {
  19914. config._d = new Date(config._i);
  19915. }
  19916. );
  19917. // Pick a moment m from moments so that m[fn](other) is true for all
  19918. // other. This relies on the function fn to be transitive.
  19919. //
  19920. // moments should either be an array of moment objects or an array, whose
  19921. // first element is an array of moment objects.
  19922. function pickBy(fn, moments) {
  19923. var res, i;
  19924. if (moments.length === 1 && isArray(moments[0])) {
  19925. moments = moments[0];
  19926. }
  19927. if (!moments.length) {
  19928. return moment();
  19929. }
  19930. res = moments[0];
  19931. for (i = 1; i < moments.length; ++i) {
  19932. if (moments[i][fn](res)) {
  19933. res = moments[i];
  19934. }
  19935. }
  19936. return res;
  19937. }
  19938. moment.min = function () {
  19939. var args = [].slice.call(arguments, 0);
  19940. return pickBy('isBefore', args);
  19941. };
  19942. moment.max = function () {
  19943. var args = [].slice.call(arguments, 0);
  19944. return pickBy('isAfter', args);
  19945. };
  19946. // creating with utc
  19947. moment.utc = function (input, format, locale, strict) {
  19948. var c;
  19949. if (typeof(locale) === "boolean") {
  19950. strict = locale;
  19951. locale = undefined;
  19952. }
  19953. // object construction must be done this way.
  19954. // https://github.com/moment/moment/issues/1423
  19955. c = {};
  19956. c._isAMomentObject = true;
  19957. c._useUTC = true;
  19958. c._isUTC = true;
  19959. c._l = locale;
  19960. c._i = input;
  19961. c._f = format;
  19962. c._strict = strict;
  19963. c._pf = defaultParsingFlags();
  19964. return makeMoment(c).utc();
  19965. };
  19966. // creating with unix timestamp (in seconds)
  19967. moment.unix = function (input) {
  19968. return moment(input * 1000);
  19969. };
  19970. // duration
  19971. moment.duration = function (input, key) {
  19972. var duration = input,
  19973. // matching against regexp is expensive, do it on demand
  19974. match = null,
  19975. sign,
  19976. ret,
  19977. parseIso,
  19978. diffRes;
  19979. if (moment.isDuration(input)) {
  19980. duration = {
  19981. ms: input._milliseconds,
  19982. d: input._days,
  19983. M: input._months
  19984. };
  19985. } else if (typeof input === 'number') {
  19986. duration = {};
  19987. if (key) {
  19988. duration[key] = input;
  19989. } else {
  19990. duration.milliseconds = input;
  19991. }
  19992. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  19993. sign = (match[1] === '-') ? -1 : 1;
  19994. duration = {
  19995. y: 0,
  19996. d: toInt(match[DATE]) * sign,
  19997. h: toInt(match[HOUR]) * sign,
  19998. m: toInt(match[MINUTE]) * sign,
  19999. s: toInt(match[SECOND]) * sign,
  20000. ms: toInt(match[MILLISECOND]) * sign
  20001. };
  20002. } else if (!!(match = isoDurationRegex.exec(input))) {
  20003. sign = (match[1] === '-') ? -1 : 1;
  20004. parseIso = function (inp) {
  20005. // We'd normally use ~~inp for this, but unfortunately it also
  20006. // converts floats to ints.
  20007. // inp may be undefined, so careful calling replace on it.
  20008. var res = inp && parseFloat(inp.replace(',', '.'));
  20009. // apply sign while we're at it
  20010. return (isNaN(res) ? 0 : res) * sign;
  20011. };
  20012. duration = {
  20013. y: parseIso(match[2]),
  20014. M: parseIso(match[3]),
  20015. d: parseIso(match[4]),
  20016. h: parseIso(match[5]),
  20017. m: parseIso(match[6]),
  20018. s: parseIso(match[7]),
  20019. w: parseIso(match[8])
  20020. };
  20021. } else if (typeof duration === 'object' &&
  20022. ('from' in duration || 'to' in duration)) {
  20023. diffRes = momentsDifference(moment(duration.from), moment(duration.to));
  20024. duration = {};
  20025. duration.ms = diffRes.milliseconds;
  20026. duration.M = diffRes.months;
  20027. }
  20028. ret = new Duration(duration);
  20029. if (moment.isDuration(input) && input.hasOwnProperty('_locale')) {
  20030. ret._locale = input._locale;
  20031. }
  20032. return ret;
  20033. };
  20034. // version number
  20035. moment.version = VERSION;
  20036. // default format
  20037. moment.defaultFormat = isoFormat;
  20038. // constant that refers to the ISO standard
  20039. moment.ISO_8601 = function () {};
  20040. // Plugins that add properties should also add the key here (null value),
  20041. // so we can properly clone ourselves.
  20042. moment.momentProperties = momentProperties;
  20043. // This function will be called whenever a moment is mutated.
  20044. // It is intended to keep the offset in sync with the timezone.
  20045. moment.updateOffset = function () {};
  20046. // This function allows you to set a threshold for relative time strings
  20047. moment.relativeTimeThreshold = function (threshold, limit) {
  20048. if (relativeTimeThresholds[threshold] === undefined) {
  20049. return false;
  20050. }
  20051. if (limit === undefined) {
  20052. return relativeTimeThresholds[threshold];
  20053. }
  20054. relativeTimeThresholds[threshold] = limit;
  20055. return true;
  20056. };
  20057. moment.lang = deprecate(
  20058. "moment.lang is deprecated. Use moment.locale instead.",
  20059. function (key, value) {
  20060. return moment.locale(key, value);
  20061. }
  20062. );
  20063. // This function will load locale and then set the global locale. If
  20064. // no arguments are passed in, it will simply return the current global
  20065. // locale key.
  20066. moment.locale = function (key, values) {
  20067. var data;
  20068. if (key) {
  20069. if (typeof(values) !== "undefined") {
  20070. data = moment.defineLocale(key, values);
  20071. }
  20072. else {
  20073. data = moment.localeData(key);
  20074. }
  20075. if (data) {
  20076. moment.duration._locale = moment._locale = data;
  20077. }
  20078. }
  20079. return moment._locale._abbr;
  20080. };
  20081. moment.defineLocale = function (name, values) {
  20082. if (values !== null) {
  20083. values.abbr = name;
  20084. if (!locales[name]) {
  20085. locales[name] = new Locale();
  20086. }
  20087. locales[name].set(values);
  20088. // backwards compat for now: also set the locale
  20089. moment.locale(name);
  20090. return locales[name];
  20091. } else {
  20092. // useful for testing
  20093. delete locales[name];
  20094. return null;
  20095. }
  20096. };
  20097. moment.langData = deprecate(
  20098. "moment.langData is deprecated. Use moment.localeData instead.",
  20099. function (key) {
  20100. return moment.localeData(key);
  20101. }
  20102. );
  20103. // returns locale data
  20104. moment.localeData = function (key) {
  20105. var locale;
  20106. if (key && key._locale && key._locale._abbr) {
  20107. key = key._locale._abbr;
  20108. }
  20109. if (!key) {
  20110. return moment._locale;
  20111. }
  20112. if (!isArray(key)) {
  20113. //short-circuit everything else
  20114. locale = loadLocale(key);
  20115. if (locale) {
  20116. return locale;
  20117. }
  20118. key = [key];
  20119. }
  20120. return chooseLocale(key);
  20121. };
  20122. // compare moment object
  20123. moment.isMoment = function (obj) {
  20124. return obj instanceof Moment ||
  20125. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  20126. };
  20127. // for typechecking Duration objects
  20128. moment.isDuration = function (obj) {
  20129. return obj instanceof Duration;
  20130. };
  20131. for (i = lists.length - 1; i >= 0; --i) {
  20132. makeList(lists[i]);
  20133. }
  20134. moment.normalizeUnits = function (units) {
  20135. return normalizeUnits(units);
  20136. };
  20137. moment.invalid = function (flags) {
  20138. var m = moment.utc(NaN);
  20139. if (flags != null) {
  20140. extend(m._pf, flags);
  20141. }
  20142. else {
  20143. m._pf.userInvalidated = true;
  20144. }
  20145. return m;
  20146. };
  20147. moment.parseZone = function () {
  20148. return moment.apply(null, arguments).parseZone();
  20149. };
  20150. moment.parseTwoDigitYear = function (input) {
  20151. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  20152. };
  20153. /************************************
  20154. Moment Prototype
  20155. ************************************/
  20156. extend(moment.fn = Moment.prototype, {
  20157. clone : function () {
  20158. return moment(this);
  20159. },
  20160. valueOf : function () {
  20161. return +this._d + ((this._offset || 0) * 60000);
  20162. },
  20163. unix : function () {
  20164. return Math.floor(+this / 1000);
  20165. },
  20166. toString : function () {
  20167. return this.clone().locale('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  20168. },
  20169. toDate : function () {
  20170. return this._offset ? new Date(+this) : this._d;
  20171. },
  20172. toISOString : function () {
  20173. var m = moment(this).utc();
  20174. if (0 < m.year() && m.year() <= 9999) {
  20175. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  20176. } else {
  20177. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  20178. }
  20179. },
  20180. toArray : function () {
  20181. var m = this;
  20182. return [
  20183. m.year(),
  20184. m.month(),
  20185. m.date(),
  20186. m.hours(),
  20187. m.minutes(),
  20188. m.seconds(),
  20189. m.milliseconds()
  20190. ];
  20191. },
  20192. isValid : function () {
  20193. return isValid(this);
  20194. },
  20195. isDSTShifted : function () {
  20196. if (this._a) {
  20197. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  20198. }
  20199. return false;
  20200. },
  20201. parsingFlags : function () {
  20202. return extend({}, this._pf);
  20203. },
  20204. invalidAt: function () {
  20205. return this._pf.overflow;
  20206. },
  20207. utc : function (keepLocalTime) {
  20208. return this.zone(0, keepLocalTime);
  20209. },
  20210. local : function (keepLocalTime) {
  20211. if (this._isUTC) {
  20212. this.zone(0, keepLocalTime);
  20213. this._isUTC = false;
  20214. if (keepLocalTime) {
  20215. this.add(this._d.getTimezoneOffset(), 'm');
  20216. }
  20217. }
  20218. return this;
  20219. },
  20220. format : function (inputString) {
  20221. var output = formatMoment(this, inputString || moment.defaultFormat);
  20222. return this.localeData().postformat(output);
  20223. },
  20224. add : createAdder(1, 'add'),
  20225. subtract : createAdder(-1, 'subtract'),
  20226. diff : function (input, units, asFloat) {
  20227. var that = makeAs(input, this),
  20228. zoneDiff = (this.zone() - that.zone()) * 6e4,
  20229. diff, output;
  20230. units = normalizeUnits(units);
  20231. if (units === 'year' || units === 'month') {
  20232. // average number of days in the months in the given dates
  20233. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  20234. // difference in months
  20235. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  20236. // adjust by taking difference in days, average number of days
  20237. // and dst in the given months.
  20238. output += ((this - moment(this).startOf('month')) -
  20239. (that - moment(that).startOf('month'))) / diff;
  20240. // same as above but with zones, to negate all dst
  20241. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  20242. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  20243. if (units === 'year') {
  20244. output = output / 12;
  20245. }
  20246. } else {
  20247. diff = (this - that);
  20248. output = units === 'second' ? diff / 1e3 : // 1000
  20249. units === 'minute' ? diff / 6e4 : // 1000 * 60
  20250. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  20251. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  20252. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  20253. diff;
  20254. }
  20255. return asFloat ? output : absRound(output);
  20256. },
  20257. from : function (time, withoutSuffix) {
  20258. return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  20259. },
  20260. fromNow : function (withoutSuffix) {
  20261. return this.from(moment(), withoutSuffix);
  20262. },
  20263. calendar : function (time) {
  20264. // We want to compare the start of today, vs this.
  20265. // Getting start-of-today depends on whether we're zone'd or not.
  20266. var now = time || moment(),
  20267. sod = makeAs(now, this).startOf('day'),
  20268. diff = this.diff(sod, 'days', true),
  20269. format = diff < -6 ? 'sameElse' :
  20270. diff < -1 ? 'lastWeek' :
  20271. diff < 0 ? 'lastDay' :
  20272. diff < 1 ? 'sameDay' :
  20273. diff < 2 ? 'nextDay' :
  20274. diff < 7 ? 'nextWeek' : 'sameElse';
  20275. return this.format(this.localeData().calendar(format, this));
  20276. },
  20277. isLeapYear : function () {
  20278. return isLeapYear(this.year());
  20279. },
  20280. isDST : function () {
  20281. return (this.zone() < this.clone().month(0).zone() ||
  20282. this.zone() < this.clone().month(5).zone());
  20283. },
  20284. day : function (input) {
  20285. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  20286. if (input != null) {
  20287. input = parseWeekday(input, this.localeData());
  20288. return this.add(input - day, 'd');
  20289. } else {
  20290. return day;
  20291. }
  20292. },
  20293. month : makeAccessor('Month', true),
  20294. startOf : function (units) {
  20295. units = normalizeUnits(units);
  20296. // the following switch intentionally omits break keywords
  20297. // to utilize falling through the cases.
  20298. switch (units) {
  20299. case 'year':
  20300. this.month(0);
  20301. /* falls through */
  20302. case 'quarter':
  20303. case 'month':
  20304. this.date(1);
  20305. /* falls through */
  20306. case 'week':
  20307. case 'isoWeek':
  20308. case 'day':
  20309. this.hours(0);
  20310. /* falls through */
  20311. case 'hour':
  20312. this.minutes(0);
  20313. /* falls through */
  20314. case 'minute':
  20315. this.seconds(0);
  20316. /* falls through */
  20317. case 'second':
  20318. this.milliseconds(0);
  20319. /* falls through */
  20320. }
  20321. // weeks are a special case
  20322. if (units === 'week') {
  20323. this.weekday(0);
  20324. } else if (units === 'isoWeek') {
  20325. this.isoWeekday(1);
  20326. }
  20327. // quarters are also special
  20328. if (units === 'quarter') {
  20329. this.month(Math.floor(this.month() / 3) * 3);
  20330. }
  20331. return this;
  20332. },
  20333. endOf: function (units) {
  20334. units = normalizeUnits(units);
  20335. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  20336. },
  20337. isAfter: function (input, units) {
  20338. units = typeof units !== 'undefined' ? units : 'millisecond';
  20339. return +this.clone().startOf(units) > +moment(input).startOf(units);
  20340. },
  20341. isBefore: function (input, units) {
  20342. units = typeof units !== 'undefined' ? units : 'millisecond';
  20343. return +this.clone().startOf(units) < +moment(input).startOf(units);
  20344. },
  20345. isSame: function (input, units) {
  20346. units = units || 'ms';
  20347. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  20348. },
  20349. min: deprecate(
  20350. 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
  20351. function (other) {
  20352. other = moment.apply(null, arguments);
  20353. return other < this ? this : other;
  20354. }
  20355. ),
  20356. max: deprecate(
  20357. 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
  20358. function (other) {
  20359. other = moment.apply(null, arguments);
  20360. return other > this ? this : other;
  20361. }
  20362. ),
  20363. // keepLocalTime = true means only change the timezone, without
  20364. // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]-->
  20365. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone
  20366. // +0200, so we adjust the time as needed, to be valid.
  20367. //
  20368. // Keeping the time actually adds/subtracts (one hour)
  20369. // from the actual represented time. That is why we call updateOffset
  20370. // a second time. In case it wants us to change the offset again
  20371. // _changeInProgress == true case, then we have to adjust, because
  20372. // there is no such time in the given timezone.
  20373. zone : function (input, keepLocalTime) {
  20374. var offset = this._offset || 0,
  20375. localAdjust;
  20376. if (input != null) {
  20377. if (typeof input === 'string') {
  20378. input = timezoneMinutesFromString(input);
  20379. }
  20380. if (Math.abs(input) < 16) {
  20381. input = input * 60;
  20382. }
  20383. if (!this._isUTC && keepLocalTime) {
  20384. localAdjust = this._d.getTimezoneOffset();
  20385. }
  20386. this._offset = input;
  20387. this._isUTC = true;
  20388. if (localAdjust != null) {
  20389. this.subtract(localAdjust, 'm');
  20390. }
  20391. if (offset !== input) {
  20392. if (!keepLocalTime || this._changeInProgress) {
  20393. addOrSubtractDurationFromMoment(this,
  20394. moment.duration(offset - input, 'm'), 1, false);
  20395. } else if (!this._changeInProgress) {
  20396. this._changeInProgress = true;
  20397. moment.updateOffset(this, true);
  20398. this._changeInProgress = null;
  20399. }
  20400. }
  20401. } else {
  20402. return this._isUTC ? offset : this._d.getTimezoneOffset();
  20403. }
  20404. return this;
  20405. },
  20406. zoneAbbr : function () {
  20407. return this._isUTC ? 'UTC' : '';
  20408. },
  20409. zoneName : function () {
  20410. return this._isUTC ? 'Coordinated Universal Time' : '';
  20411. },
  20412. parseZone : function () {
  20413. if (this._tzm) {
  20414. this.zone(this._tzm);
  20415. } else if (typeof this._i === 'string') {
  20416. this.zone(this._i);
  20417. }
  20418. return this;
  20419. },
  20420. hasAlignedHourOffset : function (input) {
  20421. if (!input) {
  20422. input = 0;
  20423. }
  20424. else {
  20425. input = moment(input).zone();
  20426. }
  20427. return (this.zone() - input) % 60 === 0;
  20428. },
  20429. daysInMonth : function () {
  20430. return daysInMonth(this.year(), this.month());
  20431. },
  20432. dayOfYear : function (input) {
  20433. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  20434. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  20435. },
  20436. quarter : function (input) {
  20437. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  20438. },
  20439. weekYear : function (input) {
  20440. var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
  20441. return input == null ? year : this.add((input - year), 'y');
  20442. },
  20443. isoWeekYear : function (input) {
  20444. var year = weekOfYear(this, 1, 4).year;
  20445. return input == null ? year : this.add((input - year), 'y');
  20446. },
  20447. week : function (input) {
  20448. var week = this.localeData().week(this);
  20449. return input == null ? week : this.add((input - week) * 7, 'd');
  20450. },
  20451. isoWeek : function (input) {
  20452. var week = weekOfYear(this, 1, 4).week;
  20453. return input == null ? week : this.add((input - week) * 7, 'd');
  20454. },
  20455. weekday : function (input) {
  20456. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  20457. return input == null ? weekday : this.add(input - weekday, 'd');
  20458. },
  20459. isoWeekday : function (input) {
  20460. // behaves the same as moment#day except
  20461. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  20462. // as a setter, sunday should belong to the previous week.
  20463. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  20464. },
  20465. isoWeeksInYear : function () {
  20466. return weeksInYear(this.year(), 1, 4);
  20467. },
  20468. weeksInYear : function () {
  20469. var weekInfo = this.localeData()._week;
  20470. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  20471. },
  20472. get : function (units) {
  20473. units = normalizeUnits(units);
  20474. return this[units]();
  20475. },
  20476. set : function (units, value) {
  20477. units = normalizeUnits(units);
  20478. if (typeof this[units] === 'function') {
  20479. this[units](value);
  20480. }
  20481. return this;
  20482. },
  20483. // If passed a locale key, it will set the locale for this
  20484. // instance. Otherwise, it will return the locale configuration
  20485. // variables for this instance.
  20486. locale : function (key) {
  20487. if (key === undefined) {
  20488. return this._locale._abbr;
  20489. } else {
  20490. this._locale = moment.localeData(key);
  20491. return this;
  20492. }
  20493. },
  20494. lang : deprecate(
  20495. "moment().lang() is deprecated. Use moment().localeData() instead.",
  20496. function (key) {
  20497. if (key === undefined) {
  20498. return this.localeData();
  20499. } else {
  20500. this._locale = moment.localeData(key);
  20501. return this;
  20502. }
  20503. }
  20504. ),
  20505. localeData : function () {
  20506. return this._locale;
  20507. }
  20508. });
  20509. function rawMonthSetter(mom, value) {
  20510. var dayOfMonth;
  20511. // TODO: Move this out of here!
  20512. if (typeof value === 'string') {
  20513. value = mom.localeData().monthsParse(value);
  20514. // TODO: Another silent failure?
  20515. if (typeof value !== 'number') {
  20516. return mom;
  20517. }
  20518. }
  20519. dayOfMonth = Math.min(mom.date(),
  20520. daysInMonth(mom.year(), value));
  20521. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  20522. return mom;
  20523. }
  20524. function rawGetter(mom, unit) {
  20525. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  20526. }
  20527. function rawSetter(mom, unit, value) {
  20528. if (unit === 'Month') {
  20529. return rawMonthSetter(mom, value);
  20530. } else {
  20531. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  20532. }
  20533. }
  20534. function makeAccessor(unit, keepTime) {
  20535. return function (value) {
  20536. if (value != null) {
  20537. rawSetter(this, unit, value);
  20538. moment.updateOffset(this, keepTime);
  20539. return this;
  20540. } else {
  20541. return rawGetter(this, unit);
  20542. }
  20543. };
  20544. }
  20545. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  20546. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  20547. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  20548. // Setting the hour should keep the time, because the user explicitly
  20549. // specified which hour he wants. So trying to maintain the same hour (in
  20550. // a new timezone) makes sense. Adding/subtracting hours does not follow
  20551. // this rule.
  20552. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  20553. // moment.fn.month is defined separately
  20554. moment.fn.date = makeAccessor('Date', true);
  20555. moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true));
  20556. moment.fn.year = makeAccessor('FullYear', true);
  20557. moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true));
  20558. // add plural methods
  20559. moment.fn.days = moment.fn.day;
  20560. moment.fn.months = moment.fn.month;
  20561. moment.fn.weeks = moment.fn.week;
  20562. moment.fn.isoWeeks = moment.fn.isoWeek;
  20563. moment.fn.quarters = moment.fn.quarter;
  20564. // add aliased format methods
  20565. moment.fn.toJSON = moment.fn.toISOString;
  20566. /************************************
  20567. Duration Prototype
  20568. ************************************/
  20569. function daysToYears (days) {
  20570. // 400 years have 146097 days (taking into account leap year rules)
  20571. return days * 400 / 146097;
  20572. }
  20573. function yearsToDays (years) {
  20574. // years * 365 + absRound(years / 4) -
  20575. // absRound(years / 100) + absRound(years / 400);
  20576. return years * 146097 / 400;
  20577. }
  20578. extend(moment.duration.fn = Duration.prototype, {
  20579. _bubble : function () {
  20580. var milliseconds = this._milliseconds,
  20581. days = this._days,
  20582. months = this._months,
  20583. data = this._data,
  20584. seconds, minutes, hours, years = 0;
  20585. // The following code bubbles up values, see the tests for
  20586. // examples of what that means.
  20587. data.milliseconds = milliseconds % 1000;
  20588. seconds = absRound(milliseconds / 1000);
  20589. data.seconds = seconds % 60;
  20590. minutes = absRound(seconds / 60);
  20591. data.minutes = minutes % 60;
  20592. hours = absRound(minutes / 60);
  20593. data.hours = hours % 24;
  20594. days += absRound(hours / 24);
  20595. // Accurately convert days to years, assume start from year 0.
  20596. years = absRound(daysToYears(days));
  20597. days -= absRound(yearsToDays(years));
  20598. // 30 days to a month
  20599. // TODO (iskren): Use anchor date (like 1st Jan) to compute this.
  20600. months += absRound(days / 30);
  20601. days %= 30;
  20602. // 12 months -> 1 year
  20603. years += absRound(months / 12);
  20604. months %= 12;
  20605. data.days = days;
  20606. data.months = months;
  20607. data.years = years;
  20608. },
  20609. abs : function () {
  20610. this._milliseconds = Math.abs(this._milliseconds);
  20611. this._days = Math.abs(this._days);
  20612. this._months = Math.abs(this._months);
  20613. this._data.milliseconds = Math.abs(this._data.milliseconds);
  20614. this._data.seconds = Math.abs(this._data.seconds);
  20615. this._data.minutes = Math.abs(this._data.minutes);
  20616. this._data.hours = Math.abs(this._data.hours);
  20617. this._data.months = Math.abs(this._data.months);
  20618. this._data.years = Math.abs(this._data.years);
  20619. return this;
  20620. },
  20621. weeks : function () {
  20622. return absRound(this.days() / 7);
  20623. },
  20624. valueOf : function () {
  20625. return this._milliseconds +
  20626. this._days * 864e5 +
  20627. (this._months % 12) * 2592e6 +
  20628. toInt(this._months / 12) * 31536e6;
  20629. },
  20630. humanize : function (withSuffix) {
  20631. var output = relativeTime(this, !withSuffix, this.localeData());
  20632. if (withSuffix) {
  20633. output = this.localeData().pastFuture(+this, output);
  20634. }
  20635. return this.localeData().postformat(output);
  20636. },
  20637. add : function (input, val) {
  20638. // supports only 2.0-style add(1, 's') or add(moment)
  20639. var dur = moment.duration(input, val);
  20640. this._milliseconds += dur._milliseconds;
  20641. this._days += dur._days;
  20642. this._months += dur._months;
  20643. this._bubble();
  20644. return this;
  20645. },
  20646. subtract : function (input, val) {
  20647. var dur = moment.duration(input, val);
  20648. this._milliseconds -= dur._milliseconds;
  20649. this._days -= dur._days;
  20650. this._months -= dur._months;
  20651. this._bubble();
  20652. return this;
  20653. },
  20654. get : function (units) {
  20655. units = normalizeUnits(units);
  20656. return this[units.toLowerCase() + 's']();
  20657. },
  20658. as : function (units) {
  20659. var days, months;
  20660. units = normalizeUnits(units);
  20661. days = this._days + this._milliseconds / 864e5;
  20662. if (units === 'month' || units === 'year') {
  20663. months = this._months + daysToYears(days) * 12;
  20664. return units === 'month' ? months : months / 12;
  20665. } else {
  20666. days += yearsToDays(this._months / 12);
  20667. switch (units) {
  20668. case 'week': return days / 7;
  20669. case 'day': return days;
  20670. case 'hour': return days * 24;
  20671. case 'minute': return days * 24 * 60;
  20672. case 'second': return days * 24 * 60 * 60;
  20673. case 'millisecond': return days * 24 * 60 * 60 * 1000;
  20674. default: throw new Error('Unknown unit ' + units);
  20675. }
  20676. }
  20677. },
  20678. lang : moment.fn.lang,
  20679. locale : moment.fn.locale,
  20680. toIsoString : deprecate(
  20681. "toIsoString() is deprecated. Please use toISOString() instead " +
  20682. "(notice the capitals)",
  20683. function () {
  20684. return this.toISOString();
  20685. }
  20686. ),
  20687. toISOString : function () {
  20688. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  20689. var years = Math.abs(this.years()),
  20690. months = Math.abs(this.months()),
  20691. days = Math.abs(this.days()),
  20692. hours = Math.abs(this.hours()),
  20693. minutes = Math.abs(this.minutes()),
  20694. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  20695. if (!this.asSeconds()) {
  20696. // this is the same as C#'s (Noda) and python (isodate)...
  20697. // but not other JS (goog.date)
  20698. return 'P0D';
  20699. }
  20700. return (this.asSeconds() < 0 ? '-' : '') +
  20701. 'P' +
  20702. (years ? years + 'Y' : '') +
  20703. (months ? months + 'M' : '') +
  20704. (days ? days + 'D' : '') +
  20705. ((hours || minutes || seconds) ? 'T' : '') +
  20706. (hours ? hours + 'H' : '') +
  20707. (minutes ? minutes + 'M' : '') +
  20708. (seconds ? seconds + 'S' : '');
  20709. },
  20710. localeData : function () {
  20711. return this._locale;
  20712. }
  20713. });
  20714. function makeDurationGetter(name) {
  20715. moment.duration.fn[name] = function () {
  20716. return this._data[name];
  20717. };
  20718. }
  20719. for (i in unitMillisecondFactors) {
  20720. if (unitMillisecondFactors.hasOwnProperty(i)) {
  20721. makeDurationGetter(i.toLowerCase());
  20722. }
  20723. }
  20724. moment.duration.fn.asMilliseconds = function () {
  20725. return this.as('ms');
  20726. };
  20727. moment.duration.fn.asSeconds = function () {
  20728. return this.as('s');
  20729. };
  20730. moment.duration.fn.asMinutes = function () {
  20731. return this.as('m');
  20732. };
  20733. moment.duration.fn.asHours = function () {
  20734. return this.as('h');
  20735. };
  20736. moment.duration.fn.asDays = function () {
  20737. return this.as('d');
  20738. };
  20739. moment.duration.fn.asWeeks = function () {
  20740. return this.as('weeks');
  20741. };
  20742. moment.duration.fn.asMonths = function () {
  20743. return this.as('M');
  20744. };
  20745. moment.duration.fn.asYears = function () {
  20746. return this.as('y');
  20747. };
  20748. /************************************
  20749. Default Locale
  20750. ************************************/
  20751. // Set default locale, other locale will inherit from English.
  20752. moment.locale('en', {
  20753. ordinal : function (number) {
  20754. var b = number % 10,
  20755. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  20756. (b === 1) ? 'st' :
  20757. (b === 2) ? 'nd' :
  20758. (b === 3) ? 'rd' : 'th';
  20759. return number + output;
  20760. }
  20761. });
  20762. /* EMBED_LOCALES */
  20763. /************************************
  20764. Exposing Moment
  20765. ************************************/
  20766. function makeGlobal(shouldDeprecate) {
  20767. /*global ender:false */
  20768. if (typeof ender !== 'undefined') {
  20769. return;
  20770. }
  20771. oldGlobalMoment = globalScope.moment;
  20772. if (shouldDeprecate) {
  20773. globalScope.moment = deprecate(
  20774. 'Accessing Moment through the global scope is ' +
  20775. 'deprecated, and will be removed in an upcoming ' +
  20776. 'release.',
  20777. moment);
  20778. } else {
  20779. globalScope.moment = moment;
  20780. }
  20781. }
  20782. // CommonJS module is defined
  20783. if (hasModule) {
  20784. module.exports = moment;
  20785. } else if (true) {
  20786. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function (require, exports, module) {
  20787. if (module.config && module.config() && module.config().noGlobal === true) {
  20788. // release the global variable
  20789. globalScope.moment = oldGlobalMoment;
  20790. }
  20791. return moment;
  20792. }.call(exports, __webpack_require__, exports, module)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  20793. makeGlobal(true);
  20794. } else {
  20795. makeGlobal();
  20796. }
  20797. }).call(this);
  20798. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(58)(module)))
  20799. /***/ },
  20800. /* 49 */
  20801. /***/ function(module, exports, __webpack_require__) {
  20802. var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20
  20803. * http://eightmedia.github.io/hammer.js
  20804. *
  20805. * Copyright (c) 2014 Jorik Tangelder <j.tangelder@gmail.com>;
  20806. * Licensed under the MIT license */
  20807. (function(window, undefined) {
  20808. 'use strict';
  20809. /**
  20810. * @main
  20811. * @module hammer
  20812. *
  20813. * @class Hammer
  20814. * @static
  20815. */
  20816. /**
  20817. * Hammer, use this to create instances
  20818. * ````
  20819. * var hammertime = new Hammer(myElement);
  20820. * ````
  20821. *
  20822. * @method Hammer
  20823. * @param {HTMLElement} element
  20824. * @param {Object} [options={}]
  20825. * @return {Hammer.Instance}
  20826. */
  20827. var Hammer = function Hammer(element, options) {
  20828. return new Hammer.Instance(element, options || {});
  20829. };
  20830. /**
  20831. * version, as defined in package.json
  20832. * the value will be set at each build
  20833. * @property VERSION
  20834. * @final
  20835. * @type {String}
  20836. */
  20837. Hammer.VERSION = '1.1.3';
  20838. /**
  20839. * default settings.
  20840. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled
  20841. * by setting it's name (like `swipe`) to false.
  20842. * You can set the defaults for all instances by changing this object before creating an instance.
  20843. * @example
  20844. * ````
  20845. * Hammer.defaults.drag = false;
  20846. * Hammer.defaults.behavior.touchAction = 'pan-y';
  20847. * delete Hammer.defaults.behavior.userSelect;
  20848. * ````
  20849. * @property defaults
  20850. * @type {Object}
  20851. */
  20852. Hammer.defaults = {
  20853. /**
  20854. * this setting object adds styles and attributes to the element to prevent the browser from doing
  20855. * its native behavior. The css properties are auto prefixed for the browsers when needed.
  20856. * @property defaults.behavior
  20857. * @type {Object}
  20858. */
  20859. behavior: {
  20860. /**
  20861. * Disables text selection to improve the dragging gesture. When the value is `none` it also sets
  20862. * `onselectstart=false` for IE on the element. Mainly for desktop browsers.
  20863. * @property defaults.behavior.userSelect
  20864. * @type {String}
  20865. * @default 'none'
  20866. */
  20867. userSelect: 'none',
  20868. /**
  20869. * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming).
  20870. * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event.
  20871. * @property defaults.behavior.touchAction
  20872. * @type {String}
  20873. * @default: 'pan-y'
  20874. */
  20875. touchAction: 'pan-y',
  20876. /**
  20877. * Disables the default callout shown when you touch and hold a touch target.
  20878. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  20879. * a callout containing information about the link. This property allows you to disable that callout.
  20880. * @property defaults.behavior.touchCallout
  20881. * @type {String}
  20882. * @default 'none'
  20883. */
  20884. touchCallout: 'none',
  20885. /**
  20886. * Specifies whether zooming is enabled. Used by IE10>
  20887. * @property defaults.behavior.contentZooming
  20888. * @type {String}
  20889. * @default 'none'
  20890. */
  20891. contentZooming: 'none',
  20892. /**
  20893. * Specifies that an entire element should be draggable instead of its contents.
  20894. * Mainly for desktop browsers.
  20895. * @property defaults.behavior.userDrag
  20896. * @type {String}
  20897. * @default 'none'
  20898. */
  20899. userDrag: 'none',
  20900. /**
  20901. * Overrides the highlight color shown when the user taps a link or a JavaScript
  20902. * clickable element in Safari on iPhone. This property obeys the alpha value, if specified.
  20903. *
  20904. * If you don't specify an alpha value, Safari on iPhone applies a default alpha value
  20905. * to the color. To disable tap highlighting, set the alpha value to 0 (invisible).
  20906. * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped.
  20907. * @property defaults.behavior.tapHighlightColor
  20908. * @type {String}
  20909. * @default 'rgba(0,0,0,0)'
  20910. */
  20911. tapHighlightColor: 'rgba(0,0,0,0)'
  20912. }
  20913. };
  20914. /**
  20915. * hammer document where the base events are added at
  20916. * @property DOCUMENT
  20917. * @type {HTMLElement}
  20918. * @default window.document
  20919. */
  20920. Hammer.DOCUMENT = document;
  20921. /**
  20922. * detect support for pointer events
  20923. * @property HAS_POINTEREVENTS
  20924. * @type {Boolean}
  20925. */
  20926. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  20927. /**
  20928. * detect support for touch events
  20929. * @property HAS_TOUCHEVENTS
  20930. * @type {Boolean}
  20931. */
  20932. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  20933. /**
  20934. * detect mobile browsers
  20935. * @property IS_MOBILE
  20936. * @type {Boolean}
  20937. */
  20938. Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent);
  20939. /**
  20940. * detect if we want to support mouseevents at all
  20941. * @property NO_MOUSEEVENTS
  20942. * @type {Boolean}
  20943. */
  20944. Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS;
  20945. /**
  20946. * interval in which Hammer recalculates current velocity/direction/angle in ms
  20947. * @property CALCULATE_INTERVAL
  20948. * @type {Number}
  20949. * @default 25
  20950. */
  20951. Hammer.CALCULATE_INTERVAL = 25;
  20952. /**
  20953. * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup`
  20954. * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`)
  20955. * @property EVENT_TYPES
  20956. * @private
  20957. * @writeOnce
  20958. * @type {Object}
  20959. */
  20960. var EVENT_TYPES = {};
  20961. /**
  20962. * direction strings, for safe comparisons
  20963. * @property DIRECTION_DOWN|LEFT|UP|RIGHT
  20964. * @final
  20965. * @type {String}
  20966. * @default 'down' 'left' 'up' 'right'
  20967. */
  20968. var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down';
  20969. var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left';
  20970. var DIRECTION_UP = Hammer.DIRECTION_UP = 'up';
  20971. var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right';
  20972. /**
  20973. * pointertype strings, for safe comparisons
  20974. * @property POINTER_MOUSE|TOUCH|PEN
  20975. * @final
  20976. * @type {String}
  20977. * @default 'mouse' 'touch' 'pen'
  20978. */
  20979. var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse';
  20980. var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch';
  20981. var POINTER_PEN = Hammer.POINTER_PEN = 'pen';
  20982. /**
  20983. * eventtypes
  20984. * @property EVENT_START|MOVE|END|RELEASE|TOUCH
  20985. * @final
  20986. * @type {String}
  20987. * @default 'start' 'change' 'move' 'end' 'release' 'touch'
  20988. */
  20989. var EVENT_START = Hammer.EVENT_START = 'start';
  20990. var EVENT_MOVE = Hammer.EVENT_MOVE = 'move';
  20991. var EVENT_END = Hammer.EVENT_END = 'end';
  20992. var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release';
  20993. var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch';
  20994. /**
  20995. * if the window events are set...
  20996. * @property READY
  20997. * @writeOnce
  20998. * @type {Boolean}
  20999. * @default false
  21000. */
  21001. Hammer.READY = false;
  21002. /**
  21003. * plugins namespace
  21004. * @property plugins
  21005. * @type {Object}
  21006. */
  21007. Hammer.plugins = Hammer.plugins || {};
  21008. /**
  21009. * gestures namespace
  21010. * see `/gestures` for the definitions
  21011. * @property gestures
  21012. * @type {Object}
  21013. */
  21014. Hammer.gestures = Hammer.gestures || {};
  21015. /**
  21016. * setup events to detect gestures on the document
  21017. * this function is called when creating an new instance
  21018. * @private
  21019. */
  21020. function setup() {
  21021. if(Hammer.READY) {
  21022. return;
  21023. }
  21024. // find what eventtypes we add listeners to
  21025. Event.determineEventTypes();
  21026. // Register all gestures inside Hammer.gestures
  21027. Utils.each(Hammer.gestures, function(gesture) {
  21028. Detection.register(gesture);
  21029. });
  21030. // Add touch events on the document
  21031. Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect);
  21032. Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect);
  21033. // Hammer is ready...!
  21034. Hammer.READY = true;
  21035. }
  21036. /**
  21037. * @module hammer
  21038. *
  21039. * @class Utils
  21040. * @static
  21041. */
  21042. var Utils = Hammer.utils = {
  21043. /**
  21044. * extend method, could also be used for cloning when `dest` is an empty object.
  21045. * changes the dest object
  21046. * @method extend
  21047. * @param {Object} dest
  21048. * @param {Object} src
  21049. * @param {Boolean} [merge=false] do a merge
  21050. * @return {Object} dest
  21051. */
  21052. extend: function extend(dest, src, merge) {
  21053. for(var key in src) {
  21054. if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) {
  21055. continue;
  21056. }
  21057. dest[key] = src[key];
  21058. }
  21059. return dest;
  21060. },
  21061. /**
  21062. * simple addEventListener wrapper
  21063. * @method on
  21064. * @param {HTMLElement} element
  21065. * @param {String} type
  21066. * @param {Function} handler
  21067. */
  21068. on: function on(element, type, handler) {
  21069. element.addEventListener(type, handler, false);
  21070. },
  21071. /**
  21072. * simple removeEventListener wrapper
  21073. * @method off
  21074. * @param {HTMLElement} element
  21075. * @param {String} type
  21076. * @param {Function} handler
  21077. */
  21078. off: function off(element, type, handler) {
  21079. element.removeEventListener(type, handler, false);
  21080. },
  21081. /**
  21082. * forEach over arrays and objects
  21083. * @method each
  21084. * @param {Object|Array} obj
  21085. * @param {Function} iterator
  21086. * @param {any} iterator.item
  21087. * @param {Number} iterator.index
  21088. * @param {Object|Array} iterator.obj the source object
  21089. * @param {Object} context value to use as `this` in the iterator
  21090. */
  21091. each: function each(obj, iterator, context) {
  21092. var i, len;
  21093. // native forEach on arrays
  21094. if('forEach' in obj) {
  21095. obj.forEach(iterator, context);
  21096. // arrays
  21097. } else if(obj.length !== undefined) {
  21098. for(i = 0, len = obj.length; i < len; i++) {
  21099. if(iterator.call(context, obj[i], i, obj) === false) {
  21100. return;
  21101. }
  21102. }
  21103. // objects
  21104. } else {
  21105. for(i in obj) {
  21106. if(obj.hasOwnProperty(i) &&
  21107. iterator.call(context, obj[i], i, obj) === false) {
  21108. return;
  21109. }
  21110. }
  21111. }
  21112. },
  21113. /**
  21114. * find if a string contains the string using indexOf
  21115. * @method inStr
  21116. * @param {String} src
  21117. * @param {String} find
  21118. * @return {Boolean} found
  21119. */
  21120. inStr: function inStr(src, find) {
  21121. return src.indexOf(find) > -1;
  21122. },
  21123. /**
  21124. * find if a array contains the object using indexOf or a simple polyfill
  21125. * @method inArray
  21126. * @param {String} src
  21127. * @param {String} find
  21128. * @return {Boolean|Number} false when not found, or the index
  21129. */
  21130. inArray: function inArray(src, find) {
  21131. if(src.indexOf) {
  21132. var index = src.indexOf(find);
  21133. return (index === -1) ? false : index;
  21134. } else {
  21135. for(var i = 0, len = src.length; i < len; i++) {
  21136. if(src[i] === find) {
  21137. return i;
  21138. }
  21139. }
  21140. return false;
  21141. }
  21142. },
  21143. /**
  21144. * convert an array-like object (`arguments`, `touchlist`) to an array
  21145. * @method toArray
  21146. * @param {Object} obj
  21147. * @return {Array}
  21148. */
  21149. toArray: function toArray(obj) {
  21150. return Array.prototype.slice.call(obj, 0);
  21151. },
  21152. /**
  21153. * find if a node is in the given parent
  21154. * @method hasParent
  21155. * @param {HTMLElement} node
  21156. * @param {HTMLElement} parent
  21157. * @return {Boolean} found
  21158. */
  21159. hasParent: function hasParent(node, parent) {
  21160. while(node) {
  21161. if(node == parent) {
  21162. return true;
  21163. }
  21164. node = node.parentNode;
  21165. }
  21166. return false;
  21167. },
  21168. /**
  21169. * get the center of all the touches
  21170. * @method getCenter
  21171. * @param {Array} touches
  21172. * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties
  21173. */
  21174. getCenter: function getCenter(touches) {
  21175. var pageX = [],
  21176. pageY = [],
  21177. clientX = [],
  21178. clientY = [],
  21179. min = Math.min,
  21180. max = Math.max;
  21181. // no need to loop when only one touch
  21182. if(touches.length === 1) {
  21183. return {
  21184. pageX: touches[0].pageX,
  21185. pageY: touches[0].pageY,
  21186. clientX: touches[0].clientX,
  21187. clientY: touches[0].clientY
  21188. };
  21189. }
  21190. Utils.each(touches, function(touch) {
  21191. pageX.push(touch.pageX);
  21192. pageY.push(touch.pageY);
  21193. clientX.push(touch.clientX);
  21194. clientY.push(touch.clientY);
  21195. });
  21196. return {
  21197. pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2,
  21198. pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2,
  21199. clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2,
  21200. clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2
  21201. };
  21202. },
  21203. /**
  21204. * calculate the velocity between two points. unit is in px per ms.
  21205. * @method getVelocity
  21206. * @param {Number} deltaTime
  21207. * @param {Number} deltaX
  21208. * @param {Number} deltaY
  21209. * @return {Object} velocity `x` and `y`
  21210. */
  21211. getVelocity: function getVelocity(deltaTime, deltaX, deltaY) {
  21212. return {
  21213. x: Math.abs(deltaX / deltaTime) || 0,
  21214. y: Math.abs(deltaY / deltaTime) || 0
  21215. };
  21216. },
  21217. /**
  21218. * calculate the angle between two coordinates
  21219. * @method getAngle
  21220. * @param {Touch} touch1
  21221. * @param {Touch} touch2
  21222. * @return {Number} angle
  21223. */
  21224. getAngle: function getAngle(touch1, touch2) {
  21225. var x = touch2.clientX - touch1.clientX,
  21226. y = touch2.clientY - touch1.clientY;
  21227. return Math.atan2(y, x) * 180 / Math.PI;
  21228. },
  21229. /**
  21230. * do a small comparision to get the direction between two touches.
  21231. * @method getDirection
  21232. * @param {Touch} touch1
  21233. * @param {Touch} touch2
  21234. * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN`
  21235. */
  21236. getDirection: function getDirection(touch1, touch2) {
  21237. var x = Math.abs(touch1.clientX - touch2.clientX),
  21238. y = Math.abs(touch1.clientY - touch2.clientY);
  21239. if(x >= y) {
  21240. return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  21241. }
  21242. return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  21243. },
  21244. /**
  21245. * calculate the distance between two touches
  21246. * @method getDistance
  21247. * @param {Touch}touch1
  21248. * @param {Touch} touch2
  21249. * @return {Number} distance
  21250. */
  21251. getDistance: function getDistance(touch1, touch2) {
  21252. var x = touch2.clientX - touch1.clientX,
  21253. y = touch2.clientY - touch1.clientY;
  21254. return Math.sqrt((x * x) + (y * y));
  21255. },
  21256. /**
  21257. * calculate the scale factor between two touchLists
  21258. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  21259. * @method getScale
  21260. * @param {Array} start array of touches
  21261. * @param {Array} end array of touches
  21262. * @return {Number} scale
  21263. */
  21264. getScale: function getScale(start, end) {
  21265. // need two fingers...
  21266. if(start.length >= 2 && end.length >= 2) {
  21267. return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]);
  21268. }
  21269. return 1;
  21270. },
  21271. /**
  21272. * calculate the rotation degrees between two touchLists
  21273. * @method getRotation
  21274. * @param {Array} start array of touches
  21275. * @param {Array} end array of touches
  21276. * @return {Number} rotation
  21277. */
  21278. getRotation: function getRotation(start, end) {
  21279. // need two fingers
  21280. if(start.length >= 2 && end.length >= 2) {
  21281. return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]);
  21282. }
  21283. return 0;
  21284. },
  21285. /**
  21286. * find out if the direction is vertical *
  21287. * @method isVertical
  21288. * @param {String} direction matches `DIRECTION_UP|DOWN`
  21289. * @return {Boolean} is_vertical
  21290. */
  21291. isVertical: function isVertical(direction) {
  21292. return direction == DIRECTION_UP || direction == DIRECTION_DOWN;
  21293. },
  21294. /**
  21295. * set css properties with their prefixes
  21296. * @param {HTMLElement} element
  21297. * @param {String} prop
  21298. * @param {String} value
  21299. * @param {Boolean} [toggle=true]
  21300. * @return {Boolean}
  21301. */
  21302. setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) {
  21303. var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms'];
  21304. prop = Utils.toCamelCase(prop);
  21305. for(var i = 0; i < prefixes.length; i++) {
  21306. var p = prop;
  21307. // prefixes
  21308. if(prefixes[i]) {
  21309. p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1);
  21310. }
  21311. // test the style
  21312. if(p in element.style) {
  21313. element.style[p] = (toggle == null || toggle) && value || '';
  21314. break;
  21315. }
  21316. }
  21317. },
  21318. /**
  21319. * toggle browser default behavior by setting css properties.
  21320. * `userSelect='none'` also sets `element.onselectstart` to false
  21321. * `userDrag='none'` also sets `element.ondragstart` to false
  21322. *
  21323. * @method toggleBehavior
  21324. * @param {HtmlElement} element
  21325. * @param {Object} props
  21326. * @param {Boolean} [toggle=true]
  21327. */
  21328. toggleBehavior: function toggleBehavior(element, props, toggle) {
  21329. if(!props || !element || !element.style) {
  21330. return;
  21331. }
  21332. // set the css properties
  21333. Utils.each(props, function(value, prop) {
  21334. Utils.setPrefixedCss(element, prop, value, toggle);
  21335. });
  21336. var falseFn = toggle && function() {
  21337. return false;
  21338. };
  21339. // also the disable onselectstart
  21340. if(props.userSelect == 'none') {
  21341. element.onselectstart = falseFn;
  21342. }
  21343. // and disable ondragstart
  21344. if(props.userDrag == 'none') {
  21345. element.ondragstart = falseFn;
  21346. }
  21347. },
  21348. /**
  21349. * convert a string with underscores to camelCase
  21350. * so prevent_default becomes preventDefault
  21351. * @param {String} str
  21352. * @return {String} camelCaseStr
  21353. */
  21354. toCamelCase: function toCamelCase(str) {
  21355. return str.replace(/[_-]([a-z])/g, function(s) {
  21356. return s[1].toUpperCase();
  21357. });
  21358. }
  21359. };
  21360. /**
  21361. * @module hammer
  21362. */
  21363. /**
  21364. * @class Event
  21365. * @static
  21366. */
  21367. var Event = Hammer.event = {
  21368. /**
  21369. * when touch events have been fired, this is true
  21370. * this is used to stop mouse events
  21371. * @property prevent_mouseevents
  21372. * @private
  21373. * @type {Boolean}
  21374. */
  21375. preventMouseEvents: false,
  21376. /**
  21377. * if EVENT_START has been fired
  21378. * @property started
  21379. * @private
  21380. * @type {Boolean}
  21381. */
  21382. started: false,
  21383. /**
  21384. * when the mouse is hold down, this is true
  21385. * @property should_detect
  21386. * @private
  21387. * @type {Boolean}
  21388. */
  21389. shouldDetect: false,
  21390. /**
  21391. * simple event binder with a hook and support for multiple types
  21392. * @method on
  21393. * @param {HTMLElement} element
  21394. * @param {String} type
  21395. * @param {Function} handler
  21396. * @param {Function} [hook]
  21397. * @param {Object} hook.type
  21398. */
  21399. on: function on(element, type, handler, hook) {
  21400. var types = type.split(' ');
  21401. Utils.each(types, function(type) {
  21402. Utils.on(element, type, handler);
  21403. hook && hook(type);
  21404. });
  21405. },
  21406. /**
  21407. * simple event unbinder with a hook and support for multiple types
  21408. * @method off
  21409. * @param {HTMLElement} element
  21410. * @param {String} type
  21411. * @param {Function} handler
  21412. * @param {Function} [hook]
  21413. * @param {Object} hook.type
  21414. */
  21415. off: function off(element, type, handler, hook) {
  21416. var types = type.split(' ');
  21417. Utils.each(types, function(type) {
  21418. Utils.off(element, type, handler);
  21419. hook && hook(type);
  21420. });
  21421. },
  21422. /**
  21423. * the core touch event handler.
  21424. * this finds out if we should to detect gestures
  21425. * @method onTouch
  21426. * @param {HTMLElement} element
  21427. * @param {String} eventType matches `EVENT_START|MOVE|END`
  21428. * @param {Function} handler
  21429. * @return onTouchHandler {Function} the core event handler
  21430. */
  21431. onTouch: function onTouch(element, eventType, handler) {
  21432. var self = this;
  21433. var onTouchHandler = function onTouchHandler(ev) {
  21434. var srcType = ev.type.toLowerCase(),
  21435. isPointer = Hammer.HAS_POINTEREVENTS,
  21436. isMouse = Utils.inStr(srcType, 'mouse'),
  21437. triggerType;
  21438. // if we are in a mouseevent, but there has been a touchevent triggered in this session
  21439. // we want to do nothing. simply break out of the event.
  21440. if(isMouse && self.preventMouseEvents) {
  21441. return;
  21442. // mousebutton must be down
  21443. } else if(isMouse && eventType == EVENT_START && ev.button === 0) {
  21444. self.preventMouseEvents = false;
  21445. self.shouldDetect = true;
  21446. } else if(isPointer && eventType == EVENT_START) {
  21447. self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev));
  21448. // just a valid start event, but no mouse
  21449. } else if(!isMouse && eventType == EVENT_START) {
  21450. self.preventMouseEvents = true;
  21451. self.shouldDetect = true;
  21452. }
  21453. // update the pointer event before entering the detection
  21454. if(isPointer && eventType != EVENT_END) {
  21455. PointerEvent.updatePointer(eventType, ev);
  21456. }
  21457. // we are in a touch/down state, so allowed detection of gestures
  21458. if(self.shouldDetect) {
  21459. triggerType = self.doDetect.call(self, ev, eventType, element, handler);
  21460. }
  21461. // ...and we are done with the detection
  21462. // so reset everything to start each detection totally fresh
  21463. if(triggerType == EVENT_END) {
  21464. self.preventMouseEvents = false;
  21465. self.shouldDetect = false;
  21466. PointerEvent.reset();
  21467. // update the pointerevent object after the detection
  21468. }
  21469. if(isPointer && eventType == EVENT_END) {
  21470. PointerEvent.updatePointer(eventType, ev);
  21471. }
  21472. };
  21473. this.on(element, EVENT_TYPES[eventType], onTouchHandler);
  21474. return onTouchHandler;
  21475. },
  21476. /**
  21477. * the core detection method
  21478. * this finds out what hammer-touch-events to trigger
  21479. * @method doDetect
  21480. * @param {Object} ev
  21481. * @param {String} eventType matches `EVENT_START|MOVE|END`
  21482. * @param {HTMLElement} element
  21483. * @param {Function} handler
  21484. * @return {String} triggerType matches `EVENT_START|MOVE|END`
  21485. */
  21486. doDetect: function doDetect(ev, eventType, element, handler) {
  21487. var touchList = this.getTouchList(ev, eventType);
  21488. var touchListLength = touchList.length;
  21489. var triggerType = eventType;
  21490. var triggerChange = touchList.trigger; // used by fakeMultitouch plugin
  21491. var changedLength = touchListLength;
  21492. // at each touchstart-like event we want also want to trigger a TOUCH event...
  21493. if(eventType == EVENT_START) {
  21494. triggerChange = EVENT_TOUCH;
  21495. // ...the same for a touchend-like event
  21496. } else if(eventType == EVENT_END) {
  21497. triggerChange = EVENT_RELEASE;
  21498. // keep track of how many touches have been removed
  21499. changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1);
  21500. }
  21501. // after there are still touches on the screen,
  21502. // we just want to trigger a MOVE event. so change the START or END to a MOVE
  21503. // but only after detection has been started, the first time we actualy want a START
  21504. if(changedLength > 0 && this.started) {
  21505. triggerType = EVENT_MOVE;
  21506. }
  21507. // detection has been started, we keep track of this, see above
  21508. this.started = true;
  21509. // generate some event data, some basic information
  21510. var evData = this.collectEventData(element, triggerType, touchList, ev);
  21511. // trigger the triggerType event before the change (TOUCH, RELEASE) events
  21512. // but the END event should be at last
  21513. if(eventType != EVENT_END) {
  21514. handler.call(Detection, evData);
  21515. }
  21516. // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed
  21517. if(triggerChange) {
  21518. evData.changedLength = changedLength;
  21519. evData.eventType = triggerChange;
  21520. handler.call(Detection, evData);
  21521. evData.eventType = triggerType;
  21522. delete evData.changedLength;
  21523. }
  21524. // trigger the END event
  21525. if(triggerType == EVENT_END) {
  21526. handler.call(Detection, evData);
  21527. // ...and we are done with the detection
  21528. // so reset everything to start each detection totally fresh
  21529. this.started = false;
  21530. }
  21531. return triggerType;
  21532. },
  21533. /**
  21534. * we have different events for each device/browser
  21535. * determine what we need and set them in the EVENT_TYPES constant
  21536. * the `onTouch` method is bind to these properties.
  21537. * @method determineEventTypes
  21538. * @return {Object} events
  21539. */
  21540. determineEventTypes: function determineEventTypes() {
  21541. var types;
  21542. if(Hammer.HAS_POINTEREVENTS) {
  21543. if(window.PointerEvent) {
  21544. types = [
  21545. 'pointerdown',
  21546. 'pointermove',
  21547. 'pointerup pointercancel lostpointercapture'
  21548. ];
  21549. } else {
  21550. types = [
  21551. 'MSPointerDown',
  21552. 'MSPointerMove',
  21553. 'MSPointerUp MSPointerCancel MSLostPointerCapture'
  21554. ];
  21555. }
  21556. } else if(Hammer.NO_MOUSEEVENTS) {
  21557. types = [
  21558. 'touchstart',
  21559. 'touchmove',
  21560. 'touchend touchcancel'
  21561. ];
  21562. } else {
  21563. types = [
  21564. 'touchstart mousedown',
  21565. 'touchmove mousemove',
  21566. 'touchend touchcancel mouseup'
  21567. ];
  21568. }
  21569. EVENT_TYPES[EVENT_START] = types[0];
  21570. EVENT_TYPES[EVENT_MOVE] = types[1];
  21571. EVENT_TYPES[EVENT_END] = types[2];
  21572. return EVENT_TYPES;
  21573. },
  21574. /**
  21575. * create touchList depending on the event
  21576. * @method getTouchList
  21577. * @param {Object} ev
  21578. * @param {String} eventType
  21579. * @return {Array} touches
  21580. */
  21581. getTouchList: function getTouchList(ev, eventType) {
  21582. // get the fake pointerEvent touchlist
  21583. if(Hammer.HAS_POINTEREVENTS) {
  21584. return PointerEvent.getTouchList();
  21585. }
  21586. // get the touchlist
  21587. if(ev.touches) {
  21588. if(eventType == EVENT_MOVE) {
  21589. return ev.touches;
  21590. }
  21591. var identifiers = [];
  21592. var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches));
  21593. var touchList = [];
  21594. Utils.each(concat, function(touch) {
  21595. if(Utils.inArray(identifiers, touch.identifier) === false) {
  21596. touchList.push(touch);
  21597. }
  21598. identifiers.push(touch.identifier);
  21599. });
  21600. return touchList;
  21601. }
  21602. // make fake touchList from mouse position
  21603. ev.identifier = 1;
  21604. return [ev];
  21605. },
  21606. /**
  21607. * collect basic event data
  21608. * @method collectEventData
  21609. * @param {HTMLElement} element
  21610. * @param {String} eventType matches `EVENT_START|MOVE|END`
  21611. * @param {Array} touches
  21612. * @param {Object} ev
  21613. * @return {Object} ev
  21614. */
  21615. collectEventData: function collectEventData(element, eventType, touches, ev) {
  21616. // find out pointerType
  21617. var pointerType = POINTER_TOUCH;
  21618. if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
  21619. pointerType = POINTER_MOUSE;
  21620. } else if(PointerEvent.matchType(POINTER_PEN, ev)) {
  21621. pointerType = POINTER_PEN;
  21622. }
  21623. return {
  21624. center: Utils.getCenter(touches),
  21625. timeStamp: Date.now(),
  21626. target: ev.target,
  21627. touches: touches,
  21628. eventType: eventType,
  21629. pointerType: pointerType,
  21630. srcEvent: ev,
  21631. /**
  21632. * prevent the browser default actions
  21633. * mostly used to disable scrolling of the browser
  21634. */
  21635. preventDefault: function() {
  21636. var srcEvent = this.srcEvent;
  21637. srcEvent.preventManipulation && srcEvent.preventManipulation();
  21638. srcEvent.preventDefault && srcEvent.preventDefault();
  21639. },
  21640. /**
  21641. * stop bubbling the event up to its parents
  21642. */
  21643. stopPropagation: function() {
  21644. this.srcEvent.stopPropagation();
  21645. },
  21646. /**
  21647. * immediately stop gesture detection
  21648. * might be useful after a swipe was detected
  21649. * @return {*}
  21650. */
  21651. stopDetect: function() {
  21652. return Detection.stopDetect();
  21653. }
  21654. };
  21655. }
  21656. };
  21657. /**
  21658. * @module hammer
  21659. *
  21660. * @class PointerEvent
  21661. * @static
  21662. */
  21663. var PointerEvent = Hammer.PointerEvent = {
  21664. /**
  21665. * holds all pointers, by `identifier`
  21666. * @property pointers
  21667. * @type {Object}
  21668. */
  21669. pointers: {},
  21670. /**
  21671. * get the pointers as an array
  21672. * @method getTouchList
  21673. * @return {Array} touchlist
  21674. */
  21675. getTouchList: function getTouchList() {
  21676. var touchlist = [];
  21677. // we can use forEach since pointerEvents only is in IE10
  21678. Utils.each(this.pointers, function(pointer) {
  21679. touchlist.push(pointer);
  21680. });
  21681. return touchlist;
  21682. },
  21683. /**
  21684. * update the position of a pointer
  21685. * @method updatePointer
  21686. * @param {String} eventType matches `EVENT_START|MOVE|END`
  21687. * @param {Object} pointerEvent
  21688. */
  21689. updatePointer: function updatePointer(eventType, pointerEvent) {
  21690. if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) {
  21691. delete this.pointers[pointerEvent.pointerId];
  21692. } else {
  21693. pointerEvent.identifier = pointerEvent.pointerId;
  21694. this.pointers[pointerEvent.pointerId] = pointerEvent;
  21695. }
  21696. },
  21697. /**
  21698. * check if ev matches pointertype
  21699. * @method matchType
  21700. * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN`
  21701. * @param {PointerEvent} ev
  21702. */
  21703. matchType: function matchType(pointerType, ev) {
  21704. if(!ev.pointerType) {
  21705. return false;
  21706. }
  21707. var pt = ev.pointerType,
  21708. types = {};
  21709. types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE));
  21710. types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH));
  21711. types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN));
  21712. return types[pointerType];
  21713. },
  21714. /**
  21715. * reset the stored pointers
  21716. * @method reset
  21717. */
  21718. reset: function resetList() {
  21719. this.pointers = {};
  21720. }
  21721. };
  21722. /**
  21723. * @module hammer
  21724. *
  21725. * @class Detection
  21726. * @static
  21727. */
  21728. var Detection = Hammer.detection = {
  21729. // contains all registred Hammer.gestures in the correct order
  21730. gestures: [],
  21731. // data of the current Hammer.gesture detection session
  21732. current: null,
  21733. // the previous Hammer.gesture session data
  21734. // is a full clone of the previous gesture.current object
  21735. previous: null,
  21736. // when this becomes true, no gestures are fired
  21737. stopped: false,
  21738. /**
  21739. * start Hammer.gesture detection
  21740. * @method startDetect
  21741. * @param {Hammer.Instance} inst
  21742. * @param {Object} eventData
  21743. */
  21744. startDetect: function startDetect(inst, eventData) {
  21745. // already busy with a Hammer.gesture detection on an element
  21746. if(this.current) {
  21747. return;
  21748. }
  21749. this.stopped = false;
  21750. // holds current session
  21751. this.current = {
  21752. inst: inst, // reference to HammerInstance we're working for
  21753. startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc
  21754. lastEvent: false, // last eventData
  21755. lastCalcEvent: false, // last eventData for calculations.
  21756. futureCalcEvent: false, // last eventData for calculations.
  21757. lastCalcData: {}, // last lastCalcData
  21758. name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  21759. };
  21760. this.detect(eventData);
  21761. },
  21762. /**
  21763. * Hammer.gesture detection
  21764. * @method detect
  21765. * @param {Object} eventData
  21766. * @return {any}
  21767. */
  21768. detect: function detect(eventData) {
  21769. if(!this.current || this.stopped) {
  21770. return;
  21771. }
  21772. // extend event data with calculations about scale, distance etc
  21773. eventData = this.extendEventData(eventData);
  21774. // hammer instance and instance options
  21775. var inst = this.current.inst,
  21776. instOptions = inst.options;
  21777. // call Hammer.gesture handlers
  21778. Utils.each(this.gestures, function triggerGesture(gesture) {
  21779. // only when the instance options have enabled this gesture
  21780. if(!this.stopped && inst.enabled && instOptions[gesture.name]) {
  21781. gesture.handler.call(gesture, eventData, inst);
  21782. }
  21783. }, this);
  21784. // store as previous event event
  21785. if(this.current) {
  21786. this.current.lastEvent = eventData;
  21787. }
  21788. if(eventData.eventType == EVENT_END) {
  21789. this.stopDetect();
  21790. }
  21791. return eventData;
  21792. },
  21793. /**
  21794. * clear the Hammer.gesture vars
  21795. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  21796. * to stop other Hammer.gestures from being fired
  21797. * @method stopDetect
  21798. */
  21799. stopDetect: function stopDetect() {
  21800. // clone current data to the store as the previous gesture
  21801. // used for the double tap gesture, since this is an other gesture detect session
  21802. this.previous = Utils.extend({}, this.current);
  21803. // reset the current
  21804. this.current = null;
  21805. this.stopped = true;
  21806. },
  21807. /**
  21808. * calculate velocity, angle and direction
  21809. * @method getVelocityData
  21810. * @param {Object} ev
  21811. * @param {Object} center
  21812. * @param {Number} deltaTime
  21813. * @param {Number} deltaX
  21814. * @param {Number} deltaY
  21815. */
  21816. getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) {
  21817. var cur = this.current,
  21818. recalc = false,
  21819. calcEv = cur.lastCalcEvent,
  21820. calcData = cur.lastCalcData;
  21821. if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) {
  21822. center = calcEv.center;
  21823. deltaTime = ev.timeStamp - calcEv.timeStamp;
  21824. deltaX = ev.center.clientX - calcEv.center.clientX;
  21825. deltaY = ev.center.clientY - calcEv.center.clientY;
  21826. recalc = true;
  21827. }
  21828. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  21829. cur.futureCalcEvent = ev;
  21830. }
  21831. if(!cur.lastCalcEvent || recalc) {
  21832. calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY);
  21833. calcData.angle = Utils.getAngle(center, ev.center);
  21834. calcData.direction = Utils.getDirection(center, ev.center);
  21835. cur.lastCalcEvent = cur.futureCalcEvent || ev;
  21836. cur.futureCalcEvent = ev;
  21837. }
  21838. ev.velocityX = calcData.velocity.x;
  21839. ev.velocityY = calcData.velocity.y;
  21840. ev.interimAngle = calcData.angle;
  21841. ev.interimDirection = calcData.direction;
  21842. },
  21843. /**
  21844. * extend eventData for Hammer.gestures
  21845. * @method extendEventData
  21846. * @param {Object} ev
  21847. * @return {Object} ev
  21848. */
  21849. extendEventData: function extendEventData(ev) {
  21850. var cur = this.current,
  21851. startEv = cur.startEvent,
  21852. lastEv = cur.lastEvent || startEv;
  21853. // update the start touchlist to calculate the scale/rotation
  21854. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  21855. startEv.touches = [];
  21856. Utils.each(ev.touches, function(touch) {
  21857. startEv.touches.push({
  21858. clientX: touch.clientX,
  21859. clientY: touch.clientY
  21860. });
  21861. });
  21862. }
  21863. var deltaTime = ev.timeStamp - startEv.timeStamp,
  21864. deltaX = ev.center.clientX - startEv.center.clientX,
  21865. deltaY = ev.center.clientY - startEv.center.clientY;
  21866. this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY);
  21867. Utils.extend(ev, {
  21868. startEvent: startEv,
  21869. deltaTime: deltaTime,
  21870. deltaX: deltaX,
  21871. deltaY: deltaY,
  21872. distance: Utils.getDistance(startEv.center, ev.center),
  21873. angle: Utils.getAngle(startEv.center, ev.center),
  21874. direction: Utils.getDirection(startEv.center, ev.center),
  21875. scale: Utils.getScale(startEv.touches, ev.touches),
  21876. rotation: Utils.getRotation(startEv.touches, ev.touches)
  21877. });
  21878. return ev;
  21879. },
  21880. /**
  21881. * register new gesture
  21882. * @method register
  21883. * @param {Object} gesture object, see `gestures/` for documentation
  21884. * @return {Array} gestures
  21885. */
  21886. register: function register(gesture) {
  21887. // add an enable gesture options if there is no given
  21888. var options = gesture.defaults || {};
  21889. if(options[gesture.name] === undefined) {
  21890. options[gesture.name] = true;
  21891. }
  21892. // extend Hammer default options with the Hammer.gesture options
  21893. Utils.extend(Hammer.defaults, options, true);
  21894. // set its index
  21895. gesture.index = gesture.index || 1000;
  21896. // add Hammer.gesture to the list
  21897. this.gestures.push(gesture);
  21898. // sort the list by index
  21899. this.gestures.sort(function(a, b) {
  21900. if(a.index < b.index) {
  21901. return -1;
  21902. }
  21903. if(a.index > b.index) {
  21904. return 1;
  21905. }
  21906. return 0;
  21907. });
  21908. return this.gestures;
  21909. }
  21910. };
  21911. /**
  21912. * @module hammer
  21913. */
  21914. /**
  21915. * create new hammer instance
  21916. * all methods should return the instance itself, so it is chainable.
  21917. *
  21918. * @class Instance
  21919. * @constructor
  21920. * @param {HTMLElement} element
  21921. * @param {Object} [options={}] options are merged with `Hammer.defaults`
  21922. * @return {Hammer.Instance}
  21923. */
  21924. Hammer.Instance = function(element, options) {
  21925. var self = this;
  21926. // setup HammerJS window events and register all gestures
  21927. // this also sets up the default options
  21928. setup();
  21929. /**
  21930. * @property element
  21931. * @type {HTMLElement}
  21932. */
  21933. this.element = element;
  21934. /**
  21935. * @property enabled
  21936. * @type {Boolean}
  21937. * @protected
  21938. */
  21939. this.enabled = true;
  21940. /**
  21941. * options, merged with the defaults
  21942. * options with an _ are converted to camelCase
  21943. * @property options
  21944. * @type {Object}
  21945. */
  21946. Utils.each(options, function(value, name) {
  21947. delete options[name];
  21948. options[Utils.toCamelCase(name)] = value;
  21949. });
  21950. this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {});
  21951. // add some css to the element to prevent the browser from doing its native behavoir
  21952. if(this.options.behavior) {
  21953. Utils.toggleBehavior(this.element, this.options.behavior, true);
  21954. }
  21955. /**
  21956. * event start handler on the element to start the detection
  21957. * @property eventStartHandler
  21958. * @type {Object}
  21959. */
  21960. this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) {
  21961. if(self.enabled && ev.eventType == EVENT_START) {
  21962. Detection.startDetect(self, ev);
  21963. } else if(ev.eventType == EVENT_TOUCH) {
  21964. Detection.detect(ev);
  21965. }
  21966. });
  21967. /**
  21968. * keep a list of user event handlers which needs to be removed when calling 'dispose'
  21969. * @property eventHandlers
  21970. * @type {Array}
  21971. */
  21972. this.eventHandlers = [];
  21973. };
  21974. Hammer.Instance.prototype = {
  21975. /**
  21976. * bind events to the instance
  21977. * @method on
  21978. * @chainable
  21979. * @param {String} gestures multiple gestures by splitting with a space
  21980. * @param {Function} handler
  21981. * @param {Object} handler.ev event object
  21982. */
  21983. on: function onEvent(gestures, handler) {
  21984. var self = this;
  21985. Event.on(self.element, gestures, handler, function(type) {
  21986. self.eventHandlers.push({ gesture: type, handler: handler });
  21987. });
  21988. return self;
  21989. },
  21990. /**
  21991. * unbind events to the instance
  21992. * @method off
  21993. * @chainable
  21994. * @param {String} gestures
  21995. * @param {Function} handler
  21996. */
  21997. off: function offEvent(gestures, handler) {
  21998. var self = this;
  21999. Event.off(self.element, gestures, handler, function(type) {
  22000. var index = Utils.inArray({ gesture: type, handler: handler });
  22001. if(index !== false) {
  22002. self.eventHandlers.splice(index, 1);
  22003. }
  22004. });
  22005. return self;
  22006. },
  22007. /**
  22008. * trigger gesture event
  22009. * @method trigger
  22010. * @chainable
  22011. * @param {String} gesture
  22012. * @param {Object} [eventData]
  22013. */
  22014. trigger: function triggerEvent(gesture, eventData) {
  22015. // optional
  22016. if(!eventData) {
  22017. eventData = {};
  22018. }
  22019. // create DOM event
  22020. var event = Hammer.DOCUMENT.createEvent('Event');
  22021. event.initEvent(gesture, true, true);
  22022. event.gesture = eventData;
  22023. // trigger on the target if it is in the instance element,
  22024. // this is for event delegation tricks
  22025. var element = this.element;
  22026. if(Utils.hasParent(eventData.target, element)) {
  22027. element = eventData.target;
  22028. }
  22029. element.dispatchEvent(event);
  22030. return this;
  22031. },
  22032. /**
  22033. * enable of disable hammer.js detection
  22034. * @method enable
  22035. * @chainable
  22036. * @param {Boolean} state
  22037. */
  22038. enable: function enable(state) {
  22039. this.enabled = state;
  22040. return this;
  22041. },
  22042. /**
  22043. * dispose this hammer instance
  22044. * @method dispose
  22045. * @return {Null}
  22046. */
  22047. dispose: function dispose() {
  22048. var i, eh;
  22049. // undo all changes made by stop_browser_behavior
  22050. Utils.toggleBehavior(this.element, this.options.behavior, false);
  22051. // unbind all custom event handlers
  22052. for(i = -1; (eh = this.eventHandlers[++i]);) {
  22053. Utils.off(this.element, eh.gesture, eh.handler);
  22054. }
  22055. this.eventHandlers = [];
  22056. // unbind the start event listener
  22057. Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler);
  22058. return null;
  22059. }
  22060. };
  22061. /**
  22062. * @module gestures
  22063. */
  22064. /**
  22065. * Move with x fingers (default 1) around on the page.
  22066. * Preventing the default browser behavior is a good way to improve feel and working.
  22067. * ````
  22068. * hammertime.on("drag", function(ev) {
  22069. * console.log(ev);
  22070. * ev.gesture.preventDefault();
  22071. * });
  22072. * ````
  22073. *
  22074. * @class Drag
  22075. * @static
  22076. */
  22077. /**
  22078. * @event drag
  22079. * @param {Object} ev
  22080. */
  22081. /**
  22082. * @event dragstart
  22083. * @param {Object} ev
  22084. */
  22085. /**
  22086. * @event dragend
  22087. * @param {Object} ev
  22088. */
  22089. /**
  22090. * @event drapleft
  22091. * @param {Object} ev
  22092. */
  22093. /**
  22094. * @event dragright
  22095. * @param {Object} ev
  22096. */
  22097. /**
  22098. * @event dragup
  22099. * @param {Object} ev
  22100. */
  22101. /**
  22102. * @event dragdown
  22103. * @param {Object} ev
  22104. */
  22105. /**
  22106. * @param {String} name
  22107. */
  22108. (function(name) {
  22109. var triggered = false;
  22110. function dragGesture(ev, inst) {
  22111. var cur = Detection.current;
  22112. // max touches
  22113. if(inst.options.dragMaxTouches > 0 &&
  22114. ev.touches.length > inst.options.dragMaxTouches) {
  22115. return;
  22116. }
  22117. switch(ev.eventType) {
  22118. case EVENT_START:
  22119. triggered = false;
  22120. break;
  22121. case EVENT_MOVE:
  22122. // when the distance we moved is too small we skip this gesture
  22123. // or we can be already in dragging
  22124. if(ev.distance < inst.options.dragMinDistance &&
  22125. cur.name != name) {
  22126. return;
  22127. }
  22128. var startCenter = cur.startEvent.center;
  22129. // we are dragging!
  22130. if(cur.name != name) {
  22131. cur.name = name;
  22132. if(inst.options.dragDistanceCorrection && ev.distance > 0) {
  22133. // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center.
  22134. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0.
  22135. // It might be useful to save the original start point somewhere
  22136. var factor = Math.abs(inst.options.dragMinDistance / ev.distance);
  22137. startCenter.pageX += ev.deltaX * factor;
  22138. startCenter.pageY += ev.deltaY * factor;
  22139. startCenter.clientX += ev.deltaX * factor;
  22140. startCenter.clientY += ev.deltaY * factor;
  22141. // recalculate event data using new start point
  22142. ev = Detection.extendEventData(ev);
  22143. }
  22144. }
  22145. // lock drag to axis?
  22146. if(cur.lastEvent.dragLockToAxis ||
  22147. ( inst.options.dragLockToAxis &&
  22148. inst.options.dragLockMinDistance <= ev.distance
  22149. )) {
  22150. ev.dragLockToAxis = true;
  22151. }
  22152. // keep direction on the axis that the drag gesture started on
  22153. var lastDirection = cur.lastEvent.direction;
  22154. if(ev.dragLockToAxis && lastDirection !== ev.direction) {
  22155. if(Utils.isVertical(lastDirection)) {
  22156. ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  22157. } else {
  22158. ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  22159. }
  22160. }
  22161. // first time, trigger dragstart event
  22162. if(!triggered) {
  22163. inst.trigger(name + 'start', ev);
  22164. triggered = true;
  22165. }
  22166. // trigger events
  22167. inst.trigger(name, ev);
  22168. inst.trigger(name + ev.direction, ev);
  22169. var isVertical = Utils.isVertical(ev.direction);
  22170. // block the browser events
  22171. if((inst.options.dragBlockVertical && isVertical) ||
  22172. (inst.options.dragBlockHorizontal && !isVertical)) {
  22173. ev.preventDefault();
  22174. }
  22175. break;
  22176. case EVENT_RELEASE:
  22177. if(triggered && ev.changedLength <= inst.options.dragMaxTouches) {
  22178. inst.trigger(name + 'end', ev);
  22179. triggered = false;
  22180. }
  22181. break;
  22182. case EVENT_END:
  22183. triggered = false;
  22184. break;
  22185. }
  22186. }
  22187. Hammer.gestures.Drag = {
  22188. name: name,
  22189. index: 50,
  22190. handler: dragGesture,
  22191. defaults: {
  22192. /**
  22193. * minimal movement that have to be made before the drag event gets triggered
  22194. * @property dragMinDistance
  22195. * @type {Number}
  22196. * @default 10
  22197. */
  22198. dragMinDistance: 10,
  22199. /**
  22200. * Set dragDistanceCorrection to true to make the starting point of the drag
  22201. * be calculated from where the drag was triggered, not from where the touch started.
  22202. * Useful to avoid a jerk-starting drag, which can make fine-adjustments
  22203. * through dragging difficult, and be visually unappealing.
  22204. * @property dragDistanceCorrection
  22205. * @type {Boolean}
  22206. * @default true
  22207. */
  22208. dragDistanceCorrection: true,
  22209. /**
  22210. * set 0 for unlimited, but this can conflict with transform
  22211. * @property dragMaxTouches
  22212. * @type {Number}
  22213. * @default 1
  22214. */
  22215. dragMaxTouches: 1,
  22216. /**
  22217. * prevent default browser behavior when dragging occurs
  22218. * be careful with it, it makes the element a blocking element
  22219. * when you are using the drag gesture, it is a good practice to set this true
  22220. * @property dragBlockHorizontal
  22221. * @type {Boolean}
  22222. * @default false
  22223. */
  22224. dragBlockHorizontal: false,
  22225. /**
  22226. * same as `dragBlockHorizontal`, but for vertical movement
  22227. * @property dragBlockVertical
  22228. * @type {Boolean}
  22229. * @default false
  22230. */
  22231. dragBlockVertical: false,
  22232. /**
  22233. * dragLockToAxis keeps the drag gesture on the axis that it started on,
  22234. * It disallows vertical directions if the initial direction was horizontal, and vice versa.
  22235. * @property dragLockToAxis
  22236. * @type {Boolean}
  22237. * @default false
  22238. */
  22239. dragLockToAxis: false,
  22240. /**
  22241. * drag lock only kicks in when distance > dragLockMinDistance
  22242. * This way, locking occurs only when the distance has become large enough to reliably determine the direction
  22243. * @property dragLockMinDistance
  22244. * @type {Number}
  22245. * @default 25
  22246. */
  22247. dragLockMinDistance: 25
  22248. }
  22249. };
  22250. })('drag');
  22251. /**
  22252. * @module gestures
  22253. */
  22254. /**
  22255. * trigger a simple gesture event, so you can do anything in your handler.
  22256. * only usable if you know what your doing...
  22257. *
  22258. * @class Gesture
  22259. * @static
  22260. */
  22261. /**
  22262. * @event gesture
  22263. * @param {Object} ev
  22264. */
  22265. Hammer.gestures.Gesture = {
  22266. name: 'gesture',
  22267. index: 1337,
  22268. handler: function releaseGesture(ev, inst) {
  22269. inst.trigger(this.name, ev);
  22270. }
  22271. };
  22272. /**
  22273. * @module gestures
  22274. */
  22275. /**
  22276. * Touch stays at the same place for x time
  22277. *
  22278. * @class Hold
  22279. * @static
  22280. */
  22281. /**
  22282. * @event hold
  22283. * @param {Object} ev
  22284. */
  22285. /**
  22286. * @param {String} name
  22287. */
  22288. (function(name) {
  22289. var timer;
  22290. function holdGesture(ev, inst) {
  22291. var options = inst.options,
  22292. current = Detection.current;
  22293. switch(ev.eventType) {
  22294. case EVENT_START:
  22295. clearTimeout(timer);
  22296. // set the gesture so we can check in the timeout if it still is
  22297. current.name = name;
  22298. // set timer and if after the timeout it still is hold,
  22299. // we trigger the hold event
  22300. timer = setTimeout(function() {
  22301. if(current && current.name == name) {
  22302. inst.trigger(name, ev);
  22303. }
  22304. }, options.holdTimeout);
  22305. break;
  22306. case EVENT_MOVE:
  22307. if(ev.distance > options.holdThreshold) {
  22308. clearTimeout(timer);
  22309. }
  22310. break;
  22311. case EVENT_RELEASE:
  22312. clearTimeout(timer);
  22313. break;
  22314. }
  22315. }
  22316. Hammer.gestures.Hold = {
  22317. name: name,
  22318. index: 10,
  22319. defaults: {
  22320. /**
  22321. * @property holdTimeout
  22322. * @type {Number}
  22323. * @default 500
  22324. */
  22325. holdTimeout: 500,
  22326. /**
  22327. * movement allowed while holding
  22328. * @property holdThreshold
  22329. * @type {Number}
  22330. * @default 2
  22331. */
  22332. holdThreshold: 2
  22333. },
  22334. handler: holdGesture
  22335. };
  22336. })('hold');
  22337. /**
  22338. * @module gestures
  22339. */
  22340. /**
  22341. * when a touch is being released from the page
  22342. *
  22343. * @class Release
  22344. * @static
  22345. */
  22346. /**
  22347. * @event release
  22348. * @param {Object} ev
  22349. */
  22350. Hammer.gestures.Release = {
  22351. name: 'release',
  22352. index: Infinity,
  22353. handler: function releaseGesture(ev, inst) {
  22354. if(ev.eventType == EVENT_RELEASE) {
  22355. inst.trigger(this.name, ev);
  22356. }
  22357. }
  22358. };
  22359. /**
  22360. * @module gestures
  22361. */
  22362. /**
  22363. * triggers swipe events when the end velocity is above the threshold
  22364. * for best usage, set `preventDefault` (on the drag gesture) to `true`
  22365. * ````
  22366. * hammertime.on("dragleft swipeleft", function(ev) {
  22367. * console.log(ev);
  22368. * ev.gesture.preventDefault();
  22369. * });
  22370. * ````
  22371. *
  22372. * @class Swipe
  22373. * @static
  22374. */
  22375. /**
  22376. * @event swipe
  22377. * @param {Object} ev
  22378. */
  22379. /**
  22380. * @event swipeleft
  22381. * @param {Object} ev
  22382. */
  22383. /**
  22384. * @event swiperight
  22385. * @param {Object} ev
  22386. */
  22387. /**
  22388. * @event swipeup
  22389. * @param {Object} ev
  22390. */
  22391. /**
  22392. * @event swipedown
  22393. * @param {Object} ev
  22394. */
  22395. Hammer.gestures.Swipe = {
  22396. name: 'swipe',
  22397. index: 40,
  22398. defaults: {
  22399. /**
  22400. * @property swipeMinTouches
  22401. * @type {Number}
  22402. * @default 1
  22403. */
  22404. swipeMinTouches: 1,
  22405. /**
  22406. * @property swipeMaxTouches
  22407. * @type {Number}
  22408. * @default 1
  22409. */
  22410. swipeMaxTouches: 1,
  22411. /**
  22412. * horizontal swipe velocity
  22413. * @property swipeVelocityX
  22414. * @type {Number}
  22415. * @default 0.6
  22416. */
  22417. swipeVelocityX: 0.6,
  22418. /**
  22419. * vertical swipe velocity
  22420. * @property swipeVelocityY
  22421. * @type {Number}
  22422. * @default 0.6
  22423. */
  22424. swipeVelocityY: 0.6
  22425. },
  22426. handler: function swipeGesture(ev, inst) {
  22427. if(ev.eventType == EVENT_RELEASE) {
  22428. var touches = ev.touches.length,
  22429. options = inst.options;
  22430. // max touches
  22431. if(touches < options.swipeMinTouches ||
  22432. touches > options.swipeMaxTouches) {
  22433. return;
  22434. }
  22435. // when the distance we moved is too small we skip this gesture
  22436. // or we can be already in dragging
  22437. if(ev.velocityX > options.swipeVelocityX ||
  22438. ev.velocityY > options.swipeVelocityY) {
  22439. // trigger swipe events
  22440. inst.trigger(this.name, ev);
  22441. inst.trigger(this.name + ev.direction, ev);
  22442. }
  22443. }
  22444. }
  22445. };
  22446. /**
  22447. * @module gestures
  22448. */
  22449. /**
  22450. * Single tap and a double tap on a place
  22451. *
  22452. * @class Tap
  22453. * @static
  22454. */
  22455. /**
  22456. * @event tap
  22457. * @param {Object} ev
  22458. */
  22459. /**
  22460. * @event doubletap
  22461. * @param {Object} ev
  22462. */
  22463. /**
  22464. * @param {String} name
  22465. */
  22466. (function(name) {
  22467. var hasMoved = false;
  22468. function tapGesture(ev, inst) {
  22469. var options = inst.options,
  22470. current = Detection.current,
  22471. prev = Detection.previous,
  22472. sincePrev,
  22473. didDoubleTap;
  22474. switch(ev.eventType) {
  22475. case EVENT_START:
  22476. hasMoved = false;
  22477. break;
  22478. case EVENT_MOVE:
  22479. hasMoved = hasMoved || (ev.distance > options.tapMaxDistance);
  22480. break;
  22481. case EVENT_END:
  22482. if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) {
  22483. // previous gesture, for the double tap since these are two different gesture detections
  22484. sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp;
  22485. didDoubleTap = false;
  22486. // check if double tap
  22487. if(prev && prev.name == name &&
  22488. (sincePrev && sincePrev < options.doubleTapInterval) &&
  22489. ev.distance < options.doubleTapDistance) {
  22490. inst.trigger('doubletap', ev);
  22491. didDoubleTap = true;
  22492. }
  22493. // do a single tap
  22494. if(!didDoubleTap || options.tapAlways) {
  22495. current.name = name;
  22496. inst.trigger(current.name, ev);
  22497. }
  22498. }
  22499. break;
  22500. }
  22501. }
  22502. Hammer.gestures.Tap = {
  22503. name: name,
  22504. index: 100,
  22505. handler: tapGesture,
  22506. defaults: {
  22507. /**
  22508. * max time of a tap, this is for the slow tappers
  22509. * @property tapMaxTime
  22510. * @type {Number}
  22511. * @default 250
  22512. */
  22513. tapMaxTime: 250,
  22514. /**
  22515. * max distance of movement of a tap, this is for the slow tappers
  22516. * @property tapMaxDistance
  22517. * @type {Number}
  22518. * @default 10
  22519. */
  22520. tapMaxDistance: 10,
  22521. /**
  22522. * always trigger the `tap` event, even while double-tapping
  22523. * @property tapAlways
  22524. * @type {Boolean}
  22525. * @default true
  22526. */
  22527. tapAlways: true,
  22528. /**
  22529. * max distance between two taps
  22530. * @property doubleTapDistance
  22531. * @type {Number}
  22532. * @default 20
  22533. */
  22534. doubleTapDistance: 20,
  22535. /**
  22536. * max time between two taps
  22537. * @property doubleTapInterval
  22538. * @type {Number}
  22539. * @default 300
  22540. */
  22541. doubleTapInterval: 300
  22542. }
  22543. };
  22544. })('tap');
  22545. /**
  22546. * @module gestures
  22547. */
  22548. /**
  22549. * when a touch is being touched at the page
  22550. *
  22551. * @class Touch
  22552. * @static
  22553. */
  22554. /**
  22555. * @event touch
  22556. * @param {Object} ev
  22557. */
  22558. Hammer.gestures.Touch = {
  22559. name: 'touch',
  22560. index: -Infinity,
  22561. defaults: {
  22562. /**
  22563. * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page,
  22564. * but it improves gestures like transforming and dragging.
  22565. * be careful with using this, it can be very annoying for users to be stuck on the page
  22566. * @property preventDefault
  22567. * @type {Boolean}
  22568. * @default false
  22569. */
  22570. preventDefault: false,
  22571. /**
  22572. * disable mouse events, so only touch (or pen!) input triggers events
  22573. * @property preventMouse
  22574. * @type {Boolean}
  22575. * @default false
  22576. */
  22577. preventMouse: false
  22578. },
  22579. handler: function touchGesture(ev, inst) {
  22580. if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) {
  22581. ev.stopDetect();
  22582. return;
  22583. }
  22584. if(inst.options.preventDefault) {
  22585. ev.preventDefault();
  22586. }
  22587. if(ev.eventType == EVENT_TOUCH) {
  22588. inst.trigger('touch', ev);
  22589. }
  22590. }
  22591. };
  22592. /**
  22593. * @module gestures
  22594. */
  22595. /**
  22596. * User want to scale or rotate with 2 fingers
  22597. * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the
  22598. * `preventDefault` option.
  22599. *
  22600. * @class Transform
  22601. * @static
  22602. */
  22603. /**
  22604. * @event transform
  22605. * @param {Object} ev
  22606. */
  22607. /**
  22608. * @event transformstart
  22609. * @param {Object} ev
  22610. */
  22611. /**
  22612. * @event transformend
  22613. * @param {Object} ev
  22614. */
  22615. /**
  22616. * @event pinchin
  22617. * @param {Object} ev
  22618. */
  22619. /**
  22620. * @event pinchout
  22621. * @param {Object} ev
  22622. */
  22623. /**
  22624. * @event rotate
  22625. * @param {Object} ev
  22626. */
  22627. /**
  22628. * @param {String} name
  22629. */
  22630. (function(name) {
  22631. var triggered = false;
  22632. function transformGesture(ev, inst) {
  22633. switch(ev.eventType) {
  22634. case EVENT_START:
  22635. triggered = false;
  22636. break;
  22637. case EVENT_MOVE:
  22638. // at least multitouch
  22639. if(ev.touches.length < 2) {
  22640. return;
  22641. }
  22642. var scaleThreshold = Math.abs(1 - ev.scale);
  22643. var rotationThreshold = Math.abs(ev.rotation);
  22644. // when the distance we moved is too small we skip this gesture
  22645. // or we can be already in dragging
  22646. if(scaleThreshold < inst.options.transformMinScale &&
  22647. rotationThreshold < inst.options.transformMinRotation) {
  22648. return;
  22649. }
  22650. // we are transforming!
  22651. Detection.current.name = name;
  22652. // first time, trigger dragstart event
  22653. if(!triggered) {
  22654. inst.trigger(name + 'start', ev);
  22655. triggered = true;
  22656. }
  22657. inst.trigger(name, ev); // basic transform event
  22658. // trigger rotate event
  22659. if(rotationThreshold > inst.options.transformMinRotation) {
  22660. inst.trigger('rotate', ev);
  22661. }
  22662. // trigger pinch event
  22663. if(scaleThreshold > inst.options.transformMinScale) {
  22664. inst.trigger('pinch', ev);
  22665. inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev);
  22666. }
  22667. break;
  22668. case EVENT_RELEASE:
  22669. if(triggered && ev.changedLength < 2) {
  22670. inst.trigger(name + 'end', ev);
  22671. triggered = false;
  22672. }
  22673. break;
  22674. }
  22675. }
  22676. Hammer.gestures.Transform = {
  22677. name: name,
  22678. index: 45,
  22679. defaults: {
  22680. /**
  22681. * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  22682. * @property transformMinScale
  22683. * @type {Number}
  22684. * @default 0.01
  22685. */
  22686. transformMinScale: 0.01,
  22687. /**
  22688. * rotation in degrees
  22689. * @property transformMinRotation
  22690. * @type {Number}
  22691. * @default 1
  22692. */
  22693. transformMinRotation: 1
  22694. },
  22695. handler: transformGesture
  22696. };
  22697. })('transform');
  22698. /**
  22699. * @module hammer
  22700. */
  22701. // AMD export
  22702. if(true) {
  22703. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
  22704. return Hammer;
  22705. }.call(exports, __webpack_require__, exports, module)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  22706. // commonjs export
  22707. } else if(typeof module !== 'undefined' && module.exports) {
  22708. module.exports = Hammer;
  22709. // browser export
  22710. } else {
  22711. window.Hammer = Hammer;
  22712. }
  22713. })(window);
  22714. /***/ },
  22715. /* 50 */
  22716. /***/ function(module, exports, __webpack_require__) {
  22717. /**
  22718. * Creation of the ClusterMixin var.
  22719. *
  22720. * This contains all the functions the Network object can use to employ clustering
  22721. */
  22722. /**
  22723. * This is only called in the constructor of the network object
  22724. *
  22725. */
  22726. exports.startWithClustering = function() {
  22727. // cluster if the data set is big
  22728. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  22729. // updates the lables after clustering
  22730. this.updateLabels();
  22731. // this is called here because if clusterin is disabled, the start and stabilize are called in
  22732. // the setData function.
  22733. if (this.stabilize) {
  22734. this._stabilize();
  22735. }
  22736. this.start();
  22737. };
  22738. /**
  22739. * This function clusters until the initialMaxNodes has been reached
  22740. *
  22741. * @param {Number} maxNumberOfNodes
  22742. * @param {Boolean} reposition
  22743. */
  22744. exports.clusterToFit = function(maxNumberOfNodes, reposition) {
  22745. var numberOfNodes = this.nodeIndices.length;
  22746. var maxLevels = 50;
  22747. var level = 0;
  22748. // we first cluster the hubs, then we pull in the outliers, repeat
  22749. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  22750. if (level % 3 == 0) {
  22751. this.forceAggregateHubs(true);
  22752. this.normalizeClusterLevels();
  22753. }
  22754. else {
  22755. this.increaseClusterLevel(); // this also includes a cluster normalization
  22756. }
  22757. numberOfNodes = this.nodeIndices.length;
  22758. level += 1;
  22759. }
  22760. // after the clustering we reposition the nodes to reduce the initial chaos
  22761. if (level > 0 && reposition == true) {
  22762. this.repositionNodes();
  22763. }
  22764. this._updateCalculationNodes();
  22765. };
  22766. /**
  22767. * This function can be called to open up a specific cluster. It is only called by
  22768. * It will unpack the cluster back one level.
  22769. *
  22770. * @param node | Node object: cluster to open.
  22771. */
  22772. exports.openCluster = function(node) {
  22773. var isMovingBeforeClustering = this.moving;
  22774. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  22775. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  22776. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  22777. this._addSector(node);
  22778. var level = 0;
  22779. // we decluster until we reach a decent number of nodes
  22780. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  22781. this.decreaseClusterLevel();
  22782. level += 1;
  22783. }
  22784. }
  22785. else {
  22786. this._expandClusterNode(node,false,true);
  22787. // update the index list, dynamic edges and labels
  22788. this._updateNodeIndexList();
  22789. this._updateDynamicEdges();
  22790. this._updateCalculationNodes();
  22791. this.updateLabels();
  22792. }
  22793. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  22794. if (this.moving != isMovingBeforeClustering) {
  22795. this.start();
  22796. }
  22797. };
  22798. /**
  22799. * This calls the updateClustes with default arguments
  22800. */
  22801. exports.updateClustersDefault = function() {
  22802. if (this.constants.clustering.enabled == true) {
  22803. this.updateClusters(0,false,false);
  22804. }
  22805. };
  22806. /**
  22807. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  22808. * be clustered with their connected node. This can be repeated as many times as needed.
  22809. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  22810. */
  22811. exports.increaseClusterLevel = function() {
  22812. this.updateClusters(-1,false,true);
  22813. };
  22814. /**
  22815. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  22816. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  22817. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  22818. */
  22819. exports.decreaseClusterLevel = function() {
  22820. this.updateClusters(1,false,true);
  22821. };
  22822. /**
  22823. * This is the main clustering function. It clusters and declusters on zoom or forced
  22824. * This function clusters on zoom, it can be called with a predefined zoom direction
  22825. * If out, check if we can form clusters, if in, check if we can open clusters.
  22826. * This function is only called from _zoom()
  22827. *
  22828. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  22829. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  22830. * @param {Boolean} force | enabled or disable forcing
  22831. * @param {Boolean} doNotStart | if true do not call start
  22832. *
  22833. */
  22834. exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) {
  22835. var isMovingBeforeClustering = this.moving;
  22836. var amountOfNodes = this.nodeIndices.length;
  22837. // on zoom out collapse the sector if the scale is at the level the sector was made
  22838. if (this.previousScale > this.scale && zoomDirection == 0) {
  22839. this._collapseSector();
  22840. }
  22841. // check if we zoom in or out
  22842. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  22843. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  22844. // outer nodes determines if it is being clustered
  22845. this._formClusters(force);
  22846. }
  22847. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  22848. if (force == true) {
  22849. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  22850. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  22851. this._openClusters(recursive,force);
  22852. }
  22853. else {
  22854. // if a cluster takes up a set percentage of the active window
  22855. this._openClustersBySize();
  22856. }
  22857. }
  22858. this._updateNodeIndexList();
  22859. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  22860. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  22861. this._aggregateHubs(force);
  22862. this._updateNodeIndexList();
  22863. }
  22864. // we now reduce chains.
  22865. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  22866. this.handleChains();
  22867. this._updateNodeIndexList();
  22868. }
  22869. this.previousScale = this.scale;
  22870. // rest of the update the index list, dynamic edges and labels
  22871. this._updateDynamicEdges();
  22872. this.updateLabels();
  22873. // if a cluster was formed, we increase the clusterSession
  22874. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  22875. this.clusterSession += 1;
  22876. // if clusters have been made, we normalize the cluster level
  22877. this.normalizeClusterLevels();
  22878. }
  22879. if (doNotStart == false || doNotStart === undefined) {
  22880. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  22881. if (this.moving != isMovingBeforeClustering) {
  22882. this.start();
  22883. }
  22884. }
  22885. this._updateCalculationNodes();
  22886. };
  22887. /**
  22888. * This function handles the chains. It is called on every updateClusters().
  22889. */
  22890. exports.handleChains = function() {
  22891. // after clustering we check how many chains there are
  22892. var chainPercentage = this._getChainFraction();
  22893. if (chainPercentage > this.constants.clustering.chainThreshold) {
  22894. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  22895. }
  22896. };
  22897. /**
  22898. * this functions starts clustering by hubs
  22899. * The minimum hub threshold is set globally
  22900. *
  22901. * @private
  22902. */
  22903. exports._aggregateHubs = function(force) {
  22904. this._getHubSize();
  22905. this._formClustersByHub(force,false);
  22906. };
  22907. /**
  22908. * This function is fired by keypress. It forces hubs to form.
  22909. *
  22910. */
  22911. exports.forceAggregateHubs = function(doNotStart) {
  22912. var isMovingBeforeClustering = this.moving;
  22913. var amountOfNodes = this.nodeIndices.length;
  22914. this._aggregateHubs(true);
  22915. // update the index list, dynamic edges and labels
  22916. this._updateNodeIndexList();
  22917. this._updateDynamicEdges();
  22918. this.updateLabels();
  22919. // if a cluster was formed, we increase the clusterSession
  22920. if (this.nodeIndices.length != amountOfNodes) {
  22921. this.clusterSession += 1;
  22922. }
  22923. if (doNotStart == false || doNotStart === undefined) {
  22924. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  22925. if (this.moving != isMovingBeforeClustering) {
  22926. this.start();
  22927. }
  22928. }
  22929. };
  22930. /**
  22931. * If a cluster takes up more than a set percentage of the screen, open the cluster
  22932. *
  22933. * @private
  22934. */
  22935. exports._openClustersBySize = function() {
  22936. for (var nodeId in this.nodes) {
  22937. if (this.nodes.hasOwnProperty(nodeId)) {
  22938. var node = this.nodes[nodeId];
  22939. if (node.inView() == true) {
  22940. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  22941. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  22942. this.openCluster(node);
  22943. }
  22944. }
  22945. }
  22946. }
  22947. };
  22948. /**
  22949. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  22950. * has to be opened based on the current zoom level.
  22951. *
  22952. * @private
  22953. */
  22954. exports._openClusters = function(recursive,force) {
  22955. for (var i = 0; i < this.nodeIndices.length; i++) {
  22956. var node = this.nodes[this.nodeIndices[i]];
  22957. this._expandClusterNode(node,recursive,force);
  22958. this._updateCalculationNodes();
  22959. }
  22960. };
  22961. /**
  22962. * This function checks if a node has to be opened. This is done by checking the zoom level.
  22963. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  22964. * This recursive behaviour is optional and can be set by the recursive argument.
  22965. *
  22966. * @param {Node} parentNode | to check for cluster and expand
  22967. * @param {Boolean} recursive | enabled or disable recursive calling
  22968. * @param {Boolean} force | enabled or disable forcing
  22969. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  22970. * @private
  22971. */
  22972. exports._expandClusterNode = function(parentNode, recursive, force, openAll) {
  22973. // first check if node is a cluster
  22974. if (parentNode.clusterSize > 1) {
  22975. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  22976. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  22977. openAll = true;
  22978. }
  22979. recursive = openAll ? true : recursive;
  22980. // if the last child has been added on a smaller scale than current scale decluster
  22981. if (parentNode.formationScale < this.scale || force == true) {
  22982. // we will check if any of the contained child nodes should be removed from the cluster
  22983. for (var containedNodeId in parentNode.containedNodes) {
  22984. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  22985. var childNode = parentNode.containedNodes[containedNodeId];
  22986. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  22987. // the largest cluster is the one that comes from outside
  22988. if (force == true) {
  22989. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  22990. || openAll) {
  22991. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  22992. }
  22993. }
  22994. else {
  22995. if (this._nodeInActiveArea(parentNode)) {
  22996. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  22997. }
  22998. }
  22999. }
  23000. }
  23001. }
  23002. }
  23003. };
  23004. /**
  23005. * ONLY CALLED FROM _expandClusterNode
  23006. *
  23007. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  23008. * the child node from the parent contained_node object and put it back into the global nodes object.
  23009. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  23010. *
  23011. * @param {Node} parentNode | the parent node
  23012. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  23013. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  23014. * With force and recursive both true, the entire cluster is unpacked
  23015. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  23016. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  23017. * @private
  23018. */
  23019. exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) {
  23020. var childNode = parentNode.containedNodes[containedNodeId];
  23021. // if child node has been added on smaller scale than current, kick out
  23022. if (childNode.formationScale < this.scale || force == true) {
  23023. // unselect all selected items
  23024. this._unselectAll();
  23025. // put the child node back in the global nodes object
  23026. this.nodes[containedNodeId] = childNode;
  23027. // release the contained edges from this childNode back into the global edges
  23028. this._releaseContainedEdges(parentNode,childNode);
  23029. // reconnect rerouted edges to the childNode
  23030. this._connectEdgeBackToChild(parentNode,childNode);
  23031. // validate all edges in dynamicEdges
  23032. this._validateEdges(parentNode);
  23033. // undo the changes from the clustering operation on the parent node
  23034. parentNode.options.mass -= childNode.options.mass;
  23035. parentNode.clusterSize -= childNode.clusterSize;
  23036. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  23037. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  23038. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  23039. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  23040. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  23041. // remove node from the list
  23042. delete parentNode.containedNodes[containedNodeId];
  23043. // check if there are other childs with this clusterSession in the parent.
  23044. var othersPresent = false;
  23045. for (var childNodeId in parentNode.containedNodes) {
  23046. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  23047. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  23048. othersPresent = true;
  23049. break;
  23050. }
  23051. }
  23052. }
  23053. // if there are no others, remove the cluster session from the list
  23054. if (othersPresent == false) {
  23055. parentNode.clusterSessions.pop();
  23056. }
  23057. this._repositionBezierNodes(childNode);
  23058. // this._repositionBezierNodes(parentNode);
  23059. // remove the clusterSession from the child node
  23060. childNode.clusterSession = 0;
  23061. // recalculate the size of the node on the next time the node is rendered
  23062. parentNode.clearSizeCache();
  23063. // restart the simulation to reorganise all nodes
  23064. this.moving = true;
  23065. }
  23066. // check if a further expansion step is possible if recursivity is enabled
  23067. if (recursive == true) {
  23068. this._expandClusterNode(childNode,recursive,force,openAll);
  23069. }
  23070. };
  23071. /**
  23072. * position the bezier nodes at the center of the edges
  23073. *
  23074. * @param node
  23075. * @private
  23076. */
  23077. exports._repositionBezierNodes = function(node) {
  23078. for (var i = 0; i < node.dynamicEdges.length; i++) {
  23079. node.dynamicEdges[i].positionBezierNode();
  23080. }
  23081. };
  23082. /**
  23083. * This function checks if any nodes at the end of their trees have edges below a threshold length
  23084. * This function is called only from updateClusters()
  23085. * forceLevelCollapse ignores the length of the edge and collapses one level
  23086. * This means that a node with only one edge will be clustered with its connected node
  23087. *
  23088. * @private
  23089. * @param {Boolean} force
  23090. */
  23091. exports._formClusters = function(force) {
  23092. if (force == false) {
  23093. this._formClustersByZoom();
  23094. }
  23095. else {
  23096. this._forceClustersByZoom();
  23097. }
  23098. };
  23099. /**
  23100. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  23101. *
  23102. * @private
  23103. */
  23104. exports._formClustersByZoom = function() {
  23105. var dx,dy,length,
  23106. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  23107. // check if any edges are shorter than minLength and start the clustering
  23108. // the clustering favours the node with the larger mass
  23109. for (var edgeId in this.edges) {
  23110. if (this.edges.hasOwnProperty(edgeId)) {
  23111. var edge = this.edges[edgeId];
  23112. if (edge.connected) {
  23113. if (edge.toId != edge.fromId) {
  23114. dx = (edge.to.x - edge.from.x);
  23115. dy = (edge.to.y - edge.from.y);
  23116. length = Math.sqrt(dx * dx + dy * dy);
  23117. if (length < minLength) {
  23118. // first check which node is larger
  23119. var parentNode = edge.from;
  23120. var childNode = edge.to;
  23121. if (edge.to.options.mass > edge.from.options.mass) {
  23122. parentNode = edge.to;
  23123. childNode = edge.from;
  23124. }
  23125. if (childNode.dynamicEdgesLength == 1) {
  23126. this._addToCluster(parentNode,childNode,false);
  23127. }
  23128. else if (parentNode.dynamicEdgesLength == 1) {
  23129. this._addToCluster(childNode,parentNode,false);
  23130. }
  23131. }
  23132. }
  23133. }
  23134. }
  23135. }
  23136. };
  23137. /**
  23138. * This function forces the network to cluster all nodes with only one connecting edge to their
  23139. * connected node.
  23140. *
  23141. * @private
  23142. */
  23143. exports._forceClustersByZoom = function() {
  23144. for (var nodeId in this.nodes) {
  23145. // another node could have absorbed this child.
  23146. if (this.nodes.hasOwnProperty(nodeId)) {
  23147. var childNode = this.nodes[nodeId];
  23148. // the edges can be swallowed by another decrease
  23149. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  23150. var edge = childNode.dynamicEdges[0];
  23151. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  23152. // group to the largest node
  23153. if (childNode.id != parentNode.id) {
  23154. if (parentNode.options.mass > childNode.options.mass) {
  23155. this._addToCluster(parentNode,childNode,true);
  23156. }
  23157. else {
  23158. this._addToCluster(childNode,parentNode,true);
  23159. }
  23160. }
  23161. }
  23162. }
  23163. }
  23164. };
  23165. /**
  23166. * To keep the nodes of roughly equal size we normalize the cluster levels.
  23167. * This function clusters a node to its smallest connected neighbour.
  23168. *
  23169. * @param node
  23170. * @private
  23171. */
  23172. exports._clusterToSmallestNeighbour = function(node) {
  23173. var smallestNeighbour = -1;
  23174. var smallestNeighbourNode = null;
  23175. for (var i = 0; i < node.dynamicEdges.length; i++) {
  23176. if (node.dynamicEdges[i] !== undefined) {
  23177. var neighbour = null;
  23178. if (node.dynamicEdges[i].fromId != node.id) {
  23179. neighbour = node.dynamicEdges[i].from;
  23180. }
  23181. else if (node.dynamicEdges[i].toId != node.id) {
  23182. neighbour = node.dynamicEdges[i].to;
  23183. }
  23184. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  23185. smallestNeighbour = neighbour.clusterSessions.length;
  23186. smallestNeighbourNode = neighbour;
  23187. }
  23188. }
  23189. }
  23190. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  23191. this._addToCluster(neighbour, node, true);
  23192. }
  23193. };
  23194. /**
  23195. * This function forms clusters from hubs, it loops over all nodes
  23196. *
  23197. * @param {Boolean} force | Disregard zoom level
  23198. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  23199. * @private
  23200. */
  23201. exports._formClustersByHub = function(force, onlyEqual) {
  23202. // we loop over all nodes in the list
  23203. for (var nodeId in this.nodes) {
  23204. // we check if it is still available since it can be used by the clustering in this loop
  23205. if (this.nodes.hasOwnProperty(nodeId)) {
  23206. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  23207. }
  23208. }
  23209. };
  23210. /**
  23211. * This function forms a cluster from a specific preselected hub node
  23212. *
  23213. * @param {Node} hubNode | the node we will cluster as a hub
  23214. * @param {Boolean} force | Disregard zoom level
  23215. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  23216. * @param {Number} [absorptionSizeOffset] |
  23217. * @private
  23218. */
  23219. exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  23220. if (absorptionSizeOffset === undefined) {
  23221. absorptionSizeOffset = 0;
  23222. }
  23223. // we decide if the node is a hub
  23224. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  23225. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  23226. // initialize variables
  23227. var dx,dy,length;
  23228. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  23229. var allowCluster = false;
  23230. // we create a list of edges because the dynamicEdges change over the course of this loop
  23231. var edgesIdarray = [];
  23232. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  23233. for (var j = 0; j < amountOfInitialEdges; j++) {
  23234. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  23235. }
  23236. // if the hub clustering is not forces, we check if one of the edges connected
  23237. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  23238. if (force == false) {
  23239. allowCluster = false;
  23240. for (j = 0; j < amountOfInitialEdges; j++) {
  23241. var edge = this.edges[edgesIdarray[j]];
  23242. if (edge !== undefined) {
  23243. if (edge.connected) {
  23244. if (edge.toId != edge.fromId) {
  23245. dx = (edge.to.x - edge.from.x);
  23246. dy = (edge.to.y - edge.from.y);
  23247. length = Math.sqrt(dx * dx + dy * dy);
  23248. if (length < minLength) {
  23249. allowCluster = true;
  23250. break;
  23251. }
  23252. }
  23253. }
  23254. }
  23255. }
  23256. }
  23257. // start the clustering if allowed
  23258. if ((!force && allowCluster) || force) {
  23259. // we loop over all edges INITIALLY connected to this hub
  23260. for (j = 0; j < amountOfInitialEdges; j++) {
  23261. edge = this.edges[edgesIdarray[j]];
  23262. // the edge can be clustered by this function in a previous loop
  23263. if (edge !== undefined) {
  23264. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  23265. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  23266. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  23267. (childNode.id != hubNode.id)) {
  23268. this._addToCluster(hubNode,childNode,force);
  23269. }
  23270. }
  23271. }
  23272. }
  23273. }
  23274. };
  23275. /**
  23276. * This function adds the child node to the parent node, creating a cluster if it is not already.
  23277. *
  23278. * @param {Node} parentNode | this is the node that will house the child node
  23279. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  23280. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  23281. * @private
  23282. */
  23283. exports._addToCluster = function(parentNode, childNode, force) {
  23284. // join child node in the parent node
  23285. parentNode.containedNodes[childNode.id] = childNode;
  23286. // manage all the edges connected to the child and parent nodes
  23287. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  23288. var edge = childNode.dynamicEdges[i];
  23289. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  23290. this._addToContainedEdges(parentNode,childNode,edge);
  23291. }
  23292. else {
  23293. this._connectEdgeToCluster(parentNode,childNode,edge);
  23294. }
  23295. }
  23296. // a contained node has no dynamic edges.
  23297. childNode.dynamicEdges = [];
  23298. // remove circular edges from clusters
  23299. this._containCircularEdgesFromNode(parentNode,childNode);
  23300. // remove the childNode from the global nodes object
  23301. delete this.nodes[childNode.id];
  23302. // update the properties of the child and parent
  23303. var massBefore = parentNode.options.mass;
  23304. childNode.clusterSession = this.clusterSession;
  23305. parentNode.options.mass += childNode.options.mass;
  23306. parentNode.clusterSize += childNode.clusterSize;
  23307. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  23308. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  23309. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  23310. parentNode.clusterSessions.push(this.clusterSession);
  23311. }
  23312. // forced clusters only open from screen size and double tap
  23313. if (force == true) {
  23314. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  23315. parentNode.formationScale = 0;
  23316. }
  23317. else {
  23318. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  23319. }
  23320. // recalculate the size of the node on the next time the node is rendered
  23321. parentNode.clearSizeCache();
  23322. // set the pop-out scale for the childnode
  23323. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  23324. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  23325. childNode.clearVelocity();
  23326. // the mass has altered, preservation of energy dictates the velocity to be updated
  23327. parentNode.updateVelocity(massBefore);
  23328. // restart the simulation to reorganise all nodes
  23329. this.moving = true;
  23330. };
  23331. /**
  23332. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  23333. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  23334. * It has to be called if a level is collapsed. It is called by _formClusters().
  23335. * @private
  23336. */
  23337. exports._updateDynamicEdges = function() {
  23338. for (var i = 0; i < this.nodeIndices.length; i++) {
  23339. var node = this.nodes[this.nodeIndices[i]];
  23340. node.dynamicEdgesLength = node.dynamicEdges.length;
  23341. // this corrects for multiple edges pointing at the same other node
  23342. var correction = 0;
  23343. if (node.dynamicEdgesLength > 1) {
  23344. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  23345. var edgeToId = node.dynamicEdges[j].toId;
  23346. var edgeFromId = node.dynamicEdges[j].fromId;
  23347. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  23348. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  23349. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  23350. correction += 1;
  23351. }
  23352. }
  23353. }
  23354. }
  23355. node.dynamicEdgesLength -= correction;
  23356. }
  23357. };
  23358. /**
  23359. * This adds an edge from the childNode to the contained edges of the parent node
  23360. *
  23361. * @param parentNode | Node object
  23362. * @param childNode | Node object
  23363. * @param edge | Edge object
  23364. * @private
  23365. */
  23366. exports._addToContainedEdges = function(parentNode, childNode, edge) {
  23367. // create an array object if it does not yet exist for this childNode
  23368. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  23369. parentNode.containedEdges[childNode.id] = []
  23370. }
  23371. // add this edge to the list
  23372. parentNode.containedEdges[childNode.id].push(edge);
  23373. // remove the edge from the global edges object
  23374. delete this.edges[edge.id];
  23375. // remove the edge from the parent object
  23376. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  23377. if (parentNode.dynamicEdges[i].id == edge.id) {
  23378. parentNode.dynamicEdges.splice(i,1);
  23379. break;
  23380. }
  23381. }
  23382. };
  23383. /**
  23384. * This function connects an edge that was connected to a child node to the parent node.
  23385. * It keeps track of which nodes it has been connected to with the originalId array.
  23386. *
  23387. * @param {Node} parentNode | Node object
  23388. * @param {Node} childNode | Node object
  23389. * @param {Edge} edge | Edge object
  23390. * @private
  23391. */
  23392. exports._connectEdgeToCluster = function(parentNode, childNode, edge) {
  23393. // handle circular edges
  23394. if (edge.toId == edge.fromId) {
  23395. this._addToContainedEdges(parentNode, childNode, edge);
  23396. }
  23397. else {
  23398. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  23399. edge.originalToId.push(childNode.id);
  23400. edge.to = parentNode;
  23401. edge.toId = parentNode.id;
  23402. }
  23403. else { // edge connected to other node with the "from" side
  23404. edge.originalFromId.push(childNode.id);
  23405. edge.from = parentNode;
  23406. edge.fromId = parentNode.id;
  23407. }
  23408. this._addToReroutedEdges(parentNode,childNode,edge);
  23409. }
  23410. };
  23411. /**
  23412. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  23413. * these edges inside of the cluster.
  23414. *
  23415. * @param parentNode
  23416. * @param childNode
  23417. * @private
  23418. */
  23419. exports._containCircularEdgesFromNode = function(parentNode, childNode) {
  23420. // manage all the edges connected to the child and parent nodes
  23421. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  23422. var edge = parentNode.dynamicEdges[i];
  23423. // handle circular edges
  23424. if (edge.toId == edge.fromId) {
  23425. this._addToContainedEdges(parentNode, childNode, edge);
  23426. }
  23427. }
  23428. };
  23429. /**
  23430. * This adds an edge from the childNode to the rerouted edges of the parent node
  23431. *
  23432. * @param parentNode | Node object
  23433. * @param childNode | Node object
  23434. * @param edge | Edge object
  23435. * @private
  23436. */
  23437. exports._addToReroutedEdges = function(parentNode, childNode, edge) {
  23438. // create an array object if it does not yet exist for this childNode
  23439. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  23440. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  23441. parentNode.reroutedEdges[childNode.id] = [];
  23442. }
  23443. parentNode.reroutedEdges[childNode.id].push(edge);
  23444. // this edge becomes part of the dynamicEdges of the cluster node
  23445. parentNode.dynamicEdges.push(edge);
  23446. };
  23447. /**
  23448. * This function connects an edge that was connected to a cluster node back to the child node.
  23449. *
  23450. * @param parentNode | Node object
  23451. * @param childNode | Node object
  23452. * @private
  23453. */
  23454. exports._connectEdgeBackToChild = function(parentNode, childNode) {
  23455. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  23456. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  23457. var edge = parentNode.reroutedEdges[childNode.id][i];
  23458. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  23459. edge.originalFromId.pop();
  23460. edge.fromId = childNode.id;
  23461. edge.from = childNode;
  23462. }
  23463. else {
  23464. edge.originalToId.pop();
  23465. edge.toId = childNode.id;
  23466. edge.to = childNode;
  23467. }
  23468. // append this edge to the list of edges connecting to the childnode
  23469. childNode.dynamicEdges.push(edge);
  23470. // remove the edge from the parent object
  23471. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  23472. if (parentNode.dynamicEdges[j].id == edge.id) {
  23473. parentNode.dynamicEdges.splice(j,1);
  23474. break;
  23475. }
  23476. }
  23477. }
  23478. // remove the entry from the rerouted edges
  23479. delete parentNode.reroutedEdges[childNode.id];
  23480. }
  23481. };
  23482. /**
  23483. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  23484. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  23485. * parentNode
  23486. *
  23487. * @param parentNode | Node object
  23488. * @private
  23489. */
  23490. exports._validateEdges = function(parentNode) {
  23491. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  23492. var edge = parentNode.dynamicEdges[i];
  23493. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  23494. parentNode.dynamicEdges.splice(i,1);
  23495. }
  23496. }
  23497. };
  23498. /**
  23499. * This function released the contained edges back into the global domain and puts them back into the
  23500. * dynamic edges of both parent and child.
  23501. *
  23502. * @param {Node} parentNode |
  23503. * @param {Node} childNode |
  23504. * @private
  23505. */
  23506. exports._releaseContainedEdges = function(parentNode, childNode) {
  23507. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  23508. var edge = parentNode.containedEdges[childNode.id][i];
  23509. // put the edge back in the global edges object
  23510. this.edges[edge.id] = edge;
  23511. // put the edge back in the dynamic edges of the child and parent
  23512. childNode.dynamicEdges.push(edge);
  23513. parentNode.dynamicEdges.push(edge);
  23514. }
  23515. // remove the entry from the contained edges
  23516. delete parentNode.containedEdges[childNode.id];
  23517. };
  23518. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  23519. /**
  23520. * This updates the node labels for all nodes (for debugging purposes)
  23521. */
  23522. exports.updateLabels = function() {
  23523. var nodeId;
  23524. // update node labels
  23525. for (nodeId in this.nodes) {
  23526. if (this.nodes.hasOwnProperty(nodeId)) {
  23527. var node = this.nodes[nodeId];
  23528. if (node.clusterSize > 1) {
  23529. node.label = "[".concat(String(node.clusterSize),"]");
  23530. }
  23531. }
  23532. }
  23533. // update node labels
  23534. for (nodeId in this.nodes) {
  23535. if (this.nodes.hasOwnProperty(nodeId)) {
  23536. node = this.nodes[nodeId];
  23537. if (node.clusterSize == 1) {
  23538. if (node.originalLabel !== undefined) {
  23539. node.label = node.originalLabel;
  23540. }
  23541. else {
  23542. node.label = String(node.id);
  23543. }
  23544. }
  23545. }
  23546. }
  23547. // /* Debug Override */
  23548. // for (nodeId in this.nodes) {
  23549. // if (this.nodes.hasOwnProperty(nodeId)) {
  23550. // node = this.nodes[nodeId];
  23551. // node.label = String(node.level);
  23552. // }
  23553. // }
  23554. };
  23555. /**
  23556. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  23557. * if the rest of the nodes are already a few cluster levels in.
  23558. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  23559. * clustered enough to the clusterToSmallestNeighbours function.
  23560. */
  23561. exports.normalizeClusterLevels = function() {
  23562. var maxLevel = 0;
  23563. var minLevel = 1e9;
  23564. var clusterLevel = 0;
  23565. var nodeId;
  23566. // we loop over all nodes in the list
  23567. for (nodeId in this.nodes) {
  23568. if (this.nodes.hasOwnProperty(nodeId)) {
  23569. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  23570. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  23571. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  23572. }
  23573. }
  23574. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  23575. var amountOfNodes = this.nodeIndices.length;
  23576. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  23577. // we loop over all nodes in the list
  23578. for (nodeId in this.nodes) {
  23579. if (this.nodes.hasOwnProperty(nodeId)) {
  23580. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  23581. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  23582. }
  23583. }
  23584. }
  23585. this._updateNodeIndexList();
  23586. this._updateDynamicEdges();
  23587. // if a cluster was formed, we increase the clusterSession
  23588. if (this.nodeIndices.length != amountOfNodes) {
  23589. this.clusterSession += 1;
  23590. }
  23591. }
  23592. };
  23593. /**
  23594. * This function determines if the cluster we want to decluster is in the active area
  23595. * this means around the zoom center
  23596. *
  23597. * @param {Node} node
  23598. * @returns {boolean}
  23599. * @private
  23600. */
  23601. exports._nodeInActiveArea = function(node) {
  23602. return (
  23603. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  23604. &&
  23605. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  23606. )
  23607. };
  23608. /**
  23609. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  23610. * It puts large clusters away from the center and randomizes the order.
  23611. *
  23612. */
  23613. exports.repositionNodes = function() {
  23614. for (var i = 0; i < this.nodeIndices.length; i++) {
  23615. var node = this.nodes[this.nodeIndices[i]];
  23616. if ((node.xFixed == false || node.yFixed == false)) {
  23617. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass);
  23618. var angle = 2 * Math.PI * Math.random();
  23619. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  23620. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  23621. this._repositionBezierNodes(node);
  23622. }
  23623. }
  23624. };
  23625. /**
  23626. * We determine how many connections denote an important hub.
  23627. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  23628. *
  23629. * @private
  23630. */
  23631. exports._getHubSize = function() {
  23632. var average = 0;
  23633. var averageSquared = 0;
  23634. var hubCounter = 0;
  23635. var largestHub = 0;
  23636. for (var i = 0; i < this.nodeIndices.length; i++) {
  23637. var node = this.nodes[this.nodeIndices[i]];
  23638. if (node.dynamicEdgesLength > largestHub) {
  23639. largestHub = node.dynamicEdgesLength;
  23640. }
  23641. average += node.dynamicEdgesLength;
  23642. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  23643. hubCounter += 1;
  23644. }
  23645. average = average / hubCounter;
  23646. averageSquared = averageSquared / hubCounter;
  23647. var variance = averageSquared - Math.pow(average,2);
  23648. var standardDeviation = Math.sqrt(variance);
  23649. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  23650. // always have at least one to cluster
  23651. if (this.hubThreshold > largestHub) {
  23652. this.hubThreshold = largestHub;
  23653. }
  23654. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  23655. // console.log("hubThreshold:",this.hubThreshold);
  23656. };
  23657. /**
  23658. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  23659. * with this amount we can cluster specifically on these chains.
  23660. *
  23661. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  23662. * @private
  23663. */
  23664. exports._reduceAmountOfChains = function(fraction) {
  23665. this.hubThreshold = 2;
  23666. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  23667. for (var nodeId in this.nodes) {
  23668. if (this.nodes.hasOwnProperty(nodeId)) {
  23669. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  23670. if (reduceAmount > 0) {
  23671. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  23672. reduceAmount -= 1;
  23673. }
  23674. }
  23675. }
  23676. }
  23677. };
  23678. /**
  23679. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  23680. * with this amount we can cluster specifically on these chains.
  23681. *
  23682. * @private
  23683. */
  23684. exports._getChainFraction = function() {
  23685. var chains = 0;
  23686. var total = 0;
  23687. for (var nodeId in this.nodes) {
  23688. if (this.nodes.hasOwnProperty(nodeId)) {
  23689. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  23690. chains += 1;
  23691. }
  23692. total += 1;
  23693. }
  23694. }
  23695. return chains/total;
  23696. };
  23697. /***/ },
  23698. /* 51 */
  23699. /***/ function(module, exports, __webpack_require__) {
  23700. var util = __webpack_require__(1);
  23701. /**
  23702. * Creation of the SectorMixin var.
  23703. *
  23704. * This contains all the functions the Network object can use to employ the sector system.
  23705. * The sector system is always used by Network, though the benefits only apply to the use of clustering.
  23706. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  23707. */
  23708. /**
  23709. * This function is only called by the setData function of the Network object.
  23710. * This loads the global references into the active sector. This initializes the sector.
  23711. *
  23712. * @private
  23713. */
  23714. exports._putDataInSector = function() {
  23715. this.sectors["active"][this._sector()].nodes = this.nodes;
  23716. this.sectors["active"][this._sector()].edges = this.edges;
  23717. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  23718. };
  23719. /**
  23720. * /**
  23721. * This function sets the global references to nodes, edges and nodeIndices back to
  23722. * those of the supplied (active) sector. If a type is defined, do the specific type
  23723. *
  23724. * @param {String} sectorId
  23725. * @param {String} [sectorType] | "active" or "frozen"
  23726. * @private
  23727. */
  23728. exports._switchToSector = function(sectorId, sectorType) {
  23729. if (sectorType === undefined || sectorType == "active") {
  23730. this._switchToActiveSector(sectorId);
  23731. }
  23732. else {
  23733. this._switchToFrozenSector(sectorId);
  23734. }
  23735. };
  23736. /**
  23737. * This function sets the global references to nodes, edges and nodeIndices back to
  23738. * those of the supplied active sector.
  23739. *
  23740. * @param sectorId
  23741. * @private
  23742. */
  23743. exports._switchToActiveSector = function(sectorId) {
  23744. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  23745. this.nodes = this.sectors["active"][sectorId]["nodes"];
  23746. this.edges = this.sectors["active"][sectorId]["edges"];
  23747. };
  23748. /**
  23749. * This function sets the global references to nodes, edges and nodeIndices back to
  23750. * those of the supplied active sector.
  23751. *
  23752. * @private
  23753. */
  23754. exports._switchToSupportSector = function() {
  23755. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  23756. this.nodes = this.sectors["support"]["nodes"];
  23757. this.edges = this.sectors["support"]["edges"];
  23758. };
  23759. /**
  23760. * This function sets the global references to nodes, edges and nodeIndices back to
  23761. * those of the supplied frozen sector.
  23762. *
  23763. * @param sectorId
  23764. * @private
  23765. */
  23766. exports._switchToFrozenSector = function(sectorId) {
  23767. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  23768. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  23769. this.edges = this.sectors["frozen"][sectorId]["edges"];
  23770. };
  23771. /**
  23772. * This function sets the global references to nodes, edges and nodeIndices back to
  23773. * those of the currently active sector.
  23774. *
  23775. * @private
  23776. */
  23777. exports._loadLatestSector = function() {
  23778. this._switchToSector(this._sector());
  23779. };
  23780. /**
  23781. * This function returns the currently active sector Id
  23782. *
  23783. * @returns {String}
  23784. * @private
  23785. */
  23786. exports._sector = function() {
  23787. return this.activeSector[this.activeSector.length-1];
  23788. };
  23789. /**
  23790. * This function returns the previously active sector Id
  23791. *
  23792. * @returns {String}
  23793. * @private
  23794. */
  23795. exports._previousSector = function() {
  23796. if (this.activeSector.length > 1) {
  23797. return this.activeSector[this.activeSector.length-2];
  23798. }
  23799. else {
  23800. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  23801. }
  23802. };
  23803. /**
  23804. * We add the active sector at the end of the this.activeSector array
  23805. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  23806. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  23807. *
  23808. * @param newId
  23809. * @private
  23810. */
  23811. exports._setActiveSector = function(newId) {
  23812. this.activeSector.push(newId);
  23813. };
  23814. /**
  23815. * We remove the currently active sector id from the active sector stack. This happens when
  23816. * we reactivate the previously active sector
  23817. *
  23818. * @private
  23819. */
  23820. exports._forgetLastSector = function() {
  23821. this.activeSector.pop();
  23822. };
  23823. /**
  23824. * This function creates a new active sector with the supplied newId. This newId
  23825. * is the expanding node id.
  23826. *
  23827. * @param {String} newId | Id of the new active sector
  23828. * @private
  23829. */
  23830. exports._createNewSector = function(newId) {
  23831. // create the new sector
  23832. this.sectors["active"][newId] = {"nodes":{},
  23833. "edges":{},
  23834. "nodeIndices":[],
  23835. "formationScale": this.scale,
  23836. "drawingNode": undefined};
  23837. // create the new sector render node. This gives visual feedback that you are in a new sector.
  23838. this.sectors["active"][newId]['drawingNode'] = new Node(
  23839. {id:newId,
  23840. color: {
  23841. background: "#eaefef",
  23842. border: "495c5e"
  23843. }
  23844. },{},{},this.constants);
  23845. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  23846. };
  23847. /**
  23848. * This function removes the currently active sector. This is called when we create a new
  23849. * active sector.
  23850. *
  23851. * @param {String} sectorId | Id of the active sector that will be removed
  23852. * @private
  23853. */
  23854. exports._deleteActiveSector = function(sectorId) {
  23855. delete this.sectors["active"][sectorId];
  23856. };
  23857. /**
  23858. * This function removes the currently active sector. This is called when we reactivate
  23859. * the previously active sector.
  23860. *
  23861. * @param {String} sectorId | Id of the active sector that will be removed
  23862. * @private
  23863. */
  23864. exports._deleteFrozenSector = function(sectorId) {
  23865. delete this.sectors["frozen"][sectorId];
  23866. };
  23867. /**
  23868. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  23869. * We copy the references, then delete the active entree.
  23870. *
  23871. * @param sectorId
  23872. * @private
  23873. */
  23874. exports._freezeSector = function(sectorId) {
  23875. // we move the set references from the active to the frozen stack.
  23876. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  23877. // we have moved the sector data into the frozen set, we now remove it from the active set
  23878. this._deleteActiveSector(sectorId);
  23879. };
  23880. /**
  23881. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  23882. * object to the "active" object.
  23883. *
  23884. * @param sectorId
  23885. * @private
  23886. */
  23887. exports._activateSector = function(sectorId) {
  23888. // we move the set references from the frozen to the active stack.
  23889. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  23890. // we have moved the sector data into the active set, we now remove it from the frozen stack
  23891. this._deleteFrozenSector(sectorId);
  23892. };
  23893. /**
  23894. * This function merges the data from the currently active sector with a frozen sector. This is used
  23895. * in the process of reverting back to the previously active sector.
  23896. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  23897. * upon the creation of a new active sector.
  23898. *
  23899. * @param sectorId
  23900. * @private
  23901. */
  23902. exports._mergeThisWithFrozen = function(sectorId) {
  23903. // copy all nodes
  23904. for (var nodeId in this.nodes) {
  23905. if (this.nodes.hasOwnProperty(nodeId)) {
  23906. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  23907. }
  23908. }
  23909. // copy all edges (if not fully clustered, else there are no edges)
  23910. for (var edgeId in this.edges) {
  23911. if (this.edges.hasOwnProperty(edgeId)) {
  23912. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  23913. }
  23914. }
  23915. // merge the nodeIndices
  23916. for (var i = 0; i < this.nodeIndices.length; i++) {
  23917. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  23918. }
  23919. };
  23920. /**
  23921. * This clusters the sector to one cluster. It was a single cluster before this process started so
  23922. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  23923. *
  23924. * @private
  23925. */
  23926. exports._collapseThisToSingleCluster = function() {
  23927. this.clusterToFit(1,false);
  23928. };
  23929. /**
  23930. * We create a new active sector from the node that we want to open.
  23931. *
  23932. * @param node
  23933. * @private
  23934. */
  23935. exports._addSector = function(node) {
  23936. // this is the currently active sector
  23937. var sector = this._sector();
  23938. // // this should allow me to select nodes from a frozen set.
  23939. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  23940. // console.log("the node is part of the active sector");
  23941. // }
  23942. // else {
  23943. // console.log("I dont know what the fuck happened!!");
  23944. // }
  23945. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  23946. delete this.nodes[node.id];
  23947. var unqiueIdentifier = util.randomUUID();
  23948. // we fully freeze the currently active sector
  23949. this._freezeSector(sector);
  23950. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  23951. this._createNewSector(unqiueIdentifier);
  23952. // we add the active sector to the sectors array to be able to revert these steps later on
  23953. this._setActiveSector(unqiueIdentifier);
  23954. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  23955. this._switchToSector(this._sector());
  23956. // finally we add the node we removed from our previous active sector to the new active sector
  23957. this.nodes[node.id] = node;
  23958. };
  23959. /**
  23960. * We close the sector that is currently open and revert back to the one before.
  23961. * If the active sector is the "default" sector, nothing happens.
  23962. *
  23963. * @private
  23964. */
  23965. exports._collapseSector = function() {
  23966. // the currently active sector
  23967. var sector = this._sector();
  23968. // we cannot collapse the default sector
  23969. if (sector != "default") {
  23970. if ((this.nodeIndices.length == 1) ||
  23971. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  23972. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  23973. var previousSector = this._previousSector();
  23974. // we collapse the sector back to a single cluster
  23975. this._collapseThisToSingleCluster();
  23976. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  23977. // This previous sector is the one we will reactivate
  23978. this._mergeThisWithFrozen(previousSector);
  23979. // the previously active (frozen) sector now has all the data from the currently active sector.
  23980. // we can now delete the active sector.
  23981. this._deleteActiveSector(sector);
  23982. // we activate the previously active (and currently frozen) sector.
  23983. this._activateSector(previousSector);
  23984. // we load the references from the newly active sector into the global references
  23985. this._switchToSector(previousSector);
  23986. // we forget the previously active sector because we reverted to the one before
  23987. this._forgetLastSector();
  23988. // finally, we update the node index list.
  23989. this._updateNodeIndexList();
  23990. // we refresh the list with calulation nodes and calculation node indices.
  23991. this._updateCalculationNodes();
  23992. }
  23993. }
  23994. };
  23995. /**
  23996. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  23997. *
  23998. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  23999. * | we dont pass the function itself because then the "this" is the window object
  24000. * | instead of the Network object
  24001. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  24002. * @private
  24003. */
  24004. exports._doInAllActiveSectors = function(runFunction,argument) {
  24005. if (argument === undefined) {
  24006. for (var sector in this.sectors["active"]) {
  24007. if (this.sectors["active"].hasOwnProperty(sector)) {
  24008. // switch the global references to those of this sector
  24009. this._switchToActiveSector(sector);
  24010. this[runFunction]();
  24011. }
  24012. }
  24013. }
  24014. else {
  24015. for (var sector in this.sectors["active"]) {
  24016. if (this.sectors["active"].hasOwnProperty(sector)) {
  24017. // switch the global references to those of this sector
  24018. this._switchToActiveSector(sector);
  24019. var args = Array.prototype.splice.call(arguments, 1);
  24020. if (args.length > 1) {
  24021. this[runFunction](args[0],args[1]);
  24022. }
  24023. else {
  24024. this[runFunction](argument);
  24025. }
  24026. }
  24027. }
  24028. }
  24029. // we revert the global references back to our active sector
  24030. this._loadLatestSector();
  24031. };
  24032. /**
  24033. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  24034. *
  24035. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  24036. * | we dont pass the function itself because then the "this" is the window object
  24037. * | instead of the Network object
  24038. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  24039. * @private
  24040. */
  24041. exports._doInSupportSector = function(runFunction,argument) {
  24042. if (argument === undefined) {
  24043. this._switchToSupportSector();
  24044. this[runFunction]();
  24045. }
  24046. else {
  24047. this._switchToSupportSector();
  24048. var args = Array.prototype.splice.call(arguments, 1);
  24049. if (args.length > 1) {
  24050. this[runFunction](args[0],args[1]);
  24051. }
  24052. else {
  24053. this[runFunction](argument);
  24054. }
  24055. }
  24056. // we revert the global references back to our active sector
  24057. this._loadLatestSector();
  24058. };
  24059. /**
  24060. * This runs a function in all frozen sectors. This is used in the _redraw().
  24061. *
  24062. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  24063. * | we don't pass the function itself because then the "this" is the window object
  24064. * | instead of the Network object
  24065. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  24066. * @private
  24067. */
  24068. exports._doInAllFrozenSectors = function(runFunction,argument) {
  24069. if (argument === undefined) {
  24070. for (var sector in this.sectors["frozen"]) {
  24071. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  24072. // switch the global references to those of this sector
  24073. this._switchToFrozenSector(sector);
  24074. this[runFunction]();
  24075. }
  24076. }
  24077. }
  24078. else {
  24079. for (var sector in this.sectors["frozen"]) {
  24080. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  24081. // switch the global references to those of this sector
  24082. this._switchToFrozenSector(sector);
  24083. var args = Array.prototype.splice.call(arguments, 1);
  24084. if (args.length > 1) {
  24085. this[runFunction](args[0],args[1]);
  24086. }
  24087. else {
  24088. this[runFunction](argument);
  24089. }
  24090. }
  24091. }
  24092. }
  24093. this._loadLatestSector();
  24094. };
  24095. /**
  24096. * This runs a function in all sectors. This is used in the _redraw().
  24097. *
  24098. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  24099. * | we don't pass the function itself because then the "this" is the window object
  24100. * | instead of the Network object
  24101. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  24102. * @private
  24103. */
  24104. exports._doInAllSectors = function(runFunction,argument) {
  24105. var args = Array.prototype.splice.call(arguments, 1);
  24106. if (argument === undefined) {
  24107. this._doInAllActiveSectors(runFunction);
  24108. this._doInAllFrozenSectors(runFunction);
  24109. }
  24110. else {
  24111. if (args.length > 1) {
  24112. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  24113. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  24114. }
  24115. else {
  24116. this._doInAllActiveSectors(runFunction,argument);
  24117. this._doInAllFrozenSectors(runFunction,argument);
  24118. }
  24119. }
  24120. };
  24121. /**
  24122. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  24123. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  24124. *
  24125. * @private
  24126. */
  24127. exports._clearNodeIndexList = function() {
  24128. var sector = this._sector();
  24129. this.sectors["active"][sector]["nodeIndices"] = [];
  24130. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  24131. };
  24132. /**
  24133. * Draw the encompassing sector node
  24134. *
  24135. * @param ctx
  24136. * @param sectorType
  24137. * @private
  24138. */
  24139. exports._drawSectorNodes = function(ctx,sectorType) {
  24140. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  24141. for (var sector in this.sectors[sectorType]) {
  24142. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  24143. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  24144. this._switchToSector(sector,sectorType);
  24145. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  24146. for (var nodeId in this.nodes) {
  24147. if (this.nodes.hasOwnProperty(nodeId)) {
  24148. node = this.nodes[nodeId];
  24149. node.resize(ctx);
  24150. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  24151. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  24152. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  24153. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  24154. }
  24155. }
  24156. node = this.sectors[sectorType][sector]["drawingNode"];
  24157. node.x = 0.5 * (maxX + minX);
  24158. node.y = 0.5 * (maxY + minY);
  24159. node.width = 2 * (node.x - minX);
  24160. node.height = 2 * (node.y - minY);
  24161. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  24162. node.setScale(this.scale);
  24163. node._drawCircle(ctx);
  24164. }
  24165. }
  24166. }
  24167. };
  24168. exports._drawAllSectorNodes = function(ctx) {
  24169. this._drawSectorNodes(ctx,"frozen");
  24170. this._drawSectorNodes(ctx,"active");
  24171. this._loadLatestSector();
  24172. };
  24173. /***/ },
  24174. /* 52 */
  24175. /***/ function(module, exports, __webpack_require__) {
  24176. var Node = __webpack_require__(36);
  24177. /**
  24178. * This function can be called from the _doInAllSectors function
  24179. *
  24180. * @param object
  24181. * @param overlappingNodes
  24182. * @private
  24183. */
  24184. exports._getNodesOverlappingWith = function(object, overlappingNodes) {
  24185. var nodes = this.nodes;
  24186. for (var nodeId in nodes) {
  24187. if (nodes.hasOwnProperty(nodeId)) {
  24188. if (nodes[nodeId].isOverlappingWith(object)) {
  24189. overlappingNodes.push(nodeId);
  24190. }
  24191. }
  24192. }
  24193. };
  24194. /**
  24195. * retrieve all nodes overlapping with given object
  24196. * @param {Object} object An object with parameters left, top, right, bottom
  24197. * @return {Number[]} An array with id's of the overlapping nodes
  24198. * @private
  24199. */
  24200. exports._getAllNodesOverlappingWith = function (object) {
  24201. var overlappingNodes = [];
  24202. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  24203. return overlappingNodes;
  24204. };
  24205. /**
  24206. * Return a position object in canvasspace from a single point in screenspace
  24207. *
  24208. * @param pointer
  24209. * @returns {{left: number, top: number, right: number, bottom: number}}
  24210. * @private
  24211. */
  24212. exports._pointerToPositionObject = function(pointer) {
  24213. var x = this._XconvertDOMtoCanvas(pointer.x);
  24214. var y = this._YconvertDOMtoCanvas(pointer.y);
  24215. return {
  24216. left: x,
  24217. top: y,
  24218. right: x,
  24219. bottom: y
  24220. };
  24221. };
  24222. /**
  24223. * Get the top node at the a specific point (like a click)
  24224. *
  24225. * @param {{x: Number, y: Number}} pointer
  24226. * @return {Node | null} node
  24227. * @private
  24228. */
  24229. exports._getNodeAt = function (pointer) {
  24230. // we first check if this is an navigation controls element
  24231. var positionObject = this._pointerToPositionObject(pointer);
  24232. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  24233. // if there are overlapping nodes, select the last one, this is the
  24234. // one which is drawn on top of the others
  24235. if (overlappingNodes.length > 0) {
  24236. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  24237. }
  24238. else {
  24239. return null;
  24240. }
  24241. };
  24242. /**
  24243. * retrieve all edges overlapping with given object, selector is around center
  24244. * @param {Object} object An object with parameters left, top, right, bottom
  24245. * @return {Number[]} An array with id's of the overlapping nodes
  24246. * @private
  24247. */
  24248. exports._getEdgesOverlappingWith = function (object, overlappingEdges) {
  24249. var edges = this.edges;
  24250. for (var edgeId in edges) {
  24251. if (edges.hasOwnProperty(edgeId)) {
  24252. if (edges[edgeId].isOverlappingWith(object)) {
  24253. overlappingEdges.push(edgeId);
  24254. }
  24255. }
  24256. }
  24257. };
  24258. /**
  24259. * retrieve all nodes overlapping with given object
  24260. * @param {Object} object An object with parameters left, top, right, bottom
  24261. * @return {Number[]} An array with id's of the overlapping nodes
  24262. * @private
  24263. */
  24264. exports._getAllEdgesOverlappingWith = function (object) {
  24265. var overlappingEdges = [];
  24266. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  24267. return overlappingEdges;
  24268. };
  24269. /**
  24270. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  24271. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  24272. *
  24273. * @param pointer
  24274. * @returns {null}
  24275. * @private
  24276. */
  24277. exports._getEdgeAt = function(pointer) {
  24278. var positionObject = this._pointerToPositionObject(pointer);
  24279. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  24280. if (overlappingEdges.length > 0) {
  24281. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  24282. }
  24283. else {
  24284. return null;
  24285. }
  24286. };
  24287. /**
  24288. * Add object to the selection array.
  24289. *
  24290. * @param obj
  24291. * @private
  24292. */
  24293. exports._addToSelection = function(obj) {
  24294. if (obj instanceof Node) {
  24295. this.selectionObj.nodes[obj.id] = obj;
  24296. }
  24297. else {
  24298. this.selectionObj.edges[obj.id] = obj;
  24299. }
  24300. };
  24301. /**
  24302. * Add object to the selection array.
  24303. *
  24304. * @param obj
  24305. * @private
  24306. */
  24307. exports._addToHover = function(obj) {
  24308. if (obj instanceof Node) {
  24309. this.hoverObj.nodes[obj.id] = obj;
  24310. }
  24311. else {
  24312. this.hoverObj.edges[obj.id] = obj;
  24313. }
  24314. };
  24315. /**
  24316. * Remove a single option from selection.
  24317. *
  24318. * @param {Object} obj
  24319. * @private
  24320. */
  24321. exports._removeFromSelection = function(obj) {
  24322. if (obj instanceof Node) {
  24323. delete this.selectionObj.nodes[obj.id];
  24324. }
  24325. else {
  24326. delete this.selectionObj.edges[obj.id];
  24327. }
  24328. };
  24329. /**
  24330. * Unselect all. The selectionObj is useful for this.
  24331. *
  24332. * @param {Boolean} [doNotTrigger] | ignore trigger
  24333. * @private
  24334. */
  24335. exports._unselectAll = function(doNotTrigger) {
  24336. if (doNotTrigger === undefined) {
  24337. doNotTrigger = false;
  24338. }
  24339. for(var nodeId in this.selectionObj.nodes) {
  24340. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24341. this.selectionObj.nodes[nodeId].unselect();
  24342. }
  24343. }
  24344. for(var edgeId in this.selectionObj.edges) {
  24345. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24346. this.selectionObj.edges[edgeId].unselect();
  24347. }
  24348. }
  24349. this.selectionObj = {nodes:{},edges:{}};
  24350. if (doNotTrigger == false) {
  24351. this.emit('select', this.getSelection());
  24352. }
  24353. };
  24354. /**
  24355. * Unselect all clusters. The selectionObj is useful for this.
  24356. *
  24357. * @param {Boolean} [doNotTrigger] | ignore trigger
  24358. * @private
  24359. */
  24360. exports._unselectClusters = function(doNotTrigger) {
  24361. if (doNotTrigger === undefined) {
  24362. doNotTrigger = false;
  24363. }
  24364. for (var nodeId in this.selectionObj.nodes) {
  24365. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24366. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  24367. this.selectionObj.nodes[nodeId].unselect();
  24368. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  24369. }
  24370. }
  24371. }
  24372. if (doNotTrigger == false) {
  24373. this.emit('select', this.getSelection());
  24374. }
  24375. };
  24376. /**
  24377. * return the number of selected nodes
  24378. *
  24379. * @returns {number}
  24380. * @private
  24381. */
  24382. exports._getSelectedNodeCount = function() {
  24383. var count = 0;
  24384. for (var nodeId in this.selectionObj.nodes) {
  24385. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24386. count += 1;
  24387. }
  24388. }
  24389. return count;
  24390. };
  24391. /**
  24392. * return the selected node
  24393. *
  24394. * @returns {number}
  24395. * @private
  24396. */
  24397. exports._getSelectedNode = function() {
  24398. for (var nodeId in this.selectionObj.nodes) {
  24399. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24400. return this.selectionObj.nodes[nodeId];
  24401. }
  24402. }
  24403. return null;
  24404. };
  24405. /**
  24406. * return the selected edge
  24407. *
  24408. * @returns {number}
  24409. * @private
  24410. */
  24411. exports._getSelectedEdge = function() {
  24412. for (var edgeId in this.selectionObj.edges) {
  24413. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24414. return this.selectionObj.edges[edgeId];
  24415. }
  24416. }
  24417. return null;
  24418. };
  24419. /**
  24420. * return the number of selected edges
  24421. *
  24422. * @returns {number}
  24423. * @private
  24424. */
  24425. exports._getSelectedEdgeCount = function() {
  24426. var count = 0;
  24427. for (var edgeId in this.selectionObj.edges) {
  24428. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24429. count += 1;
  24430. }
  24431. }
  24432. return count;
  24433. };
  24434. /**
  24435. * return the number of selected objects.
  24436. *
  24437. * @returns {number}
  24438. * @private
  24439. */
  24440. exports._getSelectedObjectCount = function() {
  24441. var count = 0;
  24442. for(var nodeId in this.selectionObj.nodes) {
  24443. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24444. count += 1;
  24445. }
  24446. }
  24447. for(var edgeId in this.selectionObj.edges) {
  24448. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24449. count += 1;
  24450. }
  24451. }
  24452. return count;
  24453. };
  24454. /**
  24455. * Check if anything is selected
  24456. *
  24457. * @returns {boolean}
  24458. * @private
  24459. */
  24460. exports._selectionIsEmpty = function() {
  24461. for(var nodeId in this.selectionObj.nodes) {
  24462. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24463. return false;
  24464. }
  24465. }
  24466. for(var edgeId in this.selectionObj.edges) {
  24467. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24468. return false;
  24469. }
  24470. }
  24471. return true;
  24472. };
  24473. /**
  24474. * check if one of the selected nodes is a cluster.
  24475. *
  24476. * @returns {boolean}
  24477. * @private
  24478. */
  24479. exports._clusterInSelection = function() {
  24480. for(var nodeId in this.selectionObj.nodes) {
  24481. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24482. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  24483. return true;
  24484. }
  24485. }
  24486. }
  24487. return false;
  24488. };
  24489. /**
  24490. * select the edges connected to the node that is being selected
  24491. *
  24492. * @param {Node} node
  24493. * @private
  24494. */
  24495. exports._selectConnectedEdges = function(node) {
  24496. for (var i = 0; i < node.dynamicEdges.length; i++) {
  24497. var edge = node.dynamicEdges[i];
  24498. edge.select();
  24499. this._addToSelection(edge);
  24500. }
  24501. };
  24502. /**
  24503. * select the edges connected to the node that is being selected
  24504. *
  24505. * @param {Node} node
  24506. * @private
  24507. */
  24508. exports._hoverConnectedEdges = function(node) {
  24509. for (var i = 0; i < node.dynamicEdges.length; i++) {
  24510. var edge = node.dynamicEdges[i];
  24511. edge.hover = true;
  24512. this._addToHover(edge);
  24513. }
  24514. };
  24515. /**
  24516. * unselect the edges connected to the node that is being selected
  24517. *
  24518. * @param {Node} node
  24519. * @private
  24520. */
  24521. exports._unselectConnectedEdges = function(node) {
  24522. for (var i = 0; i < node.dynamicEdges.length; i++) {
  24523. var edge = node.dynamicEdges[i];
  24524. edge.unselect();
  24525. this._removeFromSelection(edge);
  24526. }
  24527. };
  24528. /**
  24529. * This is called when someone clicks on a node. either select or deselect it.
  24530. * If there is an existing selection and we don't want to append to it, clear the existing selection
  24531. *
  24532. * @param {Node || Edge} object
  24533. * @param {Boolean} append
  24534. * @param {Boolean} [doNotTrigger] | ignore trigger
  24535. * @private
  24536. */
  24537. exports._selectObject = function(object, append, doNotTrigger, highlightEdges) {
  24538. if (doNotTrigger === undefined) {
  24539. doNotTrigger = false;
  24540. }
  24541. if (highlightEdges === undefined) {
  24542. highlightEdges = true;
  24543. }
  24544. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  24545. this._unselectAll(true);
  24546. }
  24547. if (object.selected == false) {
  24548. object.select();
  24549. this._addToSelection(object);
  24550. if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) {
  24551. this._selectConnectedEdges(object);
  24552. }
  24553. }
  24554. else {
  24555. object.unselect();
  24556. this._removeFromSelection(object);
  24557. }
  24558. if (doNotTrigger == false) {
  24559. this.emit('select', this.getSelection());
  24560. }
  24561. };
  24562. /**
  24563. * This is called when someone clicks on a node. either select or deselect it.
  24564. * If there is an existing selection and we don't want to append to it, clear the existing selection
  24565. *
  24566. * @param {Node || Edge} object
  24567. * @private
  24568. */
  24569. exports._blurObject = function(object) {
  24570. if (object.hover == true) {
  24571. object.hover = false;
  24572. this.emit("blurNode",{node:object.id});
  24573. }
  24574. };
  24575. /**
  24576. * This is called when someone clicks on a node. either select or deselect it.
  24577. * If there is an existing selection and we don't want to append to it, clear the existing selection
  24578. *
  24579. * @param {Node || Edge} object
  24580. * @private
  24581. */
  24582. exports._hoverObject = function(object) {
  24583. if (object.hover == false) {
  24584. object.hover = true;
  24585. this._addToHover(object);
  24586. if (object instanceof Node) {
  24587. this.emit("hoverNode",{node:object.id});
  24588. }
  24589. }
  24590. if (object instanceof Node) {
  24591. this._hoverConnectedEdges(object);
  24592. }
  24593. };
  24594. /**
  24595. * handles the selection part of the touch, only for navigation controls elements;
  24596. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  24597. * This is the most responsive solution
  24598. *
  24599. * @param {Object} pointer
  24600. * @private
  24601. */
  24602. exports._handleTouch = function(pointer) {
  24603. };
  24604. /**
  24605. * handles the selection part of the tap;
  24606. *
  24607. * @param {Object} pointer
  24608. * @private
  24609. */
  24610. exports._handleTap = function(pointer) {
  24611. var node = this._getNodeAt(pointer);
  24612. if (node != null) {
  24613. this._selectObject(node,false);
  24614. }
  24615. else {
  24616. var edge = this._getEdgeAt(pointer);
  24617. if (edge != null) {
  24618. this._selectObject(edge,false);
  24619. }
  24620. else {
  24621. this._unselectAll();
  24622. }
  24623. }
  24624. this.emit("click", this.getSelection());
  24625. this._redraw();
  24626. };
  24627. /**
  24628. * handles the selection part of the double tap and opens a cluster if needed
  24629. *
  24630. * @param {Object} pointer
  24631. * @private
  24632. */
  24633. exports._handleDoubleTap = function(pointer) {
  24634. var node = this._getNodeAt(pointer);
  24635. if (node != null && node !== undefined) {
  24636. // we reset the areaCenter here so the opening of the node will occur
  24637. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  24638. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  24639. this.openCluster(node);
  24640. }
  24641. this.emit("doubleClick", this.getSelection());
  24642. };
  24643. /**
  24644. * Handle the onHold selection part
  24645. *
  24646. * @param pointer
  24647. * @private
  24648. */
  24649. exports._handleOnHold = function(pointer) {
  24650. var node = this._getNodeAt(pointer);
  24651. if (node != null) {
  24652. this._selectObject(node,true);
  24653. }
  24654. else {
  24655. var edge = this._getEdgeAt(pointer);
  24656. if (edge != null) {
  24657. this._selectObject(edge,true);
  24658. }
  24659. }
  24660. this._redraw();
  24661. };
  24662. /**
  24663. * handle the onRelease event. These functions are here for the navigation controls module.
  24664. *
  24665. * @private
  24666. */
  24667. exports._handleOnRelease = function(pointer) {
  24668. };
  24669. /**
  24670. *
  24671. * retrieve the currently selected objects
  24672. * @return {{nodes: Array.<String>, edges: Array.<String>}} selection
  24673. */
  24674. exports.getSelection = function() {
  24675. var nodeIds = this.getSelectedNodes();
  24676. var edgeIds = this.getSelectedEdges();
  24677. return {nodes:nodeIds, edges:edgeIds};
  24678. };
  24679. /**
  24680. *
  24681. * retrieve the currently selected nodes
  24682. * @return {String[]} selection An array with the ids of the
  24683. * selected nodes.
  24684. */
  24685. exports.getSelectedNodes = function() {
  24686. var idArray = [];
  24687. for(var nodeId in this.selectionObj.nodes) {
  24688. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24689. idArray.push(nodeId);
  24690. }
  24691. }
  24692. return idArray
  24693. };
  24694. /**
  24695. *
  24696. * retrieve the currently selected edges
  24697. * @return {Array} selection An array with the ids of the
  24698. * selected nodes.
  24699. */
  24700. exports.getSelectedEdges = function() {
  24701. var idArray = [];
  24702. for(var edgeId in this.selectionObj.edges) {
  24703. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24704. idArray.push(edgeId);
  24705. }
  24706. }
  24707. return idArray;
  24708. };
  24709. /**
  24710. * select zero or more nodes
  24711. * @param {Number[] | String[]} selection An array with the ids of the
  24712. * selected nodes.
  24713. */
  24714. exports.setSelection = function(selection) {
  24715. var i, iMax, id;
  24716. if (!selection || (selection.length == undefined))
  24717. throw 'Selection must be an array with ids';
  24718. // first unselect any selected node
  24719. this._unselectAll(true);
  24720. for (i = 0, iMax = selection.length; i < iMax; i++) {
  24721. id = selection[i];
  24722. var node = this.nodes[id];
  24723. if (!node) {
  24724. throw new RangeError('Node with id "' + id + '" not found');
  24725. }
  24726. this._selectObject(node,true,true);
  24727. }
  24728. console.log("setSelection is deprecated. Please use selectNodes instead.")
  24729. this.redraw();
  24730. };
  24731. /**
  24732. * select zero or more nodes with the option to highlight edges
  24733. * @param {Number[] | String[]} selection An array with the ids of the
  24734. * selected nodes.
  24735. * @param {boolean} [highlightEdges]
  24736. */
  24737. exports.selectNodes = function(selection, highlightEdges) {
  24738. var i, iMax, id;
  24739. if (!selection || (selection.length == undefined))
  24740. throw 'Selection must be an array with ids';
  24741. // first unselect any selected node
  24742. this._unselectAll(true);
  24743. for (i = 0, iMax = selection.length; i < iMax; i++) {
  24744. id = selection[i];
  24745. var node = this.nodes[id];
  24746. if (!node) {
  24747. throw new RangeError('Node with id "' + id + '" not found');
  24748. }
  24749. this._selectObject(node,true,true,highlightEdges);
  24750. }
  24751. this.redraw();
  24752. };
  24753. /**
  24754. * select zero or more edges
  24755. * @param {Number[] | String[]} selection An array with the ids of the
  24756. * selected nodes.
  24757. */
  24758. exports.selectEdges = function(selection) {
  24759. var i, iMax, id;
  24760. if (!selection || (selection.length == undefined))
  24761. throw 'Selection must be an array with ids';
  24762. // first unselect any selected node
  24763. this._unselectAll(true);
  24764. for (i = 0, iMax = selection.length; i < iMax; i++) {
  24765. id = selection[i];
  24766. var edge = this.edges[id];
  24767. if (!edge) {
  24768. throw new RangeError('Edge with id "' + id + '" not found');
  24769. }
  24770. this._selectObject(edge,true,true,highlightEdges);
  24771. }
  24772. this.redraw();
  24773. };
  24774. /**
  24775. * Validate the selection: remove ids of nodes which no longer exist
  24776. * @private
  24777. */
  24778. exports._updateSelection = function () {
  24779. for(var nodeId in this.selectionObj.nodes) {
  24780. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  24781. if (!this.nodes.hasOwnProperty(nodeId)) {
  24782. delete this.selectionObj.nodes[nodeId];
  24783. }
  24784. }
  24785. }
  24786. for(var edgeId in this.selectionObj.edges) {
  24787. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  24788. if (!this.edges.hasOwnProperty(edgeId)) {
  24789. delete this.selectionObj.edges[edgeId];
  24790. }
  24791. }
  24792. }
  24793. };
  24794. /***/ },
  24795. /* 53 */
  24796. /***/ function(module, exports, __webpack_require__) {
  24797. var util = __webpack_require__(1);
  24798. var Node = __webpack_require__(36);
  24799. var Edge = __webpack_require__(33);
  24800. /**
  24801. * clears the toolbar div element of children
  24802. *
  24803. * @private
  24804. */
  24805. exports._clearManipulatorBar = function() {
  24806. while (this.manipulationDiv.hasChildNodes()) {
  24807. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  24808. }
  24809. };
  24810. /**
  24811. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  24812. * these functions to their original functionality, we saved them in this.cachedFunctions.
  24813. * This function restores these functions to their original function.
  24814. *
  24815. * @private
  24816. */
  24817. exports._restoreOverloadedFunctions = function() {
  24818. for (var functionName in this.cachedFunctions) {
  24819. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  24820. this[functionName] = this.cachedFunctions[functionName];
  24821. }
  24822. }
  24823. };
  24824. /**
  24825. * Enable or disable edit-mode.
  24826. *
  24827. * @private
  24828. */
  24829. exports._toggleEditMode = function() {
  24830. this.editMode = !this.editMode;
  24831. var toolbar = document.getElementById("network-manipulationDiv");
  24832. var closeDiv = document.getElementById("network-manipulation-closeDiv");
  24833. var editModeDiv = document.getElementById("network-manipulation-editMode");
  24834. if (this.editMode == true) {
  24835. toolbar.style.display="block";
  24836. closeDiv.style.display="block";
  24837. editModeDiv.style.display="none";
  24838. closeDiv.onclick = this._toggleEditMode.bind(this);
  24839. }
  24840. else {
  24841. toolbar.style.display="none";
  24842. closeDiv.style.display="none";
  24843. editModeDiv.style.display="block";
  24844. closeDiv.onclick = null;
  24845. }
  24846. this._createManipulatorBar()
  24847. };
  24848. /**
  24849. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  24850. *
  24851. * @private
  24852. */
  24853. exports._createManipulatorBar = function() {
  24854. // remove bound functions
  24855. if (this.boundFunction) {
  24856. this.off('select', this.boundFunction);
  24857. }
  24858. if (this.edgeBeingEdited !== undefined) {
  24859. this.edgeBeingEdited._disableControlNodes();
  24860. this.edgeBeingEdited = undefined;
  24861. this.selectedControlNode = null;
  24862. this.controlNodesActive = false;
  24863. }
  24864. // restore overloaded functions
  24865. this._restoreOverloadedFunctions();
  24866. // resume calculation
  24867. this.freezeSimulation = false;
  24868. // reset global variables
  24869. this.blockConnectingEdgeSelection = false;
  24870. this.forceAppendSelection = false;
  24871. if (this.editMode == true) {
  24872. while (this.manipulationDiv.hasChildNodes()) {
  24873. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  24874. }
  24875. // add the icons to the manipulator div
  24876. this.manipulationDiv.innerHTML = "" +
  24877. "<span class='network-manipulationUI add' id='network-manipulate-addNode'>" +
  24878. "<span class='network-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  24879. "<div class='network-seperatorLine'></div>" +
  24880. "<span class='network-manipulationUI connect' id='network-manipulate-connectNode'>" +
  24881. "<span class='network-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  24882. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  24883. this.manipulationDiv.innerHTML += "" +
  24884. "<div class='network-seperatorLine'></div>" +
  24885. "<span class='network-manipulationUI edit' id='network-manipulate-editNode'>" +
  24886. "<span class='network-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  24887. }
  24888. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  24889. this.manipulationDiv.innerHTML += "" +
  24890. "<div class='network-seperatorLine'></div>" +
  24891. "<span class='network-manipulationUI edit' id='network-manipulate-editEdge'>" +
  24892. "<span class='network-manipulationLabel'>"+this.constants.labels['editEdge'] +"</span></span>";
  24893. }
  24894. if (this._selectionIsEmpty() == false) {
  24895. this.manipulationDiv.innerHTML += "" +
  24896. "<div class='network-seperatorLine'></div>" +
  24897. "<span class='network-manipulationUI delete' id='network-manipulate-delete'>" +
  24898. "<span class='network-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  24899. }
  24900. // bind the icons
  24901. var addNodeButton = document.getElementById("network-manipulate-addNode");
  24902. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  24903. var addEdgeButton = document.getElementById("network-manipulate-connectNode");
  24904. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  24905. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  24906. var editButton = document.getElementById("network-manipulate-editNode");
  24907. editButton.onclick = this._editNode.bind(this);
  24908. }
  24909. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  24910. var editButton = document.getElementById("network-manipulate-editEdge");
  24911. editButton.onclick = this._createEditEdgeToolbar.bind(this);
  24912. }
  24913. if (this._selectionIsEmpty() == false) {
  24914. var deleteButton = document.getElementById("network-manipulate-delete");
  24915. deleteButton.onclick = this._deleteSelected.bind(this);
  24916. }
  24917. var closeDiv = document.getElementById("network-manipulation-closeDiv");
  24918. closeDiv.onclick = this._toggleEditMode.bind(this);
  24919. this.boundFunction = this._createManipulatorBar.bind(this);
  24920. this.on('select', this.boundFunction);
  24921. }
  24922. else {
  24923. this.editModeDiv.innerHTML = "" +
  24924. "<span class='network-manipulationUI edit editmode' id='network-manipulate-editModeButton'>" +
  24925. "<span class='network-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  24926. var editModeButton = document.getElementById("network-manipulate-editModeButton");
  24927. editModeButton.onclick = this._toggleEditMode.bind(this);
  24928. }
  24929. };
  24930. /**
  24931. * Create the toolbar for adding Nodes
  24932. *
  24933. * @private
  24934. */
  24935. exports._createAddNodeToolbar = function() {
  24936. // clear the toolbar
  24937. this._clearManipulatorBar();
  24938. if (this.boundFunction) {
  24939. this.off('select', this.boundFunction);
  24940. }
  24941. // create the toolbar contents
  24942. this.manipulationDiv.innerHTML = "" +
  24943. "<span class='network-manipulationUI back' id='network-manipulate-back'>" +
  24944. "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  24945. "<div class='network-seperatorLine'></div>" +
  24946. "<span class='network-manipulationUI none' id='network-manipulate-back'>" +
  24947. "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  24948. // bind the icon
  24949. var backButton = document.getElementById("network-manipulate-back");
  24950. backButton.onclick = this._createManipulatorBar.bind(this);
  24951. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  24952. this.boundFunction = this._addNode.bind(this);
  24953. this.on('select', this.boundFunction);
  24954. };
  24955. /**
  24956. * create the toolbar to connect nodes
  24957. *
  24958. * @private
  24959. */
  24960. exports._createAddEdgeToolbar = function() {
  24961. // clear the toolbar
  24962. this._clearManipulatorBar();
  24963. this._unselectAll(true);
  24964. this.freezeSimulation = true;
  24965. if (this.boundFunction) {
  24966. this.off('select', this.boundFunction);
  24967. }
  24968. this._unselectAll();
  24969. this.forceAppendSelection = false;
  24970. this.blockConnectingEdgeSelection = true;
  24971. this.manipulationDiv.innerHTML = "" +
  24972. "<span class='network-manipulationUI back' id='network-manipulate-back'>" +
  24973. "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  24974. "<div class='network-seperatorLine'></div>" +
  24975. "<span class='network-manipulationUI none' id='network-manipulate-back'>" +
  24976. "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  24977. // bind the icon
  24978. var backButton = document.getElementById("network-manipulate-back");
  24979. backButton.onclick = this._createManipulatorBar.bind(this);
  24980. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  24981. this.boundFunction = this._handleConnect.bind(this);
  24982. this.on('select', this.boundFunction);
  24983. // temporarily overload functions
  24984. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  24985. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  24986. this._handleTouch = this._handleConnect;
  24987. this._handleOnRelease = this._finishConnect;
  24988. // redraw to show the unselect
  24989. this._redraw();
  24990. };
  24991. /**
  24992. * create the toolbar to edit edges
  24993. *
  24994. * @private
  24995. */
  24996. exports._createEditEdgeToolbar = function() {
  24997. // clear the toolbar
  24998. this._clearManipulatorBar();
  24999. this.controlNodesActive = true;
  25000. if (this.boundFunction) {
  25001. this.off('select', this.boundFunction);
  25002. }
  25003. this.edgeBeingEdited = this._getSelectedEdge();
  25004. this.edgeBeingEdited._enableControlNodes();
  25005. this.manipulationDiv.innerHTML = "" +
  25006. "<span class='network-manipulationUI back' id='network-manipulate-back'>" +
  25007. "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  25008. "<div class='network-seperatorLine'></div>" +
  25009. "<span class='network-manipulationUI none' id='network-manipulate-back'>" +
  25010. "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['editEdgeDescription'] + "</span></span>";
  25011. // bind the icon
  25012. var backButton = document.getElementById("network-manipulate-back");
  25013. backButton.onclick = this._createManipulatorBar.bind(this);
  25014. // temporarily overload functions
  25015. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  25016. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  25017. this.cachedFunctions["_handleTap"] = this._handleTap;
  25018. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  25019. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  25020. this._handleTouch = this._selectControlNode;
  25021. this._handleTap = function () {};
  25022. this._handleOnDrag = this._controlNodeDrag;
  25023. this._handleDragStart = function () {}
  25024. this._handleOnRelease = this._releaseControlNode;
  25025. // redraw to show the unselect
  25026. this._redraw();
  25027. };
  25028. /**
  25029. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  25030. * to walk the user through the process.
  25031. *
  25032. * @private
  25033. */
  25034. exports._selectControlNode = function(pointer) {
  25035. this.edgeBeingEdited.controlNodes.from.unselect();
  25036. this.edgeBeingEdited.controlNodes.to.unselect();
  25037. this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y));
  25038. if (this.selectedControlNode !== null) {
  25039. this.selectedControlNode.select();
  25040. this.freezeSimulation = true;
  25041. }
  25042. this._redraw();
  25043. };
  25044. /**
  25045. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  25046. * to walk the user through the process.
  25047. *
  25048. * @private
  25049. */
  25050. exports._controlNodeDrag = function(event) {
  25051. var pointer = this._getPointer(event.gesture.center);
  25052. if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) {
  25053. this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x);
  25054. this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y);
  25055. }
  25056. this._redraw();
  25057. };
  25058. exports._releaseControlNode = function(pointer) {
  25059. var newNode = this._getNodeAt(pointer);
  25060. if (newNode != null) {
  25061. if (this.edgeBeingEdited.controlNodes.from.selected == true) {
  25062. this._editEdge(newNode.id, this.edgeBeingEdited.to.id);
  25063. this.edgeBeingEdited.controlNodes.from.unselect();
  25064. }
  25065. if (this.edgeBeingEdited.controlNodes.to.selected == true) {
  25066. this._editEdge(this.edgeBeingEdited.from.id, newNode.id);
  25067. this.edgeBeingEdited.controlNodes.to.unselect();
  25068. }
  25069. }
  25070. else {
  25071. this.edgeBeingEdited._restoreControlNodes();
  25072. }
  25073. this.freezeSimulation = false;
  25074. this._redraw();
  25075. };
  25076. /**
  25077. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  25078. * to walk the user through the process.
  25079. *
  25080. * @private
  25081. */
  25082. exports._handleConnect = function(pointer) {
  25083. if (this._getSelectedNodeCount() == 0) {
  25084. var node = this._getNodeAt(pointer);
  25085. if (node != null) {
  25086. if (node.clusterSize > 1) {
  25087. alert("Cannot create edges to a cluster.")
  25088. }
  25089. else {
  25090. this._selectObject(node,false);
  25091. // create a node the temporary line can look at
  25092. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  25093. this.sectors['support']['nodes']['targetNode'].x = node.x;
  25094. this.sectors['support']['nodes']['targetNode'].y = node.y;
  25095. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  25096. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  25097. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  25098. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  25099. // create a temporary edge
  25100. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  25101. this.edges['connectionEdge'].from = node;
  25102. this.edges['connectionEdge'].connected = true;
  25103. this.edges['connectionEdge'].smooth = true;
  25104. this.edges['connectionEdge'].selected = true;
  25105. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  25106. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  25107. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  25108. this._handleOnDrag = function(event) {
  25109. var pointer = this._getPointer(event.gesture.center);
  25110. this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x);
  25111. this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y);
  25112. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x);
  25113. this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y);
  25114. };
  25115. this.moving = true;
  25116. this.start();
  25117. }
  25118. }
  25119. }
  25120. };
  25121. exports._finishConnect = function(pointer) {
  25122. if (this._getSelectedNodeCount() == 1) {
  25123. // restore the drag function
  25124. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  25125. delete this.cachedFunctions["_handleOnDrag"];
  25126. // remember the edge id
  25127. var connectFromId = this.edges['connectionEdge'].fromId;
  25128. // remove the temporary nodes and edge
  25129. delete this.edges['connectionEdge'];
  25130. delete this.sectors['support']['nodes']['targetNode'];
  25131. delete this.sectors['support']['nodes']['targetViaNode'];
  25132. var node = this._getNodeAt(pointer);
  25133. if (node != null) {
  25134. if (node.clusterSize > 1) {
  25135. alert("Cannot create edges to a cluster.")
  25136. }
  25137. else {
  25138. this._createEdge(connectFromId,node.id);
  25139. this._createManipulatorBar();
  25140. }
  25141. }
  25142. this._unselectAll();
  25143. }
  25144. };
  25145. /**
  25146. * Adds a node on the specified location
  25147. */
  25148. exports._addNode = function() {
  25149. if (this._selectionIsEmpty() && this.editMode == true) {
  25150. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  25151. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  25152. if (this.triggerFunctions.add) {
  25153. if (this.triggerFunctions.add.length == 2) {
  25154. var me = this;
  25155. this.triggerFunctions.add(defaultData, function(finalizedData) {
  25156. me.nodesData.add(finalizedData);
  25157. me._createManipulatorBar();
  25158. me.moving = true;
  25159. me.start();
  25160. });
  25161. }
  25162. else {
  25163. alert(this.constants.labels['addError']);
  25164. this._createManipulatorBar();
  25165. this.moving = true;
  25166. this.start();
  25167. }
  25168. }
  25169. else {
  25170. this.nodesData.add(defaultData);
  25171. this._createManipulatorBar();
  25172. this.moving = true;
  25173. this.start();
  25174. }
  25175. }
  25176. };
  25177. /**
  25178. * connect two nodes with a new edge.
  25179. *
  25180. * @private
  25181. */
  25182. exports._createEdge = function(sourceNodeId,targetNodeId) {
  25183. if (this.editMode == true) {
  25184. var defaultData = {from:sourceNodeId, to:targetNodeId};
  25185. if (this.triggerFunctions.connect) {
  25186. if (this.triggerFunctions.connect.length == 2) {
  25187. var me = this;
  25188. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  25189. me.edgesData.add(finalizedData);
  25190. me.moving = true;
  25191. me.start();
  25192. });
  25193. }
  25194. else {
  25195. alert(this.constants.labels["linkError"]);
  25196. this.moving = true;
  25197. this.start();
  25198. }
  25199. }
  25200. else {
  25201. this.edgesData.add(defaultData);
  25202. this.moving = true;
  25203. this.start();
  25204. }
  25205. }
  25206. };
  25207. /**
  25208. * connect two nodes with a new edge.
  25209. *
  25210. * @private
  25211. */
  25212. exports._editEdge = function(sourceNodeId,targetNodeId) {
  25213. if (this.editMode == true) {
  25214. var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId};
  25215. if (this.triggerFunctions.editEdge) {
  25216. if (this.triggerFunctions.editEdge.length == 2) {
  25217. var me = this;
  25218. this.triggerFunctions.editEdge(defaultData, function(finalizedData) {
  25219. me.edgesData.update(finalizedData);
  25220. me.moving = true;
  25221. me.start();
  25222. });
  25223. }
  25224. else {
  25225. alert(this.constants.labels["linkError"]);
  25226. this.moving = true;
  25227. this.start();
  25228. }
  25229. }
  25230. else {
  25231. this.edgesData.update(defaultData);
  25232. this.moving = true;
  25233. this.start();
  25234. }
  25235. }
  25236. };
  25237. /**
  25238. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  25239. *
  25240. * @private
  25241. */
  25242. exports._editNode = function() {
  25243. if (this.triggerFunctions.edit && this.editMode == true) {
  25244. var node = this._getSelectedNode();
  25245. var data = {id:node.id,
  25246. label: node.label,
  25247. group: node.options.group,
  25248. shape: node.options.shape,
  25249. color: {
  25250. background:node.options.color.background,
  25251. border:node.options.color.border,
  25252. highlight: {
  25253. background:node.options.color.highlight.background,
  25254. border:node.options.color.highlight.border
  25255. }
  25256. }};
  25257. if (this.triggerFunctions.edit.length == 2) {
  25258. var me = this;
  25259. this.triggerFunctions.edit(data, function (finalizedData) {
  25260. me.nodesData.update(finalizedData);
  25261. me._createManipulatorBar();
  25262. me.moving = true;
  25263. me.start();
  25264. });
  25265. }
  25266. else {
  25267. alert(this.constants.labels["editError"]);
  25268. }
  25269. }
  25270. else {
  25271. alert(this.constants.labels["editBoundError"]);
  25272. }
  25273. };
  25274. /**
  25275. * delete everything in the selection
  25276. *
  25277. * @private
  25278. */
  25279. exports._deleteSelected = function() {
  25280. if (!this._selectionIsEmpty() && this.editMode == true) {
  25281. if (!this._clusterInSelection()) {
  25282. var selectedNodes = this.getSelectedNodes();
  25283. var selectedEdges = this.getSelectedEdges();
  25284. if (this.triggerFunctions.del) {
  25285. var me = this;
  25286. var data = {nodes: selectedNodes, edges: selectedEdges};
  25287. if (this.triggerFunctions.del.length = 2) {
  25288. this.triggerFunctions.del(data, function (finalizedData) {
  25289. me.edgesData.remove(finalizedData.edges);
  25290. me.nodesData.remove(finalizedData.nodes);
  25291. me._unselectAll();
  25292. me.moving = true;
  25293. me.start();
  25294. });
  25295. }
  25296. else {
  25297. alert(this.constants.labels["deleteError"])
  25298. }
  25299. }
  25300. else {
  25301. this.edgesData.remove(selectedEdges);
  25302. this.nodesData.remove(selectedNodes);
  25303. this._unselectAll();
  25304. this.moving = true;
  25305. this.start();
  25306. }
  25307. }
  25308. else {
  25309. alert(this.constants.labels["deleteClusterError"]);
  25310. }
  25311. }
  25312. };
  25313. /***/ },
  25314. /* 54 */
  25315. /***/ function(module, exports, __webpack_require__) {
  25316. var util = __webpack_require__(1);
  25317. var Hammer = __webpack_require__(41);
  25318. exports._cleanNavigation = function() {
  25319. // clean up previous navigation items
  25320. var wrapper = document.getElementById('network-navigation_wrapper');
  25321. if (wrapper != null) {
  25322. this.containerElement.removeChild(wrapper);
  25323. }
  25324. document.onmouseup = null;
  25325. };
  25326. /**
  25327. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  25328. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  25329. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  25330. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  25331. *
  25332. * @private
  25333. */
  25334. exports._loadNavigationElements = function() {
  25335. this._cleanNavigation();
  25336. this.navigationDivs = {};
  25337. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  25338. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  25339. this.navigationDivs['wrapper'] = document.createElement('div');
  25340. this.navigationDivs['wrapper'].id = "network-navigation_wrapper";
  25341. this.navigationDivs['wrapper'].style.position = "absolute";
  25342. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  25343. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  25344. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  25345. var me = this;
  25346. for (var i = 0; i < navigationDivs.length; i++) {
  25347. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  25348. this.navigationDivs[navigationDivs[i]].id = "network-navigation_" + navigationDivs[i];
  25349. this.navigationDivs[navigationDivs[i]].className = "network-navigation " + navigationDivs[i];
  25350. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  25351. var hammer = Hammer(this.navigationDivs[navigationDivs[i]], {prevent_default: true});
  25352. hammer.on("touch", me[navigationDivActions[i]].bind(me));
  25353. }
  25354. var hammer = Hammer(document, {prevent_default: false});
  25355. hammer.on("release", me._stopMovement.bind(me));
  25356. };
  25357. /**
  25358. * this stops all movement induced by the navigation buttons
  25359. *
  25360. * @private
  25361. */
  25362. exports._stopMovement = function() {
  25363. this._xStopMoving();
  25364. this._yStopMoving();
  25365. this._stopZoom();
  25366. };
  25367. /**
  25368. * move the screen up
  25369. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  25370. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  25371. * To avoid this behaviour, we do the translation in the start loop.
  25372. *
  25373. * @private
  25374. */
  25375. exports._moveUp = function(event) {
  25376. this.yIncrement = this.constants.keyboard.speed.y;
  25377. this.start(); // if there is no node movement, the calculation wont be done
  25378. };
  25379. /**
  25380. * move the screen down
  25381. * @private
  25382. */
  25383. exports._moveDown = function(event) {
  25384. this.yIncrement = -this.constants.keyboard.speed.y;
  25385. this.start(); // if there is no node movement, the calculation wont be done
  25386. };
  25387. /**
  25388. * move the screen left
  25389. * @private
  25390. */
  25391. exports._moveLeft = function(event) {
  25392. this.xIncrement = this.constants.keyboard.speed.x;
  25393. this.start(); // if there is no node movement, the calculation wont be done
  25394. };
  25395. /**
  25396. * move the screen right
  25397. * @private
  25398. */
  25399. exports._moveRight = function(event) {
  25400. this.xIncrement = -this.constants.keyboard.speed.y;
  25401. this.start(); // if there is no node movement, the calculation wont be done
  25402. };
  25403. /**
  25404. * Zoom in, using the same method as the movement.
  25405. * @private
  25406. */
  25407. exports._zoomIn = function(event) {
  25408. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  25409. this.start(); // if there is no node movement, the calculation wont be done
  25410. };
  25411. /**
  25412. * Zoom out
  25413. * @private
  25414. */
  25415. exports._zoomOut = function() {
  25416. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  25417. this.start(); // if there is no node movement, the calculation wont be done
  25418. util.preventDefault(event);
  25419. };
  25420. /**
  25421. * Stop zooming and unhighlight the zoom controls
  25422. * @private
  25423. */
  25424. exports._stopZoom = function() {
  25425. this.zoomIncrement = 0;
  25426. };
  25427. /**
  25428. * Stop moving in the Y direction and unHighlight the up and down
  25429. * @private
  25430. */
  25431. exports._yStopMoving = function() {
  25432. this.yIncrement = 0;
  25433. };
  25434. /**
  25435. * Stop moving in the X direction and unHighlight left and right.
  25436. * @private
  25437. */
  25438. exports._xStopMoving = function() {
  25439. this.xIncrement = 0;
  25440. };
  25441. /***/ },
  25442. /* 55 */
  25443. /***/ function(module, exports, __webpack_require__) {
  25444. exports._resetLevels = function() {
  25445. for (var nodeId in this.nodes) {
  25446. if (this.nodes.hasOwnProperty(nodeId)) {
  25447. var node = this.nodes[nodeId];
  25448. if (node.preassignedLevel == false) {
  25449. node.level = -1;
  25450. }
  25451. }
  25452. }
  25453. };
  25454. /**
  25455. * This is the main function to layout the nodes in a hierarchical way.
  25456. * It checks if the node details are supplied correctly
  25457. *
  25458. * @private
  25459. */
  25460. exports._setupHierarchicalLayout = function() {
  25461. if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) {
  25462. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  25463. this.constants.hierarchicalLayout.levelSeparation *= -1;
  25464. }
  25465. else {
  25466. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  25467. }
  25468. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") {
  25469. if (this.constants.smoothCurves.enabled == true) {
  25470. this.constants.smoothCurves.type = "vertical";
  25471. }
  25472. }
  25473. else {
  25474. if (this.constants.smoothCurves.enabled == true) {
  25475. this.constants.smoothCurves.type = "horizontal";
  25476. }
  25477. }
  25478. // get the size of the largest hubs and check if the user has defined a level for a node.
  25479. var hubsize = 0;
  25480. var node, nodeId;
  25481. var definedLevel = false;
  25482. var undefinedLevel = false;
  25483. for (nodeId in this.nodes) {
  25484. if (this.nodes.hasOwnProperty(nodeId)) {
  25485. node = this.nodes[nodeId];
  25486. if (node.level != -1) {
  25487. definedLevel = true;
  25488. }
  25489. else {
  25490. undefinedLevel = true;
  25491. }
  25492. if (hubsize < node.edges.length) {
  25493. hubsize = node.edges.length;
  25494. }
  25495. }
  25496. }
  25497. // if the user defined some levels but not all, alert and run without hierarchical layout
  25498. if (undefinedLevel == true && definedLevel == true) {
  25499. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  25500. this.zoomExtent(true,this.constants.clustering.enabled);
  25501. if (!this.constants.clustering.enabled) {
  25502. this.start();
  25503. }
  25504. }
  25505. else {
  25506. // setup the system to use hierarchical method.
  25507. this._changeConstants();
  25508. // define levels if undefined by the users. Based on hubsize
  25509. if (undefinedLevel == true) {
  25510. this._determineLevels(hubsize);
  25511. }
  25512. // check the distribution of the nodes per level.
  25513. var distribution = this._getDistribution();
  25514. // place the nodes on the canvas. This also stablilizes the system.
  25515. this._placeNodesByHierarchy(distribution);
  25516. // start the simulation.
  25517. this.start();
  25518. }
  25519. }
  25520. };
  25521. /**
  25522. * This function places the nodes on the canvas based on the hierarchial distribution.
  25523. *
  25524. * @param {Object} distribution | obtained by the function this._getDistribution()
  25525. * @private
  25526. */
  25527. exports._placeNodesByHierarchy = function(distribution) {
  25528. var nodeId, node;
  25529. // start placing all the level 0 nodes first. Then recursively position their branches.
  25530. for (var level in distribution) {
  25531. if (distribution.hasOwnProperty(level)) {
  25532. for (nodeId in distribution[level].nodes) {
  25533. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  25534. node = distribution[level].nodes[nodeId];
  25535. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  25536. if (node.xFixed) {
  25537. node.x = distribution[level].minPos;
  25538. node.xFixed = false;
  25539. distribution[level].minPos += distribution[level].nodeSpacing;
  25540. }
  25541. }
  25542. else {
  25543. if (node.yFixed) {
  25544. node.y = distribution[level].minPos;
  25545. node.yFixed = false;
  25546. distribution[level].minPos += distribution[level].nodeSpacing;
  25547. }
  25548. }
  25549. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  25550. }
  25551. }
  25552. }
  25553. }
  25554. // stabilize the system after positioning. This function calls zoomExtent.
  25555. this._stabilize();
  25556. };
  25557. /**
  25558. * This function get the distribution of levels based on hubsize
  25559. *
  25560. * @returns {Object}
  25561. * @private
  25562. */
  25563. exports._getDistribution = function() {
  25564. var distribution = {};
  25565. var nodeId, node, level;
  25566. // 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.
  25567. // the fix of X is removed after the x value has been set.
  25568. for (nodeId in this.nodes) {
  25569. if (this.nodes.hasOwnProperty(nodeId)) {
  25570. node = this.nodes[nodeId];
  25571. node.xFixed = true;
  25572. node.yFixed = true;
  25573. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  25574. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  25575. }
  25576. else {
  25577. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  25578. }
  25579. if (distribution[node.level] === undefined) {
  25580. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  25581. }
  25582. distribution[node.level].amount += 1;
  25583. distribution[node.level].nodes[nodeId] = node;
  25584. }
  25585. }
  25586. // determine the largest amount of nodes of all levels
  25587. var maxCount = 0;
  25588. for (level in distribution) {
  25589. if (distribution.hasOwnProperty(level)) {
  25590. if (maxCount < distribution[level].amount) {
  25591. maxCount = distribution[level].amount;
  25592. }
  25593. }
  25594. }
  25595. // set the initial position and spacing of each nodes accordingly
  25596. for (level in distribution) {
  25597. if (distribution.hasOwnProperty(level)) {
  25598. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  25599. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  25600. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  25601. }
  25602. }
  25603. return distribution;
  25604. };
  25605. /**
  25606. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  25607. *
  25608. * @param hubsize
  25609. * @private
  25610. */
  25611. exports._determineLevels = function(hubsize) {
  25612. var nodeId, node;
  25613. // determine hubs
  25614. for (nodeId in this.nodes) {
  25615. if (this.nodes.hasOwnProperty(nodeId)) {
  25616. node = this.nodes[nodeId];
  25617. if (node.edges.length == hubsize) {
  25618. node.level = 0;
  25619. }
  25620. }
  25621. }
  25622. // branch from hubs
  25623. for (nodeId in this.nodes) {
  25624. if (this.nodes.hasOwnProperty(nodeId)) {
  25625. node = this.nodes[nodeId];
  25626. if (node.level == 0) {
  25627. this._setLevel(1,node.edges,node.id);
  25628. }
  25629. }
  25630. }
  25631. };
  25632. /**
  25633. * Since hierarchical layout does not support:
  25634. * - smooth curves (based on the physics),
  25635. * - clustering (based on dynamic node counts)
  25636. *
  25637. * We disable both features so there will be no problems.
  25638. *
  25639. * @private
  25640. */
  25641. exports._changeConstants = function() {
  25642. this.constants.clustering.enabled = false;
  25643. this.constants.physics.barnesHut.enabled = false;
  25644. this.constants.physics.hierarchicalRepulsion.enabled = true;
  25645. this._loadSelectedForceSolver();
  25646. if (this.constants.smoothCurves.enabled == true) {
  25647. this.constants.smoothCurves.dynamic = false;
  25648. }
  25649. this._configureSmoothCurves();
  25650. };
  25651. /**
  25652. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  25653. * on a X position that ensures there will be no overlap.
  25654. *
  25655. * @param edges
  25656. * @param parentId
  25657. * @param distribution
  25658. * @param parentLevel
  25659. * @private
  25660. */
  25661. exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) {
  25662. for (var i = 0; i < edges.length; i++) {
  25663. var childNode = null;
  25664. if (edges[i].toId == parentId) {
  25665. childNode = edges[i].from;
  25666. }
  25667. else {
  25668. childNode = edges[i].to;
  25669. }
  25670. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  25671. var nodeMoved = false;
  25672. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  25673. if (childNode.xFixed && childNode.level > parentLevel) {
  25674. childNode.xFixed = false;
  25675. childNode.x = distribution[childNode.level].minPos;
  25676. nodeMoved = true;
  25677. }
  25678. }
  25679. else {
  25680. if (childNode.yFixed && childNode.level > parentLevel) {
  25681. childNode.yFixed = false;
  25682. childNode.y = distribution[childNode.level].minPos;
  25683. nodeMoved = true;
  25684. }
  25685. }
  25686. if (nodeMoved == true) {
  25687. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  25688. if (childNode.edges.length > 1) {
  25689. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  25690. }
  25691. }
  25692. }
  25693. };
  25694. /**
  25695. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  25696. *
  25697. * @param level
  25698. * @param edges
  25699. * @param parentId
  25700. * @private
  25701. */
  25702. exports._setLevel = function(level, edges, parentId) {
  25703. for (var i = 0; i < edges.length; i++) {
  25704. var childNode = null;
  25705. if (edges[i].toId == parentId) {
  25706. childNode = edges[i].from;
  25707. }
  25708. else {
  25709. childNode = edges[i].to;
  25710. }
  25711. if (childNode.level == -1 || childNode.level > level) {
  25712. childNode.level = level;
  25713. if (edges.length > 1) {
  25714. this._setLevel(level+1, childNode.edges, childNode.id);
  25715. }
  25716. }
  25717. }
  25718. };
  25719. /**
  25720. * Unfix nodes
  25721. *
  25722. * @private
  25723. */
  25724. exports._restoreNodes = function() {
  25725. for (var nodeId in this.nodes) {
  25726. if (this.nodes.hasOwnProperty(nodeId)) {
  25727. this.nodes[nodeId].xFixed = false;
  25728. this.nodes[nodeId].yFixed = false;
  25729. }
  25730. }
  25731. };
  25732. /***/ },
  25733. /* 56 */
  25734. /***/ function(module, exports, __webpack_require__) {
  25735. var util = __webpack_require__(1);
  25736. var RepulsionMixin = __webpack_require__(59);
  25737. var HierarchialRepulsionMixin = __webpack_require__(60);
  25738. var BarnesHutMixin = __webpack_require__(61);
  25739. /**
  25740. * Toggling barnes Hut calculation on and off.
  25741. *
  25742. * @private
  25743. */
  25744. exports._toggleBarnesHut = function () {
  25745. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  25746. this._loadSelectedForceSolver();
  25747. this.moving = true;
  25748. this.start();
  25749. };
  25750. /**
  25751. * This loads the node force solver based on the barnes hut or repulsion algorithm
  25752. *
  25753. * @private
  25754. */
  25755. exports._loadSelectedForceSolver = function () {
  25756. // this overloads the this._calculateNodeForces
  25757. if (this.constants.physics.barnesHut.enabled == true) {
  25758. this._clearMixin(RepulsionMixin);
  25759. this._clearMixin(HierarchialRepulsionMixin);
  25760. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  25761. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  25762. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  25763. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  25764. this._loadMixin(BarnesHutMixin);
  25765. }
  25766. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  25767. this._clearMixin(BarnesHutMixin);
  25768. this._clearMixin(RepulsionMixin);
  25769. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  25770. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  25771. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  25772. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  25773. this._loadMixin(HierarchialRepulsionMixin);
  25774. }
  25775. else {
  25776. this._clearMixin(BarnesHutMixin);
  25777. this._clearMixin(HierarchialRepulsionMixin);
  25778. this.barnesHutTree = undefined;
  25779. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  25780. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  25781. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  25782. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  25783. this._loadMixin(RepulsionMixin);
  25784. }
  25785. };
  25786. /**
  25787. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  25788. * if there is more than one node. If it is just one node, we dont calculate anything.
  25789. *
  25790. * @private
  25791. */
  25792. exports._initializeForceCalculation = function () {
  25793. // stop calculation if there is only one node
  25794. if (this.nodeIndices.length == 1) {
  25795. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  25796. }
  25797. else {
  25798. // if there are too many nodes on screen, we cluster without repositioning
  25799. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  25800. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  25801. }
  25802. // we now start the force calculation
  25803. this._calculateForces();
  25804. }
  25805. };
  25806. /**
  25807. * Calculate the external forces acting on the nodes
  25808. * Forces are caused by: edges, repulsing forces between nodes, gravity
  25809. * @private
  25810. */
  25811. exports._calculateForces = function () {
  25812. // Gravity is required to keep separated groups from floating off
  25813. // the forces are reset to zero in this loop by using _setForce instead
  25814. // of _addForce
  25815. this._calculateGravitationalForces();
  25816. this._calculateNodeForces();
  25817. if (this.constants.physics.springConstant > 0) {
  25818. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  25819. this._calculateSpringForcesWithSupport();
  25820. }
  25821. else {
  25822. if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  25823. this._calculateHierarchicalSpringForces();
  25824. }
  25825. else {
  25826. this._calculateSpringForces();
  25827. }
  25828. }
  25829. }
  25830. };
  25831. /**
  25832. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  25833. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  25834. * This function joins the datanodes and invisible (called support) nodes into one object.
  25835. * We do this so we do not contaminate this.nodes with the support nodes.
  25836. *
  25837. * @private
  25838. */
  25839. exports._updateCalculationNodes = function () {
  25840. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  25841. this.calculationNodes = {};
  25842. this.calculationNodeIndices = [];
  25843. for (var nodeId in this.nodes) {
  25844. if (this.nodes.hasOwnProperty(nodeId)) {
  25845. this.calculationNodes[nodeId] = this.nodes[nodeId];
  25846. }
  25847. }
  25848. var supportNodes = this.sectors['support']['nodes'];
  25849. for (var supportNodeId in supportNodes) {
  25850. if (supportNodes.hasOwnProperty(supportNodeId)) {
  25851. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  25852. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  25853. }
  25854. else {
  25855. supportNodes[supportNodeId]._setForce(0, 0);
  25856. }
  25857. }
  25858. }
  25859. for (var idx in this.calculationNodes) {
  25860. if (this.calculationNodes.hasOwnProperty(idx)) {
  25861. this.calculationNodeIndices.push(idx);
  25862. }
  25863. }
  25864. }
  25865. else {
  25866. this.calculationNodes = this.nodes;
  25867. this.calculationNodeIndices = this.nodeIndices;
  25868. }
  25869. };
  25870. /**
  25871. * this function applies the central gravity effect to keep groups from floating off
  25872. *
  25873. * @private
  25874. */
  25875. exports._calculateGravitationalForces = function () {
  25876. var dx, dy, distance, node, i;
  25877. var nodes = this.calculationNodes;
  25878. var gravity = this.constants.physics.centralGravity;
  25879. var gravityForce = 0;
  25880. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  25881. node = nodes[this.calculationNodeIndices[i]];
  25882. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  25883. // gravity does not apply when we are in a pocket sector
  25884. if (this._sector() == "default" && gravity != 0) {
  25885. dx = -node.x;
  25886. dy = -node.y;
  25887. distance = Math.sqrt(dx * dx + dy * dy);
  25888. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  25889. node.fx = dx * gravityForce;
  25890. node.fy = dy * gravityForce;
  25891. }
  25892. else {
  25893. node.fx = 0;
  25894. node.fy = 0;
  25895. }
  25896. }
  25897. };
  25898. /**
  25899. * this function calculates the effects of the springs in the case of unsmooth curves.
  25900. *
  25901. * @private
  25902. */
  25903. exports._calculateSpringForces = function () {
  25904. var edgeLength, edge, edgeId;
  25905. var dx, dy, fx, fy, springForce, distance;
  25906. var edges = this.edges;
  25907. // forces caused by the edges, modelled as springs
  25908. for (edgeId in edges) {
  25909. if (edges.hasOwnProperty(edgeId)) {
  25910. edge = edges[edgeId];
  25911. if (edge.connected) {
  25912. // only calculate forces if nodes are in the same sector
  25913. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25914. edgeLength = edge.physics.springLength;
  25915. // this implies that the edges between big clusters are longer
  25916. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  25917. dx = (edge.from.x - edge.to.x);
  25918. dy = (edge.from.y - edge.to.y);
  25919. distance = Math.sqrt(dx * dx + dy * dy);
  25920. if (distance == 0) {
  25921. distance = 0.01;
  25922. }
  25923. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25924. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25925. fx = dx * springForce;
  25926. fy = dy * springForce;
  25927. edge.from.fx += fx;
  25928. edge.from.fy += fy;
  25929. edge.to.fx -= fx;
  25930. edge.to.fy -= fy;
  25931. }
  25932. }
  25933. }
  25934. }
  25935. };
  25936. /**
  25937. * This function calculates the springforces on the nodes, accounting for the support nodes.
  25938. *
  25939. * @private
  25940. */
  25941. exports._calculateSpringForcesWithSupport = function () {
  25942. var edgeLength, edge, edgeId, combinedClusterSize;
  25943. var edges = this.edges;
  25944. // forces caused by the edges, modelled as springs
  25945. for (edgeId in edges) {
  25946. if (edges.hasOwnProperty(edgeId)) {
  25947. edge = edges[edgeId];
  25948. if (edge.connected) {
  25949. // only calculate forces if nodes are in the same sector
  25950. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  25951. if (edge.via != null) {
  25952. var node1 = edge.to;
  25953. var node2 = edge.via;
  25954. var node3 = edge.from;
  25955. edgeLength = edge.physics.springLength;
  25956. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  25957. // this implies that the edges between big clusters are longer
  25958. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  25959. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  25960. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  25961. }
  25962. }
  25963. }
  25964. }
  25965. }
  25966. };
  25967. /**
  25968. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  25969. *
  25970. * @param node1
  25971. * @param node2
  25972. * @param edgeLength
  25973. * @private
  25974. */
  25975. exports._calculateSpringForce = function (node1, node2, edgeLength) {
  25976. var dx, dy, fx, fy, springForce, distance;
  25977. dx = (node1.x - node2.x);
  25978. dy = (node1.y - node2.y);
  25979. distance = Math.sqrt(dx * dx + dy * dy);
  25980. if (distance == 0) {
  25981. distance = 0.01;
  25982. }
  25983. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  25984. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  25985. fx = dx * springForce;
  25986. fy = dy * springForce;
  25987. node1.fx += fx;
  25988. node1.fy += fy;
  25989. node2.fx -= fx;
  25990. node2.fy -= fy;
  25991. };
  25992. /**
  25993. * Load the HTML for the physics config and bind it
  25994. * @private
  25995. */
  25996. exports._loadPhysicsConfiguration = function () {
  25997. if (this.physicsConfiguration === undefined) {
  25998. this.backupConstants = {};
  25999. util.deepExtend(this.backupConstants,this.constants);
  26000. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  26001. this.physicsConfiguration = document.createElement('div');
  26002. this.physicsConfiguration.className = "PhysicsConfiguration";
  26003. this.physicsConfiguration.innerHTML = '' +
  26004. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  26005. '<tr>' +
  26006. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  26007. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  26008. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  26009. '</tr>' +
  26010. '</table>' +
  26011. '<table id="graph_BH_table" style="display:none">' +
  26012. '<tr><td><b>Barnes Hut</b></td></tr>' +
  26013. '<tr>' +
  26014. '<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>' +
  26015. '</tr>' +
  26016. '<tr>' +
  26017. '<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>' +
  26018. '</tr>' +
  26019. '<tr>' +
  26020. '<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>' +
  26021. '</tr>' +
  26022. '<tr>' +
  26023. '<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>' +
  26024. '</tr>' +
  26025. '<tr>' +
  26026. '<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>' +
  26027. '</tr>' +
  26028. '</table>' +
  26029. '<table id="graph_R_table" style="display:none">' +
  26030. '<tr><td><b>Repulsion</b></td></tr>' +
  26031. '<tr>' +
  26032. '<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>' +
  26033. '</tr>' +
  26034. '<tr>' +
  26035. '<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>' +
  26036. '</tr>' +
  26037. '<tr>' +
  26038. '<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>' +
  26039. '</tr>' +
  26040. '<tr>' +
  26041. '<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>' +
  26042. '</tr>' +
  26043. '<tr>' +
  26044. '<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>' +
  26045. '</tr>' +
  26046. '</table>' +
  26047. '<table id="graph_H_table" style="display:none">' +
  26048. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  26049. '<tr>' +
  26050. '<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>' +
  26051. '</tr>' +
  26052. '<tr>' +
  26053. '<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>' +
  26054. '</tr>' +
  26055. '<tr>' +
  26056. '<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>' +
  26057. '</tr>' +
  26058. '<tr>' +
  26059. '<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>' +
  26060. '</tr>' +
  26061. '<tr>' +
  26062. '<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>' +
  26063. '</tr>' +
  26064. '<tr>' +
  26065. '<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>' +
  26066. '</tr>' +
  26067. '<tr>' +
  26068. '<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>' +
  26069. '</tr>' +
  26070. '<tr>' +
  26071. '<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>' +
  26072. '</tr>' +
  26073. '</table>' +
  26074. '<table><tr><td><b>Options:</b></td></tr>' +
  26075. '<tr>' +
  26076. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  26077. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  26078. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  26079. '</tr>' +
  26080. '</table>'
  26081. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  26082. this.optionsDiv = document.createElement("div");
  26083. this.optionsDiv.style.fontSize = "14px";
  26084. this.optionsDiv.style.fontFamily = "verdana";
  26085. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  26086. var rangeElement;
  26087. rangeElement = document.getElementById('graph_BH_gc');
  26088. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  26089. rangeElement = document.getElementById('graph_BH_cg');
  26090. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  26091. rangeElement = document.getElementById('graph_BH_sc');
  26092. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  26093. rangeElement = document.getElementById('graph_BH_sl');
  26094. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  26095. rangeElement = document.getElementById('graph_BH_damp');
  26096. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  26097. rangeElement = document.getElementById('graph_R_nd');
  26098. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  26099. rangeElement = document.getElementById('graph_R_cg');
  26100. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  26101. rangeElement = document.getElementById('graph_R_sc');
  26102. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  26103. rangeElement = document.getElementById('graph_R_sl');
  26104. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  26105. rangeElement = document.getElementById('graph_R_damp');
  26106. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  26107. rangeElement = document.getElementById('graph_H_nd');
  26108. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  26109. rangeElement = document.getElementById('graph_H_cg');
  26110. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  26111. rangeElement = document.getElementById('graph_H_sc');
  26112. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  26113. rangeElement = document.getElementById('graph_H_sl');
  26114. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  26115. rangeElement = document.getElementById('graph_H_damp');
  26116. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  26117. rangeElement = document.getElementById('graph_H_direction');
  26118. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  26119. rangeElement = document.getElementById('graph_H_levsep');
  26120. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  26121. rangeElement = document.getElementById('graph_H_nspac');
  26122. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  26123. var radioButton1 = document.getElementById("graph_physicsMethod1");
  26124. var radioButton2 = document.getElementById("graph_physicsMethod2");
  26125. var radioButton3 = document.getElementById("graph_physicsMethod3");
  26126. radioButton2.checked = true;
  26127. if (this.constants.physics.barnesHut.enabled) {
  26128. radioButton1.checked = true;
  26129. }
  26130. if (this.constants.hierarchicalLayout.enabled) {
  26131. radioButton3.checked = true;
  26132. }
  26133. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  26134. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  26135. var graph_generateOptions = document.getElementById("graph_generateOptions");
  26136. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  26137. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  26138. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  26139. if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) {
  26140. graph_toggleSmooth.style.background = "#A4FF56";
  26141. }
  26142. else {
  26143. graph_toggleSmooth.style.background = "#FF8532";
  26144. }
  26145. switchConfigurations.apply(this);
  26146. radioButton1.onchange = switchConfigurations.bind(this);
  26147. radioButton2.onchange = switchConfigurations.bind(this);
  26148. radioButton3.onchange = switchConfigurations.bind(this);
  26149. }
  26150. };
  26151. /**
  26152. * This overwrites the this.constants.
  26153. *
  26154. * @param constantsVariableName
  26155. * @param value
  26156. * @private
  26157. */
  26158. exports._overWriteGraphConstants = function (constantsVariableName, value) {
  26159. var nameArray = constantsVariableName.split("_");
  26160. if (nameArray.length == 1) {
  26161. this.constants[nameArray[0]] = value;
  26162. }
  26163. else if (nameArray.length == 2) {
  26164. this.constants[nameArray[0]][nameArray[1]] = value;
  26165. }
  26166. else if (nameArray.length == 3) {
  26167. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  26168. }
  26169. };
  26170. /**
  26171. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  26172. */
  26173. function graphToggleSmoothCurves () {
  26174. this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled;
  26175. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  26176. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  26177. else {graph_toggleSmooth.style.background = "#FF8532";}
  26178. this._configureSmoothCurves(false);
  26179. }
  26180. /**
  26181. * this function is used to scramble the nodes
  26182. *
  26183. */
  26184. function graphRepositionNodes () {
  26185. for (var nodeId in this.calculationNodes) {
  26186. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  26187. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  26188. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  26189. }
  26190. }
  26191. if (this.constants.hierarchicalLayout.enabled == true) {
  26192. this._setupHierarchicalLayout();
  26193. showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  26194. showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity");
  26195. showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant");
  26196. showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength");
  26197. showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping");
  26198. }
  26199. else {
  26200. this.repositionNodes();
  26201. }
  26202. this.moving = true;
  26203. this.start();
  26204. }
  26205. /**
  26206. * this is used to generate an options file from the playing with physics system.
  26207. */
  26208. function graphGenerateOptions () {
  26209. var options = "No options are required, default values used.";
  26210. var optionsSpecific = [];
  26211. var radioButton1 = document.getElementById("graph_physicsMethod1");
  26212. var radioButton2 = document.getElementById("graph_physicsMethod2");
  26213. if (radioButton1.checked == true) {
  26214. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  26215. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  26216. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  26217. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  26218. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  26219. if (optionsSpecific.length != 0) {
  26220. options = "var options = {";
  26221. options += "physics: {barnesHut: {";
  26222. for (var i = 0; i < optionsSpecific.length; i++) {
  26223. options += optionsSpecific[i];
  26224. if (i < optionsSpecific.length - 1) {
  26225. options += ", "
  26226. }
  26227. }
  26228. options += '}}'
  26229. }
  26230. if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {
  26231. if (optionsSpecific.length == 0) {options = "var options = {";}
  26232. else {options += ", "}
  26233. options += "smoothCurves: " + this.constants.smoothCurves.enabled;
  26234. }
  26235. if (options != "No options are required, default values used.") {
  26236. options += '};'
  26237. }
  26238. }
  26239. else if (radioButton2.checked == true) {
  26240. options = "var options = {";
  26241. options += "physics: {barnesHut: {enabled: false}";
  26242. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  26243. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  26244. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  26245. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  26246. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  26247. if (optionsSpecific.length != 0) {
  26248. options += ", repulsion: {";
  26249. for (var i = 0; i < optionsSpecific.length; i++) {
  26250. options += optionsSpecific[i];
  26251. if (i < optionsSpecific.length - 1) {
  26252. options += ", "
  26253. }
  26254. }
  26255. options += '}}'
  26256. }
  26257. if (optionsSpecific.length == 0) {options += "}"}
  26258. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  26259. options += ", smoothCurves: " + this.constants.smoothCurves;
  26260. }
  26261. options += '};'
  26262. }
  26263. else {
  26264. options = "var options = {";
  26265. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  26266. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  26267. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  26268. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  26269. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  26270. if (optionsSpecific.length != 0) {
  26271. options += "physics: {hierarchicalRepulsion: {";
  26272. for (var i = 0; i < optionsSpecific.length; i++) {
  26273. options += optionsSpecific[i];
  26274. if (i < optionsSpecific.length - 1) {
  26275. options += ", ";
  26276. }
  26277. }
  26278. options += '}},';
  26279. }
  26280. options += 'hierarchicalLayout: {';
  26281. optionsSpecific = [];
  26282. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  26283. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  26284. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  26285. if (optionsSpecific.length != 0) {
  26286. for (var i = 0; i < optionsSpecific.length; i++) {
  26287. options += optionsSpecific[i];
  26288. if (i < optionsSpecific.length - 1) {
  26289. options += ", "
  26290. }
  26291. }
  26292. options += '}'
  26293. }
  26294. else {
  26295. options += "enabled:true}";
  26296. }
  26297. options += '};'
  26298. }
  26299. this.optionsDiv.innerHTML = options;
  26300. }
  26301. /**
  26302. * this is used to switch between barnesHut, repulsion and hierarchical.
  26303. *
  26304. */
  26305. function switchConfigurations () {
  26306. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  26307. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  26308. var tableId = "graph_" + radioButton + "_table";
  26309. var table = document.getElementById(tableId);
  26310. table.style.display = "block";
  26311. for (var i = 0; i < ids.length; i++) {
  26312. if (ids[i] != tableId) {
  26313. table = document.getElementById(ids[i]);
  26314. table.style.display = "none";
  26315. }
  26316. }
  26317. this._restoreNodes();
  26318. if (radioButton == "R") {
  26319. this.constants.hierarchicalLayout.enabled = false;
  26320. this.constants.physics.hierarchicalRepulsion.enabled = false;
  26321. this.constants.physics.barnesHut.enabled = false;
  26322. }
  26323. else if (radioButton == "H") {
  26324. if (this.constants.hierarchicalLayout.enabled == false) {
  26325. this.constants.hierarchicalLayout.enabled = true;
  26326. this.constants.physics.hierarchicalRepulsion.enabled = true;
  26327. this.constants.physics.barnesHut.enabled = false;
  26328. this.constants.smoothCurves.enabled = false;
  26329. this._setupHierarchicalLayout();
  26330. }
  26331. }
  26332. else {
  26333. this.constants.hierarchicalLayout.enabled = false;
  26334. this.constants.physics.hierarchicalRepulsion.enabled = false;
  26335. this.constants.physics.barnesHut.enabled = true;
  26336. }
  26337. this._loadSelectedForceSolver();
  26338. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  26339. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  26340. else {graph_toggleSmooth.style.background = "#FF8532";}
  26341. this.moving = true;
  26342. this.start();
  26343. }
  26344. /**
  26345. * this generates the ranges depending on the iniital values.
  26346. *
  26347. * @param id
  26348. * @param map
  26349. * @param constantsVariableName
  26350. */
  26351. function showValueOfRange (id,map,constantsVariableName) {
  26352. var valueId = id + "_value";
  26353. var rangeValue = document.getElementById(id).value;
  26354. if (map instanceof Array) {
  26355. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  26356. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  26357. }
  26358. else {
  26359. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  26360. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  26361. }
  26362. if (constantsVariableName == "hierarchicalLayout_direction" ||
  26363. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  26364. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  26365. this._setupHierarchicalLayout();
  26366. }
  26367. this.moving = true;
  26368. this.start();
  26369. }
  26370. /***/ },
  26371. /* 57 */
  26372. /***/ function(module, exports, __webpack_require__) {
  26373. function webpackContext(req) {
  26374. throw new Error("Cannot find module '" + req + "'.");
  26375. }
  26376. webpackContext.resolve = webpackContext;
  26377. webpackContext.keys = function() { return []; };
  26378. module.exports = webpackContext;
  26379. /***/ },
  26380. /* 58 */
  26381. /***/ function(module, exports, __webpack_require__) {
  26382. module.exports = function(module) {
  26383. if(!module.webpackPolyfill) {
  26384. module.deprecate = function() {};
  26385. module.paths = [];
  26386. // module.parent = undefined by default
  26387. module.children = [];
  26388. module.webpackPolyfill = 1;
  26389. }
  26390. return module;
  26391. }
  26392. /***/ },
  26393. /* 59 */
  26394. /***/ function(module, exports, __webpack_require__) {
  26395. /**
  26396. * Calculate the forces the nodes apply on each other based on a repulsion field.
  26397. * This field is linearly approximated.
  26398. *
  26399. * @private
  26400. */
  26401. exports._calculateNodeForces = function () {
  26402. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  26403. repulsingForce, node1, node2, i, j;
  26404. var nodes = this.calculationNodes;
  26405. var nodeIndices = this.calculationNodeIndices;
  26406. // approximation constants
  26407. var a_base = -2 / 3;
  26408. var b = 4 / 3;
  26409. // repulsing forces between nodes
  26410. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  26411. var minimumDistance = nodeDistance;
  26412. // we loop from i over all but the last entree in the array
  26413. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  26414. for (i = 0; i < nodeIndices.length - 1; i++) {
  26415. node1 = nodes[nodeIndices[i]];
  26416. for (j = i + 1; j < nodeIndices.length; j++) {
  26417. node2 = nodes[nodeIndices[j]];
  26418. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  26419. dx = node2.x - node1.x;
  26420. dy = node2.y - node1.y;
  26421. distance = Math.sqrt(dx * dx + dy * dy);
  26422. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  26423. var a = a_base / minimumDistance;
  26424. if (distance < 2 * minimumDistance) {
  26425. if (distance < 0.5 * minimumDistance) {
  26426. repulsingForce = 1.0;
  26427. }
  26428. else {
  26429. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  26430. }
  26431. // amplify the repulsion for clusters.
  26432. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  26433. repulsingForce = repulsingForce / distance;
  26434. fx = dx * repulsingForce;
  26435. fy = dy * repulsingForce;
  26436. node1.fx -= fx;
  26437. node1.fy -= fy;
  26438. node2.fx += fx;
  26439. node2.fy += fy;
  26440. }
  26441. }
  26442. }
  26443. };
  26444. /***/ },
  26445. /* 60 */
  26446. /***/ function(module, exports, __webpack_require__) {
  26447. /**
  26448. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  26449. * This field is linearly approximated.
  26450. *
  26451. * @private
  26452. */
  26453. exports._calculateNodeForces = function () {
  26454. var dx, dy, distance, fx, fy,
  26455. repulsingForce, node1, node2, i, j;
  26456. var nodes = this.calculationNodes;
  26457. var nodeIndices = this.calculationNodeIndices;
  26458. // repulsing forces between nodes
  26459. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  26460. // we loop from i over all but the last entree in the array
  26461. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  26462. for (i = 0; i < nodeIndices.length - 1; i++) {
  26463. node1 = nodes[nodeIndices[i]];
  26464. for (j = i + 1; j < nodeIndices.length; j++) {
  26465. node2 = nodes[nodeIndices[j]];
  26466. // nodes only affect nodes on their level
  26467. if (node1.level == node2.level) {
  26468. dx = node2.x - node1.x;
  26469. dy = node2.y - node1.y;
  26470. distance = Math.sqrt(dx * dx + dy * dy);
  26471. var steepness = 0.05;
  26472. if (distance < nodeDistance) {
  26473. repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2);
  26474. }
  26475. else {
  26476. repulsingForce = 0;
  26477. }
  26478. // normalize force with
  26479. if (distance == 0) {
  26480. distance = 0.01;
  26481. }
  26482. else {
  26483. repulsingForce = repulsingForce / distance;
  26484. }
  26485. fx = dx * repulsingForce;
  26486. fy = dy * repulsingForce;
  26487. node1.fx -= fx;
  26488. node1.fy -= fy;
  26489. node2.fx += fx;
  26490. node2.fy += fy;
  26491. }
  26492. }
  26493. }
  26494. };
  26495. /**
  26496. * this function calculates the effects of the springs in the case of unsmooth curves.
  26497. *
  26498. * @private
  26499. */
  26500. exports._calculateHierarchicalSpringForces = function () {
  26501. var edgeLength, edge, edgeId;
  26502. var dx, dy, fx, fy, springForce, distance;
  26503. var edges = this.edges;
  26504. var nodes = this.calculationNodes;
  26505. var nodeIndices = this.calculationNodeIndices;
  26506. for (var i = 0; i < nodeIndices.length; i++) {
  26507. var node1 = nodes[nodeIndices[i]];
  26508. node1.springFx = 0;
  26509. node1.springFy = 0;
  26510. }
  26511. // forces caused by the edges, modelled as springs
  26512. for (edgeId in edges) {
  26513. if (edges.hasOwnProperty(edgeId)) {
  26514. edge = edges[edgeId];
  26515. if (edge.connected) {
  26516. // only calculate forces if nodes are in the same sector
  26517. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  26518. edgeLength = edge.physics.springLength;
  26519. // this implies that the edges between big clusters are longer
  26520. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  26521. dx = (edge.from.x - edge.to.x);
  26522. dy = (edge.from.y - edge.to.y);
  26523. distance = Math.sqrt(dx * dx + dy * dy);
  26524. if (distance == 0) {
  26525. distance = 0.01;
  26526. }
  26527. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  26528. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  26529. fx = dx * springForce;
  26530. fy = dy * springForce;
  26531. if (edge.to.level != edge.from.level) {
  26532. edge.to.springFx -= fx;
  26533. edge.to.springFy -= fy;
  26534. edge.from.springFx += fx;
  26535. edge.from.springFy += fy;
  26536. }
  26537. else {
  26538. var factor = 0.5;
  26539. edge.to.fx -= factor*fx;
  26540. edge.to.fy -= factor*fy;
  26541. edge.from.fx += factor*fx;
  26542. edge.from.fy += factor*fy;
  26543. }
  26544. }
  26545. }
  26546. }
  26547. }
  26548. // normalize spring forces
  26549. var springForce = 1;
  26550. var springFx, springFy;
  26551. for (i = 0; i < nodeIndices.length; i++) {
  26552. var node = nodes[nodeIndices[i]];
  26553. springFx = Math.min(springForce,Math.max(-springForce,node.springFx));
  26554. springFy = Math.min(springForce,Math.max(-springForce,node.springFy));
  26555. node.fx += springFx;
  26556. node.fy += springFy;
  26557. }
  26558. // retain energy balance
  26559. var totalFx = 0;
  26560. var totalFy = 0;
  26561. for (i = 0; i < nodeIndices.length; i++) {
  26562. var node = nodes[nodeIndices[i]];
  26563. totalFx += node.fx;
  26564. totalFy += node.fy;
  26565. }
  26566. var correctionFx = totalFx / nodeIndices.length;
  26567. var correctionFy = totalFy / nodeIndices.length;
  26568. for (i = 0; i < nodeIndices.length; i++) {
  26569. var node = nodes[nodeIndices[i]];
  26570. node.fx -= correctionFx;
  26571. node.fy -= correctionFy;
  26572. }
  26573. };
  26574. /***/ },
  26575. /* 61 */
  26576. /***/ function(module, exports, __webpack_require__) {
  26577. /**
  26578. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  26579. * The Barnes Hut method is used to speed up this N-body simulation.
  26580. *
  26581. * @private
  26582. */
  26583. exports._calculateNodeForces = function() {
  26584. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  26585. var node;
  26586. var nodes = this.calculationNodes;
  26587. var nodeIndices = this.calculationNodeIndices;
  26588. var nodeCount = nodeIndices.length;
  26589. this._formBarnesHutTree(nodes,nodeIndices);
  26590. var barnesHutTree = this.barnesHutTree;
  26591. // place the nodes one by one recursively
  26592. for (var i = 0; i < nodeCount; i++) {
  26593. node = nodes[nodeIndices[i]];
  26594. if (node.options.mass > 0) {
  26595. // starting with root is irrelevant, it never passes the BarnesHut condition
  26596. this._getForceContribution(barnesHutTree.root.children.NW,node);
  26597. this._getForceContribution(barnesHutTree.root.children.NE,node);
  26598. this._getForceContribution(barnesHutTree.root.children.SW,node);
  26599. this._getForceContribution(barnesHutTree.root.children.SE,node);
  26600. }
  26601. }
  26602. }
  26603. };
  26604. /**
  26605. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  26606. * If a region contains a single node, we check if it is not itself, then we apply the force.
  26607. *
  26608. * @param parentBranch
  26609. * @param node
  26610. * @private
  26611. */
  26612. exports._getForceContribution = function(parentBranch,node) {
  26613. // we get no force contribution from an empty region
  26614. if (parentBranch.childrenCount > 0) {
  26615. var dx,dy,distance;
  26616. // get the distance from the center of mass to the node.
  26617. dx = parentBranch.centerOfMass.x - node.x;
  26618. dy = parentBranch.centerOfMass.y - node.y;
  26619. distance = Math.sqrt(dx * dx + dy * dy);
  26620. // BarnesHut condition
  26621. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  26622. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  26623. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  26624. // duplicate code to reduce function calls to speed up program
  26625. if (distance == 0) {
  26626. distance = 0.1*Math.random();
  26627. dx = distance;
  26628. }
  26629. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  26630. var fx = dx * gravityForce;
  26631. var fy = dy * gravityForce;
  26632. node.fx += fx;
  26633. node.fy += fy;
  26634. }
  26635. else {
  26636. // Did not pass the condition, go into children if available
  26637. if (parentBranch.childrenCount == 4) {
  26638. this._getForceContribution(parentBranch.children.NW,node);
  26639. this._getForceContribution(parentBranch.children.NE,node);
  26640. this._getForceContribution(parentBranch.children.SW,node);
  26641. this._getForceContribution(parentBranch.children.SE,node);
  26642. }
  26643. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  26644. if (parentBranch.children.data.id != node.id) { // if it is not self
  26645. // duplicate code to reduce function calls to speed up program
  26646. if (distance == 0) {
  26647. distance = 0.5*Math.random();
  26648. dx = distance;
  26649. }
  26650. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  26651. var fx = dx * gravityForce;
  26652. var fy = dy * gravityForce;
  26653. node.fx += fx;
  26654. node.fy += fy;
  26655. }
  26656. }
  26657. }
  26658. }
  26659. };
  26660. /**
  26661. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  26662. *
  26663. * @param nodes
  26664. * @param nodeIndices
  26665. * @private
  26666. */
  26667. exports._formBarnesHutTree = function(nodes,nodeIndices) {
  26668. var node;
  26669. var nodeCount = nodeIndices.length;
  26670. var minX = Number.MAX_VALUE,
  26671. minY = Number.MAX_VALUE,
  26672. maxX =-Number.MAX_VALUE,
  26673. maxY =-Number.MAX_VALUE;
  26674. // get the range of the nodes
  26675. for (var i = 0; i < nodeCount; i++) {
  26676. var x = nodes[nodeIndices[i]].x;
  26677. var y = nodes[nodeIndices[i]].y;
  26678. if (nodes[nodeIndices[i]].options.mass > 0) {
  26679. if (x < minX) { minX = x; }
  26680. if (x > maxX) { maxX = x; }
  26681. if (y < minY) { minY = y; }
  26682. if (y > maxY) { maxY = y; }
  26683. }
  26684. }
  26685. // make the range a square
  26686. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  26687. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  26688. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  26689. var minimumTreeSize = 1e-5;
  26690. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  26691. var halfRootSize = 0.5 * rootSize;
  26692. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  26693. // construct the barnesHutTree
  26694. var barnesHutTree = {
  26695. root:{
  26696. centerOfMass: {x:0, y:0},
  26697. mass:0,
  26698. range: {
  26699. minX: centerX-halfRootSize,maxX:centerX+halfRootSize,
  26700. minY: centerY-halfRootSize,maxY:centerY+halfRootSize
  26701. },
  26702. size: rootSize,
  26703. calcSize: 1 / rootSize,
  26704. children: { data:null},
  26705. maxWidth: 0,
  26706. level: 0,
  26707. childrenCount: 4
  26708. }
  26709. };
  26710. this._splitBranch(barnesHutTree.root);
  26711. // place the nodes one by one recursively
  26712. for (i = 0; i < nodeCount; i++) {
  26713. node = nodes[nodeIndices[i]];
  26714. if (node.options.mass > 0) {
  26715. this._placeInTree(barnesHutTree.root,node);
  26716. }
  26717. }
  26718. // make global
  26719. this.barnesHutTree = barnesHutTree
  26720. };
  26721. /**
  26722. * this updates the mass of a branch. this is increased by adding a node.
  26723. *
  26724. * @param parentBranch
  26725. * @param node
  26726. * @private
  26727. */
  26728. exports._updateBranchMass = function(parentBranch, node) {
  26729. var totalMass = parentBranch.mass + node.options.mass;
  26730. var totalMassInv = 1/totalMass;
  26731. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  26732. parentBranch.centerOfMass.x *= totalMassInv;
  26733. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  26734. parentBranch.centerOfMass.y *= totalMassInv;
  26735. parentBranch.mass = totalMass;
  26736. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  26737. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  26738. };
  26739. /**
  26740. * determine in which branch the node will be placed.
  26741. *
  26742. * @param parentBranch
  26743. * @param node
  26744. * @param skipMassUpdate
  26745. * @private
  26746. */
  26747. exports._placeInTree = function(parentBranch,node,skipMassUpdate) {
  26748. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  26749. // update the mass of the branch.
  26750. this._updateBranchMass(parentBranch,node);
  26751. }
  26752. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  26753. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  26754. this._placeInRegion(parentBranch,node,"NW");
  26755. }
  26756. else { // in SW
  26757. this._placeInRegion(parentBranch,node,"SW");
  26758. }
  26759. }
  26760. else { // in NE or SE
  26761. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  26762. this._placeInRegion(parentBranch,node,"NE");
  26763. }
  26764. else { // in SE
  26765. this._placeInRegion(parentBranch,node,"SE");
  26766. }
  26767. }
  26768. };
  26769. /**
  26770. * actually place the node in a region (or branch)
  26771. *
  26772. * @param parentBranch
  26773. * @param node
  26774. * @param region
  26775. * @private
  26776. */
  26777. exports._placeInRegion = function(parentBranch,node,region) {
  26778. switch (parentBranch.children[region].childrenCount) {
  26779. case 0: // place node here
  26780. parentBranch.children[region].children.data = node;
  26781. parentBranch.children[region].childrenCount = 1;
  26782. this._updateBranchMass(parentBranch.children[region],node);
  26783. break;
  26784. case 1: // convert into children
  26785. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  26786. // we move one node a pixel and we do not put it in the tree.
  26787. if (parentBranch.children[region].children.data.x == node.x &&
  26788. parentBranch.children[region].children.data.y == node.y) {
  26789. node.x += Math.random();
  26790. node.y += Math.random();
  26791. }
  26792. else {
  26793. this._splitBranch(parentBranch.children[region]);
  26794. this._placeInTree(parentBranch.children[region],node);
  26795. }
  26796. break;
  26797. case 4: // place in branch
  26798. this._placeInTree(parentBranch.children[region],node);
  26799. break;
  26800. }
  26801. };
  26802. /**
  26803. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  26804. * after the split is complete.
  26805. *
  26806. * @param parentBranch
  26807. * @private
  26808. */
  26809. exports._splitBranch = function(parentBranch) {
  26810. // if the branch is shaded with a node, replace the node in the new subset.
  26811. var containedNode = null;
  26812. if (parentBranch.childrenCount == 1) {
  26813. containedNode = parentBranch.children.data;
  26814. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  26815. }
  26816. parentBranch.childrenCount = 4;
  26817. parentBranch.children.data = null;
  26818. this._insertRegion(parentBranch,"NW");
  26819. this._insertRegion(parentBranch,"NE");
  26820. this._insertRegion(parentBranch,"SW");
  26821. this._insertRegion(parentBranch,"SE");
  26822. if (containedNode != null) {
  26823. this._placeInTree(parentBranch,containedNode);
  26824. }
  26825. };
  26826. /**
  26827. * This function subdivides the region into four new segments.
  26828. * Specifically, this inserts a single new segment.
  26829. * It fills the children section of the parentBranch
  26830. *
  26831. * @param parentBranch
  26832. * @param region
  26833. * @param parentRange
  26834. * @private
  26835. */
  26836. exports._insertRegion = function(parentBranch, region) {
  26837. var minX,maxX,minY,maxY;
  26838. var childSize = 0.5 * parentBranch.size;
  26839. switch (region) {
  26840. case "NW":
  26841. minX = parentBranch.range.minX;
  26842. maxX = parentBranch.range.minX + childSize;
  26843. minY = parentBranch.range.minY;
  26844. maxY = parentBranch.range.minY + childSize;
  26845. break;
  26846. case "NE":
  26847. minX = parentBranch.range.minX + childSize;
  26848. maxX = parentBranch.range.maxX;
  26849. minY = parentBranch.range.minY;
  26850. maxY = parentBranch.range.minY + childSize;
  26851. break;
  26852. case "SW":
  26853. minX = parentBranch.range.minX;
  26854. maxX = parentBranch.range.minX + childSize;
  26855. minY = parentBranch.range.minY + childSize;
  26856. maxY = parentBranch.range.maxY;
  26857. break;
  26858. case "SE":
  26859. minX = parentBranch.range.minX + childSize;
  26860. maxX = parentBranch.range.maxX;
  26861. minY = parentBranch.range.minY + childSize;
  26862. maxY = parentBranch.range.maxY;
  26863. break;
  26864. }
  26865. parentBranch.children[region] = {
  26866. centerOfMass:{x:0,y:0},
  26867. mass:0,
  26868. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  26869. size: 0.5 * parentBranch.size,
  26870. calcSize: 2 * parentBranch.calcSize,
  26871. children: {data:null},
  26872. maxWidth: 0,
  26873. level: parentBranch.level+1,
  26874. childrenCount: 0
  26875. };
  26876. };
  26877. /**
  26878. * This function is for debugging purposed, it draws the tree.
  26879. *
  26880. * @param ctx
  26881. * @param color
  26882. * @private
  26883. */
  26884. exports._drawTree = function(ctx,color) {
  26885. if (this.barnesHutTree !== undefined) {
  26886. ctx.lineWidth = 1;
  26887. this._drawBranch(this.barnesHutTree.root,ctx,color);
  26888. }
  26889. };
  26890. /**
  26891. * This function is for debugging purposes. It draws the branches recursively.
  26892. *
  26893. * @param branch
  26894. * @param ctx
  26895. * @param color
  26896. * @private
  26897. */
  26898. exports._drawBranch = function(branch,ctx,color) {
  26899. if (color === undefined) {
  26900. color = "#FF0000";
  26901. }
  26902. if (branch.childrenCount == 4) {
  26903. this._drawBranch(branch.children.NW,ctx);
  26904. this._drawBranch(branch.children.NE,ctx);
  26905. this._drawBranch(branch.children.SE,ctx);
  26906. this._drawBranch(branch.children.SW,ctx);
  26907. }
  26908. ctx.strokeStyle = color;
  26909. ctx.beginPath();
  26910. ctx.moveTo(branch.range.minX,branch.range.minY);
  26911. ctx.lineTo(branch.range.maxX,branch.range.minY);
  26912. ctx.stroke();
  26913. ctx.beginPath();
  26914. ctx.moveTo(branch.range.maxX,branch.range.minY);
  26915. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  26916. ctx.stroke();
  26917. ctx.beginPath();
  26918. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  26919. ctx.lineTo(branch.range.minX,branch.range.maxY);
  26920. ctx.stroke();
  26921. ctx.beginPath();
  26922. ctx.moveTo(branch.range.minX,branch.range.maxY);
  26923. ctx.lineTo(branch.range.minX,branch.range.minY);
  26924. ctx.stroke();
  26925. /*
  26926. if (branch.mass > 0) {
  26927. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  26928. ctx.stroke();
  26929. }
  26930. */
  26931. };
  26932. /***/ }
  26933. /******/ ])
  26934. });