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.

22599 lines
668 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version @@version
  8. * @date @@date
  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(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Test whether all elements in two arrays are equal.
  354. * @param {Array} a
  355. * @param {Array} b
  356. * @return {boolean} Returns true if both arrays have the same length and same
  357. * elements.
  358. */
  359. util.equalArray = function (a, b) {
  360. if (a.length != b.length) return false;
  361. for (var i = 1, len = a.length; i < len; i++) {
  362. if (a[i] != b[i]) return false;
  363. }
  364. return true;
  365. };
  366. /**
  367. * Convert an object to another type
  368. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  369. * @param {String | undefined} type Name of the type. Available types:
  370. * 'Boolean', 'Number', 'String',
  371. * 'Date', 'Moment', ISODate', 'ASPDate'.
  372. * @return {*} object
  373. * @throws Error
  374. */
  375. util.convert = function convert(object, type) {
  376. var match;
  377. if (object === undefined) {
  378. return undefined;
  379. }
  380. if (object === null) {
  381. return null;
  382. }
  383. if (!type) {
  384. return object;
  385. }
  386. if (!(typeof type === 'string') && !(type instanceof String)) {
  387. throw new Error('Type must be a string');
  388. }
  389. //noinspection FallthroughInSwitchStatementJS
  390. switch (type) {
  391. case 'boolean':
  392. case 'Boolean':
  393. return Boolean(object);
  394. case 'number':
  395. case 'Number':
  396. return Number(object.valueOf());
  397. case 'string':
  398. case 'String':
  399. return String(object);
  400. case 'Date':
  401. if (util.isNumber(object)) {
  402. return new Date(object);
  403. }
  404. if (object instanceof Date) {
  405. return new Date(object.valueOf());
  406. }
  407. else if (moment.isMoment(object)) {
  408. return new Date(object.valueOf());
  409. }
  410. if (util.isString(object)) {
  411. match = ASPDateRegex.exec(object);
  412. if (match) {
  413. // object is an ASP date
  414. return new Date(Number(match[1])); // parse number
  415. }
  416. else {
  417. return moment(object).toDate(); // parse string
  418. }
  419. }
  420. else {
  421. throw new Error(
  422. 'Cannot convert object of type ' + util.getType(object) +
  423. ' to type Date');
  424. }
  425. case 'Moment':
  426. if (util.isNumber(object)) {
  427. return moment(object);
  428. }
  429. if (object instanceof Date) {
  430. return moment(object.valueOf());
  431. }
  432. else if (moment.isMoment(object)) {
  433. return moment(object);
  434. }
  435. if (util.isString(object)) {
  436. match = ASPDateRegex.exec(object);
  437. if (match) {
  438. // object is an ASP date
  439. return moment(Number(match[1])); // parse number
  440. }
  441. else {
  442. return moment(object); // parse string
  443. }
  444. }
  445. else {
  446. throw new Error(
  447. 'Cannot convert object of type ' + util.getType(object) +
  448. ' to type Date');
  449. }
  450. case 'ISODate':
  451. if (util.isNumber(object)) {
  452. return new Date(object);
  453. }
  454. else if (object instanceof Date) {
  455. return object.toISOString();
  456. }
  457. else if (moment.isMoment(object)) {
  458. return object.toDate().toISOString();
  459. }
  460. else if (util.isString(object)) {
  461. match = ASPDateRegex.exec(object);
  462. if (match) {
  463. // object is an ASP date
  464. return new Date(Number(match[1])).toISOString(); // parse number
  465. }
  466. else {
  467. return new Date(object).toISOString(); // parse string
  468. }
  469. }
  470. else {
  471. throw new Error(
  472. 'Cannot convert object of type ' + util.getType(object) +
  473. ' to type ISODate');
  474. }
  475. case 'ASPDate':
  476. if (util.isNumber(object)) {
  477. return '/Date(' + object + ')/';
  478. }
  479. else if (object instanceof Date) {
  480. return '/Date(' + object.valueOf() + ')/';
  481. }
  482. else if (util.isString(object)) {
  483. match = ASPDateRegex.exec(object);
  484. var value;
  485. if (match) {
  486. // object is an ASP date
  487. value = new Date(Number(match[1])).valueOf(); // parse number
  488. }
  489. else {
  490. value = new Date(object).valueOf(); // parse string
  491. }
  492. return '/Date(' + value + ')/';
  493. }
  494. else {
  495. throw new Error(
  496. 'Cannot convert object of type ' + util.getType(object) +
  497. ' to type ASPDate');
  498. }
  499. default:
  500. throw new Error('Cannot convert object of type ' + util.getType(object) +
  501. ' to type "' + type + '"');
  502. }
  503. };
  504. // parse ASP.Net Date pattern,
  505. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  506. // code from http://momentjs.com/
  507. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  508. /**
  509. * Get the type of an object, for example util.getType([]) returns 'Array'
  510. * @param {*} object
  511. * @return {String} type
  512. */
  513. util.getType = function getType(object) {
  514. var type = typeof object;
  515. if (type == 'object') {
  516. if (object == null) {
  517. return 'null';
  518. }
  519. if (object instanceof Boolean) {
  520. return 'Boolean';
  521. }
  522. if (object instanceof Number) {
  523. return 'Number';
  524. }
  525. if (object instanceof String) {
  526. return 'String';
  527. }
  528. if (object instanceof Array) {
  529. return 'Array';
  530. }
  531. if (object instanceof Date) {
  532. return 'Date';
  533. }
  534. return 'Object';
  535. }
  536. else if (type == 'number') {
  537. return 'Number';
  538. }
  539. else if (type == 'boolean') {
  540. return 'Boolean';
  541. }
  542. else if (type == 'string') {
  543. return 'String';
  544. }
  545. return type;
  546. };
  547. /**
  548. * Retrieve the absolute left value of a DOM element
  549. * @param {Element} elem A dom element, for example a div
  550. * @return {number} left The absolute left position of this element
  551. * in the browser page.
  552. */
  553. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  554. var doc = document.documentElement;
  555. var body = document.body;
  556. var left = elem.offsetLeft;
  557. var e = elem.offsetParent;
  558. while (e != null && e != body && e != doc) {
  559. left += e.offsetLeft;
  560. left -= e.scrollLeft;
  561. e = e.offsetParent;
  562. }
  563. return left;
  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. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  572. var doc = document.documentElement;
  573. var body = document.body;
  574. var top = elem.offsetTop;
  575. var e = elem.offsetParent;
  576. while (e != null && e != body && e != doc) {
  577. top += e.offsetTop;
  578. top -= e.scrollTop;
  579. e = e.offsetParent;
  580. }
  581. return top;
  582. };
  583. /**
  584. * Get the absolute, vertical mouse position from an event.
  585. * @param {Event} event
  586. * @return {Number} pageY
  587. */
  588. util.getPageY = function getPageY (event) {
  589. if ('pageY' in event) {
  590. return event.pageY;
  591. }
  592. else {
  593. var clientY;
  594. if (('targetTouches' in event) && event.targetTouches.length) {
  595. clientY = event.targetTouches[0].clientY;
  596. }
  597. else {
  598. clientY = event.clientY;
  599. }
  600. var doc = document.documentElement;
  601. var body = document.body;
  602. return clientY +
  603. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  604. ( doc && doc.clientTop || body && body.clientTop || 0 );
  605. }
  606. };
  607. /**
  608. * Get the absolute, horizontal mouse position from an event.
  609. * @param {Event} event
  610. * @return {Number} pageX
  611. */
  612. util.getPageX = function getPageX (event) {
  613. if ('pageY' in event) {
  614. return event.pageX;
  615. }
  616. else {
  617. var clientX;
  618. if (('targetTouches' in event) && event.targetTouches.length) {
  619. clientX = event.targetTouches[0].clientX;
  620. }
  621. else {
  622. clientX = event.clientX;
  623. }
  624. var doc = document.documentElement;
  625. var body = document.body;
  626. return clientX +
  627. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  628. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  629. }
  630. };
  631. /**
  632. * add a className to the given elements style
  633. * @param {Element} elem
  634. * @param {String} className
  635. */
  636. util.addClassName = function addClassName(elem, className) {
  637. var classes = elem.className.split(' ');
  638. if (classes.indexOf(className) == -1) {
  639. classes.push(className); // add the class to the array
  640. elem.className = classes.join(' ');
  641. }
  642. };
  643. /**
  644. * add a className to the given elements style
  645. * @param {Element} elem
  646. * @param {String} className
  647. */
  648. util.removeClassName = function removeClassname(elem, className) {
  649. var classes = elem.className.split(' ');
  650. var index = classes.indexOf(className);
  651. if (index != -1) {
  652. classes.splice(index, 1); // remove the class from the array
  653. elem.className = classes.join(' ');
  654. }
  655. };
  656. /**
  657. * For each method for both arrays and objects.
  658. * In case of an array, the built-in Array.forEach() is applied.
  659. * In case of an Object, the method loops over all properties of the object.
  660. * @param {Object | Array} object An Object or Array
  661. * @param {function} callback Callback method, called for each item in
  662. * the object or array with three parameters:
  663. * callback(value, index, object)
  664. */
  665. util.forEach = function forEach (object, callback) {
  666. var i,
  667. len;
  668. if (object instanceof Array) {
  669. // array
  670. for (i = 0, len = object.length; i < len; i++) {
  671. callback(object[i], i, object);
  672. }
  673. }
  674. else {
  675. // object
  676. for (i in object) {
  677. if (object.hasOwnProperty(i)) {
  678. callback(object[i], i, object);
  679. }
  680. }
  681. }
  682. };
  683. /**
  684. * Convert an object into an array: all objects properties are put into the
  685. * array. The resulting array is unordered.
  686. * @param {Object} object
  687. * @param {Array} array
  688. */
  689. util.toArray = function toArray(object) {
  690. var array = [];
  691. for (var prop in object) {
  692. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  693. }
  694. return array;
  695. }
  696. /**
  697. * Update a property in an object
  698. * @param {Object} object
  699. * @param {String} key
  700. * @param {*} value
  701. * @return {Boolean} changed
  702. */
  703. util.updateProperty = function updateProperty (object, key, value) {
  704. if (object[key] !== value) {
  705. object[key] = value;
  706. return true;
  707. }
  708. else {
  709. return false;
  710. }
  711. };
  712. /**
  713. * Add and event listener. Works for all browsers
  714. * @param {Element} element An html element
  715. * @param {string} action The action, for example "click",
  716. * without the prefix "on"
  717. * @param {function} listener The callback function to be executed
  718. * @param {boolean} [useCapture]
  719. */
  720. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  721. if (element.addEventListener) {
  722. if (useCapture === undefined)
  723. useCapture = false;
  724. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  725. action = "DOMMouseScroll"; // For Firefox
  726. }
  727. element.addEventListener(action, listener, useCapture);
  728. } else {
  729. element.attachEvent("on" + action, listener); // IE browsers
  730. }
  731. };
  732. /**
  733. * Remove an event listener from an element
  734. * @param {Element} element An html dom element
  735. * @param {string} action The name of the event, for example "mousedown"
  736. * @param {function} listener The listener function
  737. * @param {boolean} [useCapture]
  738. */
  739. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  740. if (element.removeEventListener) {
  741. // non-IE browsers
  742. if (useCapture === undefined)
  743. useCapture = false;
  744. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  745. action = "DOMMouseScroll"; // For Firefox
  746. }
  747. element.removeEventListener(action, listener, useCapture);
  748. } else {
  749. // IE browsers
  750. element.detachEvent("on" + action, listener);
  751. }
  752. };
  753. /**
  754. * Get HTML element which is the target of the event
  755. * @param {Event} event
  756. * @return {Element} target element
  757. */
  758. util.getTarget = function getTarget(event) {
  759. // code from http://www.quirksmode.org/js/events_properties.html
  760. if (!event) {
  761. event = window.event;
  762. }
  763. var target;
  764. if (event.target) {
  765. target = event.target;
  766. }
  767. else if (event.srcElement) {
  768. target = event.srcElement;
  769. }
  770. if (target.nodeType != undefined && target.nodeType == 3) {
  771. // defeat Safari bug
  772. target = target.parentNode;
  773. }
  774. return target;
  775. };
  776. /**
  777. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  778. * @param {Element} element
  779. * @param {Event} event
  780. */
  781. util.fakeGesture = function fakeGesture (element, event) {
  782. var eventType = null;
  783. // for hammer.js 1.0.5
  784. var gesture = Hammer.event.collectEventData(this, eventType, event);
  785. // for hammer.js 1.0.6
  786. //var touches = Hammer.event.getTouchList(event, eventType);
  787. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  788. // on IE in standards mode, no touches are recognized by hammer.js,
  789. // resulting in NaN values for center.pageX and center.pageY
  790. if (isNaN(gesture.center.pageX)) {
  791. gesture.center.pageX = event.pageX;
  792. }
  793. if (isNaN(gesture.center.pageY)) {
  794. gesture.center.pageY = event.pageY;
  795. }
  796. return gesture;
  797. };
  798. util.option = {};
  799. /**
  800. * Convert a value into a boolean
  801. * @param {Boolean | function | undefined} value
  802. * @param {Boolean} [defaultValue]
  803. * @returns {Boolean} bool
  804. */
  805. util.option.asBoolean = function (value, defaultValue) {
  806. if (typeof value == 'function') {
  807. value = value();
  808. }
  809. if (value != null) {
  810. return (value != false);
  811. }
  812. return defaultValue || null;
  813. };
  814. /**
  815. * Convert a value into a number
  816. * @param {Boolean | function | undefined} value
  817. * @param {Number} [defaultValue]
  818. * @returns {Number} number
  819. */
  820. util.option.asNumber = function (value, defaultValue) {
  821. if (typeof value == 'function') {
  822. value = value();
  823. }
  824. if (value != null) {
  825. return Number(value) || defaultValue || null;
  826. }
  827. return defaultValue || null;
  828. };
  829. /**
  830. * Convert a value into a string
  831. * @param {String | function | undefined} value
  832. * @param {String} [defaultValue]
  833. * @returns {String} str
  834. */
  835. util.option.asString = function (value, defaultValue) {
  836. if (typeof value == 'function') {
  837. value = value();
  838. }
  839. if (value != null) {
  840. return String(value);
  841. }
  842. return defaultValue || null;
  843. };
  844. /**
  845. * Convert a size or location into a string with pixels or a percentage
  846. * @param {String | Number | function | undefined} value
  847. * @param {String} [defaultValue]
  848. * @returns {String} size
  849. */
  850. util.option.asSize = function (value, defaultValue) {
  851. if (typeof value == 'function') {
  852. value = value();
  853. }
  854. if (util.isString(value)) {
  855. return value;
  856. }
  857. else if (util.isNumber(value)) {
  858. return value + 'px';
  859. }
  860. else {
  861. return defaultValue || null;
  862. }
  863. };
  864. /**
  865. * Convert a value into a DOM element
  866. * @param {HTMLElement | function | undefined} value
  867. * @param {HTMLElement} [defaultValue]
  868. * @returns {HTMLElement | null} dom
  869. */
  870. util.option.asElement = function (value, defaultValue) {
  871. if (typeof value == 'function') {
  872. value = value();
  873. }
  874. return value || defaultValue || null;
  875. };
  876. util.GiveDec = function GiveDec(Hex) {
  877. var Value;
  878. if (Hex == "A")
  879. Value = 10;
  880. else if (Hex == "B")
  881. Value = 11;
  882. else if (Hex == "C")
  883. Value = 12;
  884. else if (Hex == "D")
  885. Value = 13;
  886. else if (Hex == "E")
  887. Value = 14;
  888. else if (Hex == "F")
  889. Value = 15;
  890. else
  891. Value = eval(Hex);
  892. return Value;
  893. };
  894. util.GiveHex = function GiveHex(Dec) {
  895. var Value;
  896. if(Dec == 10)
  897. Value = "A";
  898. else if (Dec == 11)
  899. Value = "B";
  900. else if (Dec == 12)
  901. Value = "C";
  902. else if (Dec == 13)
  903. Value = "D";
  904. else if (Dec == 14)
  905. Value = "E";
  906. else if (Dec == 15)
  907. Value = "F";
  908. else
  909. Value = "" + Dec;
  910. return Value;
  911. };
  912. /**
  913. * Parse a color property into an object with border, background, and
  914. * highlight colors
  915. * @param {Object | String} color
  916. * @return {Object} colorObject
  917. */
  918. util.parseColor = function(color) {
  919. var c;
  920. if (util.isString(color)) {
  921. if (util.isValidHex(color)) {
  922. var hsv = util.hexToHSV(color);
  923. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  924. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  925. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  926. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  927. c = {
  928. background: color,
  929. border:darkerColorHex,
  930. highlight: {
  931. background:lighterColorHex,
  932. border:darkerColorHex
  933. }
  934. };
  935. }
  936. else {
  937. c = {
  938. background:color,
  939. border:color,
  940. highlight: {
  941. background:color,
  942. border:color
  943. }
  944. };
  945. }
  946. }
  947. else {
  948. c = {};
  949. c.background = color.background || 'white';
  950. c.border = color.border || c.background;
  951. if (util.isString(color.highlight)) {
  952. c.highlight = {
  953. border: color.highlight,
  954. background: color.highlight
  955. }
  956. }
  957. else {
  958. c.highlight = {};
  959. c.highlight.background = color.highlight && color.highlight.background || c.background;
  960. c.highlight.border = color.highlight && color.highlight.border || c.border;
  961. }
  962. }
  963. return c;
  964. };
  965. /**
  966. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  967. *
  968. * @param {String} hex
  969. * @returns {{r: *, g: *, b: *}}
  970. */
  971. util.hexToRGB = function hexToRGB(hex) {
  972. hex = hex.replace("#","").toUpperCase();
  973. var a = util.GiveDec(hex.substring(0, 1));
  974. var b = util.GiveDec(hex.substring(1, 2));
  975. var c = util.GiveDec(hex.substring(2, 3));
  976. var d = util.GiveDec(hex.substring(3, 4));
  977. var e = util.GiveDec(hex.substring(4, 5));
  978. var f = util.GiveDec(hex.substring(5, 6));
  979. var r = (a * 16) + b;
  980. var g = (c * 16) + d;
  981. var b = (e * 16) + f;
  982. return {r:r,g:g,b:b};
  983. };
  984. util.RGBToHex = function RGBToHex(red,green,blue) {
  985. var a = util.GiveHex(Math.floor(red / 16));
  986. var b = util.GiveHex(red % 16);
  987. var c = util.GiveHex(Math.floor(green / 16));
  988. var d = util.GiveHex(green % 16);
  989. var e = util.GiveHex(Math.floor(blue / 16));
  990. var f = util.GiveHex(blue % 16);
  991. var hex = a + b + c + d + e + f;
  992. return "#" + hex;
  993. };
  994. /**
  995. * http://www.javascripter.net/faq/rgb2hsv.htm
  996. *
  997. * @param red
  998. * @param green
  999. * @param blue
  1000. * @returns {*}
  1001. * @constructor
  1002. */
  1003. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1004. red=red/255; green=green/255; blue=blue/255;
  1005. var minRGB = Math.min(red,Math.min(green,blue));
  1006. var maxRGB = Math.max(red,Math.max(green,blue));
  1007. // Black-gray-white
  1008. if (minRGB == maxRGB) {
  1009. return {h:0,s:0,v:minRGB};
  1010. }
  1011. // Colors other than black-gray-white:
  1012. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1013. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1014. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1015. var saturation = (maxRGB - minRGB)/maxRGB;
  1016. var value = maxRGB;
  1017. return {h:hue,s:saturation,v:value};
  1018. };
  1019. /**
  1020. * https://gist.github.com/mjijackson/5311256
  1021. * @param hue
  1022. * @param saturation
  1023. * @param value
  1024. * @returns {{r: number, g: number, b: number}}
  1025. * @constructor
  1026. */
  1027. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1028. var r, g, b;
  1029. var i = Math.floor(h * 6);
  1030. var f = h * 6 - i;
  1031. var p = v * (1 - s);
  1032. var q = v * (1 - f * s);
  1033. var t = v * (1 - (1 - f) * s);
  1034. switch (i % 6) {
  1035. case 0: r = v, g = t, b = p; break;
  1036. case 1: r = q, g = v, b = p; break;
  1037. case 2: r = p, g = v, b = t; break;
  1038. case 3: r = p, g = q, b = v; break;
  1039. case 4: r = t, g = p, b = v; break;
  1040. case 5: r = v, g = p, b = q; break;
  1041. }
  1042. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1043. };
  1044. util.HSVToHex = function HSVToHex(h, s, v) {
  1045. var rgb = util.HSVToRGB(h, s, v);
  1046. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1047. };
  1048. util.hexToHSV = function hexToHSV(hex) {
  1049. var rgb = util.hexToRGB(hex);
  1050. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1051. };
  1052. util.isValidHex = function isValidHex(hex) {
  1053. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1054. return isOk;
  1055. };
  1056. util.copyObject = function copyObject(objectFrom, objectTo) {
  1057. for (var i in objectFrom) {
  1058. if (objectFrom.hasOwnProperty(i)) {
  1059. if (typeof objectFrom[i] == "object") {
  1060. objectTo[i] = {};
  1061. util.copyObject(objectFrom[i], objectTo[i]);
  1062. }
  1063. else {
  1064. objectTo[i] = objectFrom[i];
  1065. }
  1066. }
  1067. }
  1068. };
  1069. /**
  1070. * DataSet
  1071. *
  1072. * Usage:
  1073. * var dataSet = new DataSet({
  1074. * fieldId: '_id',
  1075. * convert: {
  1076. * // ...
  1077. * }
  1078. * });
  1079. *
  1080. * dataSet.add(item);
  1081. * dataSet.add(data);
  1082. * dataSet.update(item);
  1083. * dataSet.update(data);
  1084. * dataSet.remove(id);
  1085. * dataSet.remove(ids);
  1086. * var data = dataSet.get();
  1087. * var data = dataSet.get(id);
  1088. * var data = dataSet.get(ids);
  1089. * var data = dataSet.get(ids, options, data);
  1090. * dataSet.clear();
  1091. *
  1092. * A data set can:
  1093. * - add/remove/update data
  1094. * - gives triggers upon changes in the data
  1095. * - can import/export data in various data formats
  1096. *
  1097. * @param {Array | DataTable} [data] Optional array with initial data
  1098. * @param {Object} [options] Available options:
  1099. * {String} fieldId Field name of the id in the
  1100. * items, 'id' by default.
  1101. * {Object.<String, String} convert
  1102. * A map with field names as key,
  1103. * and the field type as value.
  1104. * @constructor DataSet
  1105. */
  1106. // TODO: add a DataSet constructor DataSet(data, options)
  1107. function DataSet (data, options) {
  1108. this.id = util.randomUUID();
  1109. // correctly read optional arguments
  1110. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1111. options = data;
  1112. data = null;
  1113. }
  1114. this.options = options || {};
  1115. this.data = {}; // map with data indexed by id
  1116. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1117. this.convert = {}; // field types by field name
  1118. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1119. if (this.options.convert) {
  1120. for (var field in this.options.convert) {
  1121. if (this.options.convert.hasOwnProperty(field)) {
  1122. var value = this.options.convert[field];
  1123. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1124. this.convert[field] = 'Date';
  1125. }
  1126. else {
  1127. this.convert[field] = value;
  1128. }
  1129. }
  1130. }
  1131. }
  1132. this.subscribers = {}; // event subscribers
  1133. this.internalIds = {}; // internally generated id's
  1134. // add initial data when provided
  1135. if (data) {
  1136. this.add(data);
  1137. }
  1138. }
  1139. /**
  1140. * Subscribe to an event, add an event listener
  1141. * @param {String} event Event name. Available events: 'put', 'update',
  1142. * 'remove'
  1143. * @param {function} callback Callback method. Called with three parameters:
  1144. * {String} event
  1145. * {Object | null} params
  1146. * {String | Number} senderId
  1147. */
  1148. DataSet.prototype.on = function on (event, callback) {
  1149. var subscribers = this.subscribers[event];
  1150. if (!subscribers) {
  1151. subscribers = [];
  1152. this.subscribers[event] = subscribers;
  1153. }
  1154. subscribers.push({
  1155. callback: callback
  1156. });
  1157. };
  1158. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1159. DataSet.prototype.subscribe = DataSet.prototype.on;
  1160. /**
  1161. * Unsubscribe from an event, remove an event listener
  1162. * @param {String} event
  1163. * @param {function} callback
  1164. */
  1165. DataSet.prototype.off = function off(event, callback) {
  1166. var subscribers = this.subscribers[event];
  1167. if (subscribers) {
  1168. this.subscribers[event] = subscribers.filter(function (listener) {
  1169. return (listener.callback != callback);
  1170. });
  1171. }
  1172. };
  1173. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1174. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1175. /**
  1176. * Trigger an event
  1177. * @param {String} event
  1178. * @param {Object | null} params
  1179. * @param {String} [senderId] Optional id of the sender.
  1180. * @private
  1181. */
  1182. DataSet.prototype._trigger = function (event, params, senderId) {
  1183. if (event == '*') {
  1184. throw new Error('Cannot trigger event *');
  1185. }
  1186. var subscribers = [];
  1187. if (event in this.subscribers) {
  1188. subscribers = subscribers.concat(this.subscribers[event]);
  1189. }
  1190. if ('*' in this.subscribers) {
  1191. subscribers = subscribers.concat(this.subscribers['*']);
  1192. }
  1193. for (var i = 0; i < subscribers.length; i++) {
  1194. var subscriber = subscribers[i];
  1195. if (subscriber.callback) {
  1196. subscriber.callback(event, params, senderId || null);
  1197. }
  1198. }
  1199. };
  1200. /**
  1201. * Add data.
  1202. * Adding an item will fail when there already is an item with the same id.
  1203. * @param {Object | Array | DataTable} data
  1204. * @param {String} [senderId] Optional sender id
  1205. * @return {Array} addedIds Array with the ids of the added items
  1206. */
  1207. DataSet.prototype.add = function (data, senderId) {
  1208. var addedIds = [],
  1209. id,
  1210. me = this;
  1211. if (data instanceof Array) {
  1212. // Array
  1213. for (var i = 0, len = data.length; i < len; i++) {
  1214. id = me._addItem(data[i]);
  1215. addedIds.push(id);
  1216. }
  1217. }
  1218. else if (util.isDataTable(data)) {
  1219. // Google DataTable
  1220. var columns = this._getColumnNames(data);
  1221. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1222. var item = {};
  1223. for (var col = 0, cols = columns.length; col < cols; col++) {
  1224. var field = columns[col];
  1225. item[field] = data.getValue(row, col);
  1226. }
  1227. id = me._addItem(item);
  1228. addedIds.push(id);
  1229. }
  1230. }
  1231. else if (data instanceof Object) {
  1232. // Single item
  1233. id = me._addItem(data);
  1234. addedIds.push(id);
  1235. }
  1236. else {
  1237. throw new Error('Unknown dataType');
  1238. }
  1239. if (addedIds.length) {
  1240. this._trigger('add', {items: addedIds}, senderId);
  1241. }
  1242. return addedIds;
  1243. };
  1244. /**
  1245. * Update existing items. When an item does not exist, it will be created
  1246. * @param {Object | Array | DataTable} data
  1247. * @param {String} [senderId] Optional sender id
  1248. * @return {Array} updatedIds The ids of the added or updated items
  1249. */
  1250. DataSet.prototype.update = function (data, senderId) {
  1251. var addedIds = [],
  1252. updatedIds = [],
  1253. me = this,
  1254. fieldId = me.fieldId;
  1255. var addOrUpdate = function (item) {
  1256. var id = item[fieldId];
  1257. if (me.data[id]) {
  1258. // update item
  1259. id = me._updateItem(item);
  1260. updatedIds.push(id);
  1261. }
  1262. else {
  1263. // add new item
  1264. id = me._addItem(item);
  1265. addedIds.push(id);
  1266. }
  1267. };
  1268. if (data instanceof Array) {
  1269. // Array
  1270. for (var i = 0, len = data.length; i < len; i++) {
  1271. addOrUpdate(data[i]);
  1272. }
  1273. }
  1274. else if (util.isDataTable(data)) {
  1275. // Google DataTable
  1276. var columns = this._getColumnNames(data);
  1277. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1278. var item = {};
  1279. for (var col = 0, cols = columns.length; col < cols; col++) {
  1280. var field = columns[col];
  1281. item[field] = data.getValue(row, col);
  1282. }
  1283. addOrUpdate(item);
  1284. }
  1285. }
  1286. else if (data instanceof Object) {
  1287. // Single item
  1288. addOrUpdate(data);
  1289. }
  1290. else {
  1291. throw new Error('Unknown dataType');
  1292. }
  1293. if (addedIds.length) {
  1294. this._trigger('add', {items: addedIds}, senderId);
  1295. }
  1296. if (updatedIds.length) {
  1297. this._trigger('update', {items: updatedIds}, senderId);
  1298. }
  1299. return addedIds.concat(updatedIds);
  1300. };
  1301. /**
  1302. * Get a data item or multiple items.
  1303. *
  1304. * Usage:
  1305. *
  1306. * get()
  1307. * get(options: Object)
  1308. * get(options: Object, data: Array | DataTable)
  1309. *
  1310. * get(id: Number | String)
  1311. * get(id: Number | String, options: Object)
  1312. * get(id: Number | String, options: Object, data: Array | DataTable)
  1313. *
  1314. * get(ids: Number[] | String[])
  1315. * get(ids: Number[] | String[], options: Object)
  1316. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1317. *
  1318. * Where:
  1319. *
  1320. * {Number | String} id The id of an item
  1321. * {Number[] | String{}} ids An array with ids of items
  1322. * {Object} options An Object with options. Available options:
  1323. * {String} [type] Type of data to be returned. Can
  1324. * be 'DataTable' or 'Array' (default)
  1325. * {Object.<String, String>} [convert]
  1326. * {String[]} [fields] field names to be returned
  1327. * {function} [filter] filter items
  1328. * {String | function} [order] Order the items by
  1329. * a field name or custom sort function.
  1330. * {Array | DataTable} [data] If provided, items will be appended to this
  1331. * array or table. Required in case of Google
  1332. * DataTable.
  1333. *
  1334. * @throws Error
  1335. */
  1336. DataSet.prototype.get = function (args) {
  1337. var me = this;
  1338. var globalShowInternalIds = this.showInternalIds;
  1339. // parse the arguments
  1340. var id, ids, options, data;
  1341. var firstType = util.getType(arguments[0]);
  1342. if (firstType == 'String' || firstType == 'Number') {
  1343. // get(id [, options] [, data])
  1344. id = arguments[0];
  1345. options = arguments[1];
  1346. data = arguments[2];
  1347. }
  1348. else if (firstType == 'Array') {
  1349. // get(ids [, options] [, data])
  1350. ids = arguments[0];
  1351. options = arguments[1];
  1352. data = arguments[2];
  1353. }
  1354. else {
  1355. // get([, options] [, data])
  1356. options = arguments[0];
  1357. data = arguments[1];
  1358. }
  1359. // determine the return type
  1360. var type;
  1361. if (options && options.type) {
  1362. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1363. if (data && (type != util.getType(data))) {
  1364. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1365. 'does not correspond with specified options.type (' + options.type + ')');
  1366. }
  1367. if (type == 'DataTable' && !util.isDataTable(data)) {
  1368. throw new Error('Parameter "data" must be a DataTable ' +
  1369. 'when options.type is "DataTable"');
  1370. }
  1371. }
  1372. else if (data) {
  1373. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1374. }
  1375. else {
  1376. type = 'Array';
  1377. }
  1378. // we allow the setting of this value for a single get request.
  1379. if (options != undefined) {
  1380. if (options.showInternalIds != undefined) {
  1381. this.showInternalIds = options.showInternalIds;
  1382. }
  1383. }
  1384. // build options
  1385. var convert = options && options.convert || this.options.convert;
  1386. var filter = options && options.filter;
  1387. var items = [], item, itemId, i, len;
  1388. // convert items
  1389. if (id != undefined) {
  1390. // return a single item
  1391. item = me._getItem(id, convert);
  1392. if (filter && !filter(item)) {
  1393. item = null;
  1394. }
  1395. }
  1396. else if (ids != undefined) {
  1397. // return a subset of items
  1398. for (i = 0, len = ids.length; i < len; i++) {
  1399. item = me._getItem(ids[i], convert);
  1400. if (!filter || filter(item)) {
  1401. items.push(item);
  1402. }
  1403. }
  1404. }
  1405. else {
  1406. // return all items
  1407. for (itemId in this.data) {
  1408. if (this.data.hasOwnProperty(itemId)) {
  1409. item = me._getItem(itemId, convert);
  1410. if (!filter || filter(item)) {
  1411. items.push(item);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. // restore the global value of showInternalIds
  1417. this.showInternalIds = globalShowInternalIds;
  1418. // order the results
  1419. if (options && options.order && id == undefined) {
  1420. this._sort(items, options.order);
  1421. }
  1422. // filter fields of the items
  1423. if (options && options.fields) {
  1424. var fields = options.fields;
  1425. if (id != undefined) {
  1426. item = this._filterFields(item, fields);
  1427. }
  1428. else {
  1429. for (i = 0, len = items.length; i < len; i++) {
  1430. items[i] = this._filterFields(items[i], fields);
  1431. }
  1432. }
  1433. }
  1434. // return the results
  1435. if (type == 'DataTable') {
  1436. var columns = this._getColumnNames(data);
  1437. if (id != undefined) {
  1438. // append a single item to the data table
  1439. me._appendRow(data, columns, item);
  1440. }
  1441. else {
  1442. // copy the items to the provided data table
  1443. for (i = 0, len = items.length; i < len; i++) {
  1444. me._appendRow(data, columns, items[i]);
  1445. }
  1446. }
  1447. return data;
  1448. }
  1449. else {
  1450. // return an array
  1451. if (id != undefined) {
  1452. // a single item
  1453. return item;
  1454. }
  1455. else {
  1456. // multiple items
  1457. if (data) {
  1458. // copy the items to the provided array
  1459. for (i = 0, len = items.length; i < len; i++) {
  1460. data.push(items[i]);
  1461. }
  1462. return data;
  1463. }
  1464. else {
  1465. // just return our array
  1466. return items;
  1467. }
  1468. }
  1469. }
  1470. };
  1471. /**
  1472. * Get ids of all items or from a filtered set of items.
  1473. * @param {Object} [options] An Object with options. Available options:
  1474. * {function} [filter] filter items
  1475. * {String | function} [order] Order the items by
  1476. * a field name or custom sort function.
  1477. * @return {Array} ids
  1478. */
  1479. DataSet.prototype.getIds = function (options) {
  1480. var data = this.data,
  1481. filter = options && options.filter,
  1482. order = options && options.order,
  1483. convert = options && options.convert || this.options.convert,
  1484. i,
  1485. len,
  1486. id,
  1487. item,
  1488. items,
  1489. ids = [];
  1490. if (filter) {
  1491. // get filtered items
  1492. if (order) {
  1493. // create ordered list
  1494. items = [];
  1495. for (id in data) {
  1496. if (data.hasOwnProperty(id)) {
  1497. item = this._getItem(id, convert);
  1498. if (filter(item)) {
  1499. items.push(item);
  1500. }
  1501. }
  1502. }
  1503. this._sort(items, order);
  1504. for (i = 0, len = items.length; i < len; i++) {
  1505. ids[i] = items[i][this.fieldId];
  1506. }
  1507. }
  1508. else {
  1509. // create unordered list
  1510. for (id in data) {
  1511. if (data.hasOwnProperty(id)) {
  1512. item = this._getItem(id, convert);
  1513. if (filter(item)) {
  1514. ids.push(item[this.fieldId]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. }
  1520. else {
  1521. // get all items
  1522. if (order) {
  1523. // create an ordered list
  1524. items = [];
  1525. for (id in data) {
  1526. if (data.hasOwnProperty(id)) {
  1527. items.push(data[id]);
  1528. }
  1529. }
  1530. this._sort(items, order);
  1531. for (i = 0, len = items.length; i < len; i++) {
  1532. ids[i] = items[i][this.fieldId];
  1533. }
  1534. }
  1535. else {
  1536. // create unordered list
  1537. for (id in data) {
  1538. if (data.hasOwnProperty(id)) {
  1539. item = data[id];
  1540. ids.push(item[this.fieldId]);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. return ids;
  1546. };
  1547. /**
  1548. * Execute a callback function for every item in the dataset.
  1549. * The order of the items is not determined.
  1550. * @param {function} callback
  1551. * @param {Object} [options] Available options:
  1552. * {Object.<String, String>} [convert]
  1553. * {String[]} [fields] filter fields
  1554. * {function} [filter] filter items
  1555. * {String | function} [order] Order the items by
  1556. * a field name or custom sort function.
  1557. */
  1558. DataSet.prototype.forEach = function (callback, options) {
  1559. var filter = options && options.filter,
  1560. convert = options && options.convert || this.options.convert,
  1561. data = this.data,
  1562. item,
  1563. id;
  1564. if (options && options.order) {
  1565. // execute forEach on ordered list
  1566. var items = this.get(options);
  1567. for (var i = 0, len = items.length; i < len; i++) {
  1568. item = items[i];
  1569. id = item[this.fieldId];
  1570. callback(item, id);
  1571. }
  1572. }
  1573. else {
  1574. // unordered
  1575. for (id in data) {
  1576. if (data.hasOwnProperty(id)) {
  1577. item = this._getItem(id, convert);
  1578. if (!filter || filter(item)) {
  1579. callback(item, id);
  1580. }
  1581. }
  1582. }
  1583. }
  1584. };
  1585. /**
  1586. * Map every item in the dataset.
  1587. * @param {function} callback
  1588. * @param {Object} [options] Available options:
  1589. * {Object.<String, String>} [convert]
  1590. * {String[]} [fields] filter fields
  1591. * {function} [filter] filter items
  1592. * {String | function} [order] Order the items by
  1593. * a field name or custom sort function.
  1594. * @return {Object[]} mappedItems
  1595. */
  1596. DataSet.prototype.map = function (callback, options) {
  1597. var filter = options && options.filter,
  1598. convert = options && options.convert || this.options.convert,
  1599. mappedItems = [],
  1600. data = this.data,
  1601. item;
  1602. // convert and filter items
  1603. for (var id in data) {
  1604. if (data.hasOwnProperty(id)) {
  1605. item = this._getItem(id, convert);
  1606. if (!filter || filter(item)) {
  1607. mappedItems.push(callback(item, id));
  1608. }
  1609. }
  1610. }
  1611. // order items
  1612. if (options && options.order) {
  1613. this._sort(mappedItems, options.order);
  1614. }
  1615. return mappedItems;
  1616. };
  1617. /**
  1618. * Filter the fields of an item
  1619. * @param {Object} item
  1620. * @param {String[]} fields Field names
  1621. * @return {Object} filteredItem
  1622. * @private
  1623. */
  1624. DataSet.prototype._filterFields = function (item, fields) {
  1625. var filteredItem = {};
  1626. for (var field in item) {
  1627. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1628. filteredItem[field] = item[field];
  1629. }
  1630. }
  1631. return filteredItem;
  1632. };
  1633. /**
  1634. * Sort the provided array with items
  1635. * @param {Object[]} items
  1636. * @param {String | function} order A field name or custom sort function.
  1637. * @private
  1638. */
  1639. DataSet.prototype._sort = function (items, order) {
  1640. if (util.isString(order)) {
  1641. // order by provided field name
  1642. var name = order; // field name
  1643. items.sort(function (a, b) {
  1644. var av = a[name];
  1645. var bv = b[name];
  1646. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1647. });
  1648. }
  1649. else if (typeof order === 'function') {
  1650. // order by sort function
  1651. items.sort(order);
  1652. }
  1653. // TODO: extend order by an Object {field:String, direction:String}
  1654. // where direction can be 'asc' or 'desc'
  1655. else {
  1656. throw new TypeError('Order must be a function or a string');
  1657. }
  1658. };
  1659. /**
  1660. * Remove an object by pointer or by id
  1661. * @param {String | Number | Object | Array} id Object or id, or an array with
  1662. * objects or ids to be removed
  1663. * @param {String} [senderId] Optional sender id
  1664. * @return {Array} removedIds
  1665. */
  1666. DataSet.prototype.remove = function (id, senderId) {
  1667. var removedIds = [],
  1668. i, len, removedId;
  1669. if (id instanceof Array) {
  1670. for (i = 0, len = id.length; i < len; i++) {
  1671. removedId = this._remove(id[i]);
  1672. if (removedId != null) {
  1673. removedIds.push(removedId);
  1674. }
  1675. }
  1676. }
  1677. else {
  1678. removedId = this._remove(id);
  1679. if (removedId != null) {
  1680. removedIds.push(removedId);
  1681. }
  1682. }
  1683. if (removedIds.length) {
  1684. this._trigger('remove', {items: removedIds}, senderId);
  1685. }
  1686. return removedIds;
  1687. };
  1688. /**
  1689. * Remove an item by its id
  1690. * @param {Number | String | Object} id id or item
  1691. * @returns {Number | String | null} id
  1692. * @private
  1693. */
  1694. DataSet.prototype._remove = function (id) {
  1695. if (util.isNumber(id) || util.isString(id)) {
  1696. if (this.data[id]) {
  1697. delete this.data[id];
  1698. delete this.internalIds[id];
  1699. return id;
  1700. }
  1701. }
  1702. else if (id instanceof Object) {
  1703. var itemId = id[this.fieldId];
  1704. if (itemId && this.data[itemId]) {
  1705. delete this.data[itemId];
  1706. delete this.internalIds[itemId];
  1707. return itemId;
  1708. }
  1709. }
  1710. return null;
  1711. };
  1712. /**
  1713. * Clear the data
  1714. * @param {String} [senderId] Optional sender id
  1715. * @return {Array} removedIds The ids of all removed items
  1716. */
  1717. DataSet.prototype.clear = function (senderId) {
  1718. var ids = Object.keys(this.data);
  1719. this.data = {};
  1720. this.internalIds = {};
  1721. this._trigger('remove', {items: ids}, senderId);
  1722. return ids;
  1723. };
  1724. /**
  1725. * Find the item with maximum value of a specified field
  1726. * @param {String} field
  1727. * @return {Object | null} item Item containing max value, or null if no items
  1728. */
  1729. DataSet.prototype.max = function (field) {
  1730. var data = this.data,
  1731. max = null,
  1732. maxField = null;
  1733. for (var id in data) {
  1734. if (data.hasOwnProperty(id)) {
  1735. var item = data[id];
  1736. var itemField = item[field];
  1737. if (itemField != null && (!max || itemField > maxField)) {
  1738. max = item;
  1739. maxField = itemField;
  1740. }
  1741. }
  1742. }
  1743. return max;
  1744. };
  1745. /**
  1746. * Find the item with minimum value of a specified field
  1747. * @param {String} field
  1748. * @return {Object | null} item Item containing max value, or null if no items
  1749. */
  1750. DataSet.prototype.min = function (field) {
  1751. var data = this.data,
  1752. min = null,
  1753. minField = null;
  1754. for (var id in data) {
  1755. if (data.hasOwnProperty(id)) {
  1756. var item = data[id];
  1757. var itemField = item[field];
  1758. if (itemField != null && (!min || itemField < minField)) {
  1759. min = item;
  1760. minField = itemField;
  1761. }
  1762. }
  1763. }
  1764. return min;
  1765. };
  1766. /**
  1767. * Find all distinct values of a specified field
  1768. * @param {String} field
  1769. * @return {Array} values Array containing all distinct values. If the data
  1770. * items do not contain the specified field, an array
  1771. * containing a single value undefined is returned.
  1772. * The returned array is unordered.
  1773. */
  1774. DataSet.prototype.distinct = function (field) {
  1775. var data = this.data,
  1776. values = [],
  1777. fieldType = this.options.convert[field],
  1778. count = 0;
  1779. for (var prop in data) {
  1780. if (data.hasOwnProperty(prop)) {
  1781. var item = data[prop];
  1782. var value = util.convert(item[field], fieldType);
  1783. var exists = false;
  1784. for (var i = 0; i < count; i++) {
  1785. if (values[i] == value) {
  1786. exists = true;
  1787. break;
  1788. }
  1789. }
  1790. if (!exists) {
  1791. values[count] = value;
  1792. count++;
  1793. }
  1794. }
  1795. }
  1796. return values;
  1797. };
  1798. /**
  1799. * Add a single item. Will fail when an item with the same id already exists.
  1800. * @param {Object} item
  1801. * @return {String} id
  1802. * @private
  1803. */
  1804. DataSet.prototype._addItem = function (item) {
  1805. var id = item[this.fieldId];
  1806. if (id != undefined) {
  1807. // check whether this id is already taken
  1808. if (this.data[id]) {
  1809. // item already exists
  1810. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1811. }
  1812. }
  1813. else {
  1814. // generate an id
  1815. id = util.randomUUID();
  1816. item[this.fieldId] = id;
  1817. this.internalIds[id] = item;
  1818. }
  1819. var d = {};
  1820. for (var field in item) {
  1821. if (item.hasOwnProperty(field)) {
  1822. var fieldType = this.convert[field]; // type may be undefined
  1823. d[field] = util.convert(item[field], fieldType);
  1824. }
  1825. }
  1826. this.data[id] = d;
  1827. return id;
  1828. };
  1829. /**
  1830. * Get an item. Fields can be converted to a specific type
  1831. * @param {String} id
  1832. * @param {Object.<String, String>} [convert] field types to convert
  1833. * @return {Object | null} item
  1834. * @private
  1835. */
  1836. DataSet.prototype._getItem = function (id, convert) {
  1837. var field, value;
  1838. // get the item from the dataset
  1839. var raw = this.data[id];
  1840. if (!raw) {
  1841. return null;
  1842. }
  1843. // convert the items field types
  1844. var converted = {},
  1845. fieldId = this.fieldId,
  1846. internalIds = this.internalIds;
  1847. if (convert) {
  1848. for (field in raw) {
  1849. if (raw.hasOwnProperty(field)) {
  1850. value = raw[field];
  1851. // output all fields, except internal ids
  1852. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1853. converted[field] = util.convert(value, convert[field]);
  1854. }
  1855. }
  1856. }
  1857. }
  1858. else {
  1859. // no field types specified, no converting needed
  1860. for (field in raw) {
  1861. if (raw.hasOwnProperty(field)) {
  1862. value = raw[field];
  1863. // output all fields, except internal ids
  1864. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1865. converted[field] = value;
  1866. }
  1867. }
  1868. }
  1869. }
  1870. return converted;
  1871. };
  1872. /**
  1873. * Update a single item: merge with existing item.
  1874. * Will fail when the item has no id, or when there does not exist an item
  1875. * with the same id.
  1876. * @param {Object} item
  1877. * @return {String} id
  1878. * @private
  1879. */
  1880. DataSet.prototype._updateItem = function (item) {
  1881. var id = item[this.fieldId];
  1882. if (id == undefined) {
  1883. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1884. }
  1885. var d = this.data[id];
  1886. if (!d) {
  1887. // item doesn't exist
  1888. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1889. }
  1890. // merge with current item
  1891. for (var field in item) {
  1892. if (item.hasOwnProperty(field)) {
  1893. var fieldType = this.convert[field]; // type may be undefined
  1894. d[field] = util.convert(item[field], fieldType);
  1895. }
  1896. }
  1897. return id;
  1898. };
  1899. /**
  1900. * check if an id is an internal or external id
  1901. * @param id
  1902. * @returns {boolean}
  1903. * @private
  1904. */
  1905. DataSet.prototype.isInternalId = function(id) {
  1906. return (id in this.internalIds);
  1907. };
  1908. /**
  1909. * Get an array with the column names of a Google DataTable
  1910. * @param {DataTable} dataTable
  1911. * @return {String[]} columnNames
  1912. * @private
  1913. */
  1914. DataSet.prototype._getColumnNames = function (dataTable) {
  1915. var columns = [];
  1916. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1917. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1918. }
  1919. return columns;
  1920. };
  1921. /**
  1922. * Append an item as a row to the dataTable
  1923. * @param dataTable
  1924. * @param columns
  1925. * @param item
  1926. * @private
  1927. */
  1928. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1929. var row = dataTable.addRow();
  1930. for (var col = 0, cols = columns.length; col < cols; col++) {
  1931. var field = columns[col];
  1932. dataTable.setValue(row, col, item[field]);
  1933. }
  1934. };
  1935. /**
  1936. * DataView
  1937. *
  1938. * a dataview offers a filtered view on a dataset or an other dataview.
  1939. *
  1940. * @param {DataSet | DataView} data
  1941. * @param {Object} [options] Available options: see method get
  1942. *
  1943. * @constructor DataView
  1944. */
  1945. function DataView (data, options) {
  1946. this.id = util.randomUUID();
  1947. this.data = null;
  1948. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1949. this.options = options || {};
  1950. this.fieldId = 'id'; // name of the field containing id
  1951. this.subscribers = {}; // event subscribers
  1952. var me = this;
  1953. this.listener = function () {
  1954. me._onEvent.apply(me, arguments);
  1955. };
  1956. this.setData(data);
  1957. }
  1958. // TODO: implement a function .config() to dynamically update things like configured filter
  1959. // and trigger changes accordingly
  1960. /**
  1961. * Set a data source for the view
  1962. * @param {DataSet | DataView} data
  1963. */
  1964. DataView.prototype.setData = function (data) {
  1965. var ids, dataItems, i, len;
  1966. if (this.data) {
  1967. // unsubscribe from current dataset
  1968. if (this.data.unsubscribe) {
  1969. this.data.unsubscribe('*', this.listener);
  1970. }
  1971. // trigger a remove of all items in memory
  1972. ids = [];
  1973. for (var id in this.ids) {
  1974. if (this.ids.hasOwnProperty(id)) {
  1975. ids.push(id);
  1976. }
  1977. }
  1978. this.ids = {};
  1979. this._trigger('remove', {items: ids});
  1980. }
  1981. this.data = data;
  1982. if (this.data) {
  1983. // update fieldId
  1984. this.fieldId = this.options.fieldId ||
  1985. (this.data && this.data.options && this.data.options.fieldId) ||
  1986. 'id';
  1987. // trigger an add of all added items
  1988. ids = this.data.getIds({filter: this.options && this.options.filter});
  1989. for (i = 0, len = ids.length; i < len; i++) {
  1990. id = ids[i];
  1991. this.ids[id] = true;
  1992. }
  1993. this._trigger('add', {items: ids});
  1994. // subscribe to new dataset
  1995. if (this.data.on) {
  1996. this.data.on('*', this.listener);
  1997. }
  1998. }
  1999. };
  2000. /**
  2001. * Get data from the data view
  2002. *
  2003. * Usage:
  2004. *
  2005. * get()
  2006. * get(options: Object)
  2007. * get(options: Object, data: Array | DataTable)
  2008. *
  2009. * get(id: Number)
  2010. * get(id: Number, options: Object)
  2011. * get(id: Number, options: Object, data: Array | DataTable)
  2012. *
  2013. * get(ids: Number[])
  2014. * get(ids: Number[], options: Object)
  2015. * get(ids: Number[], options: Object, data: Array | DataTable)
  2016. *
  2017. * Where:
  2018. *
  2019. * {Number | String} id The id of an item
  2020. * {Number[] | String{}} ids An array with ids of items
  2021. * {Object} options An Object with options. Available options:
  2022. * {String} [type] Type of data to be returned. Can
  2023. * be 'DataTable' or 'Array' (default)
  2024. * {Object.<String, String>} [convert]
  2025. * {String[]} [fields] field names to be returned
  2026. * {function} [filter] filter items
  2027. * {String | function} [order] Order the items by
  2028. * a field name or custom sort function.
  2029. * {Array | DataTable} [data] If provided, items will be appended to this
  2030. * array or table. Required in case of Google
  2031. * DataTable.
  2032. * @param args
  2033. */
  2034. DataView.prototype.get = function (args) {
  2035. var me = this;
  2036. // parse the arguments
  2037. var ids, options, data;
  2038. var firstType = util.getType(arguments[0]);
  2039. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2040. // get(id(s) [, options] [, data])
  2041. ids = arguments[0]; // can be a single id or an array with ids
  2042. options = arguments[1];
  2043. data = arguments[2];
  2044. }
  2045. else {
  2046. // get([, options] [, data])
  2047. options = arguments[0];
  2048. data = arguments[1];
  2049. }
  2050. // extend the options with the default options and provided options
  2051. var viewOptions = util.extend({}, this.options, options);
  2052. // create a combined filter method when needed
  2053. if (this.options.filter && options && options.filter) {
  2054. viewOptions.filter = function (item) {
  2055. return me.options.filter(item) && options.filter(item);
  2056. }
  2057. }
  2058. // build up the call to the linked data set
  2059. var getArguments = [];
  2060. if (ids != undefined) {
  2061. getArguments.push(ids);
  2062. }
  2063. getArguments.push(viewOptions);
  2064. getArguments.push(data);
  2065. return this.data && this.data.get.apply(this.data, getArguments);
  2066. };
  2067. /**
  2068. * Get ids of all items or from a filtered set of items.
  2069. * @param {Object} [options] An Object with options. Available options:
  2070. * {function} [filter] filter items
  2071. * {String | function} [order] Order the items by
  2072. * a field name or custom sort function.
  2073. * @return {Array} ids
  2074. */
  2075. DataView.prototype.getIds = function (options) {
  2076. var ids;
  2077. if (this.data) {
  2078. var defaultFilter = this.options.filter;
  2079. var filter;
  2080. if (options && options.filter) {
  2081. if (defaultFilter) {
  2082. filter = function (item) {
  2083. return defaultFilter(item) && options.filter(item);
  2084. }
  2085. }
  2086. else {
  2087. filter = options.filter;
  2088. }
  2089. }
  2090. else {
  2091. filter = defaultFilter;
  2092. }
  2093. ids = this.data.getIds({
  2094. filter: filter,
  2095. order: options && options.order
  2096. });
  2097. }
  2098. else {
  2099. ids = [];
  2100. }
  2101. return ids;
  2102. };
  2103. /**
  2104. * Event listener. Will propagate all events from the connected data set to
  2105. * the subscribers of the DataView, but will filter the items and only trigger
  2106. * when there are changes in the filtered data set.
  2107. * @param {String} event
  2108. * @param {Object | null} params
  2109. * @param {String} senderId
  2110. * @private
  2111. */
  2112. DataView.prototype._onEvent = function (event, params, senderId) {
  2113. var i, len, id, item,
  2114. ids = params && params.items,
  2115. data = this.data,
  2116. added = [],
  2117. updated = [],
  2118. removed = [];
  2119. if (ids && data) {
  2120. switch (event) {
  2121. case 'add':
  2122. // filter the ids of the added items
  2123. for (i = 0, len = ids.length; i < len; i++) {
  2124. id = ids[i];
  2125. item = this.get(id);
  2126. if (item) {
  2127. this.ids[id] = true;
  2128. added.push(id);
  2129. }
  2130. }
  2131. break;
  2132. case 'update':
  2133. // determine the event from the views viewpoint: an updated
  2134. // item can be added, updated, or removed from this view.
  2135. for (i = 0, len = ids.length; i < len; i++) {
  2136. id = ids[i];
  2137. item = this.get(id);
  2138. if (item) {
  2139. if (this.ids[id]) {
  2140. updated.push(id);
  2141. }
  2142. else {
  2143. this.ids[id] = true;
  2144. added.push(id);
  2145. }
  2146. }
  2147. else {
  2148. if (this.ids[id]) {
  2149. delete this.ids[id];
  2150. removed.push(id);
  2151. }
  2152. else {
  2153. // nothing interesting for me :-(
  2154. }
  2155. }
  2156. }
  2157. break;
  2158. case 'remove':
  2159. // filter the ids of the removed items
  2160. for (i = 0, len = ids.length; i < len; i++) {
  2161. id = ids[i];
  2162. if (this.ids[id]) {
  2163. delete this.ids[id];
  2164. removed.push(id);
  2165. }
  2166. }
  2167. break;
  2168. }
  2169. if (added.length) {
  2170. this._trigger('add', {items: added}, senderId);
  2171. }
  2172. if (updated.length) {
  2173. this._trigger('update', {items: updated}, senderId);
  2174. }
  2175. if (removed.length) {
  2176. this._trigger('remove', {items: removed}, senderId);
  2177. }
  2178. }
  2179. };
  2180. // copy subscription functionality from DataSet
  2181. DataView.prototype.on = DataSet.prototype.on;
  2182. DataView.prototype.off = DataSet.prototype.off;
  2183. DataView.prototype._trigger = DataSet.prototype._trigger;
  2184. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2185. DataView.prototype.subscribe = DataView.prototype.on;
  2186. DataView.prototype.unsubscribe = DataView.prototype.off;
  2187. /**
  2188. * @constructor TimeStep
  2189. * The class TimeStep is an iterator for dates. You provide a start date and an
  2190. * end date. The class itself determines the best scale (step size) based on the
  2191. * provided start Date, end Date, and minimumStep.
  2192. *
  2193. * If minimumStep is provided, the step size is chosen as close as possible
  2194. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2195. * provided, the scale is set to 1 DAY.
  2196. * The minimumStep should correspond with the onscreen size of about 6 characters
  2197. *
  2198. * Alternatively, you can set a scale by hand.
  2199. * After creation, you can initialize the class by executing first(). Then you
  2200. * can iterate from the start date to the end date via next(). You can check if
  2201. * the end date is reached with the function hasNext(). After each step, you can
  2202. * retrieve the current date via getCurrent().
  2203. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2204. * days, to years.
  2205. *
  2206. * Version: 1.2
  2207. *
  2208. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2209. * or new Date(2010, 9, 21, 23, 45, 00)
  2210. * @param {Date} [end] The end date
  2211. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2212. */
  2213. TimeStep = function(start, end, minimumStep) {
  2214. // variables
  2215. this.current = new Date();
  2216. this._start = new Date();
  2217. this._end = new Date();
  2218. this.autoScale = true;
  2219. this.scale = TimeStep.SCALE.DAY;
  2220. this.step = 1;
  2221. // initialize the range
  2222. this.setRange(start, end, minimumStep);
  2223. };
  2224. /// enum scale
  2225. TimeStep.SCALE = {
  2226. MILLISECOND: 1,
  2227. SECOND: 2,
  2228. MINUTE: 3,
  2229. HOUR: 4,
  2230. DAY: 5,
  2231. WEEKDAY: 6,
  2232. MONTH: 7,
  2233. YEAR: 8
  2234. };
  2235. /**
  2236. * Set a new range
  2237. * If minimumStep is provided, the step size is chosen as close as possible
  2238. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2239. * provided, the scale is set to 1 DAY.
  2240. * The minimumStep should correspond with the onscreen size of about 6 characters
  2241. * @param {Date} [start] The start date and time.
  2242. * @param {Date} [end] The end date and time.
  2243. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2244. */
  2245. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2246. if (!(start instanceof Date) || !(end instanceof Date)) {
  2247. throw "No legal start or end date in method setRange";
  2248. }
  2249. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2250. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2251. if (this.autoScale) {
  2252. this.setMinimumStep(minimumStep);
  2253. }
  2254. };
  2255. /**
  2256. * Set the range iterator to the start date.
  2257. */
  2258. TimeStep.prototype.first = function() {
  2259. this.current = new Date(this._start.valueOf());
  2260. this.roundToMinor();
  2261. };
  2262. /**
  2263. * Round the current date to the first minor date value
  2264. * This must be executed once when the current date is set to start Date
  2265. */
  2266. TimeStep.prototype.roundToMinor = function() {
  2267. // round to floor
  2268. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2269. //noinspection FallthroughInSwitchStatementJS
  2270. switch (this.scale) {
  2271. case TimeStep.SCALE.YEAR:
  2272. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2273. this.current.setMonth(0);
  2274. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2275. case TimeStep.SCALE.DAY: // intentional fall through
  2276. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2277. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2278. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2279. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2280. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2281. }
  2282. if (this.step != 1) {
  2283. // round down to the first minor value that is a multiple of the current step size
  2284. switch (this.scale) {
  2285. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2286. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2287. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2288. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2289. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2290. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2291. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2292. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2293. default: break;
  2294. }
  2295. }
  2296. };
  2297. /**
  2298. * Check if the there is a next step
  2299. * @return {boolean} true if the current date has not passed the end date
  2300. */
  2301. TimeStep.prototype.hasNext = function () {
  2302. return (this.current.valueOf() <= this._end.valueOf());
  2303. };
  2304. /**
  2305. * Do the next step
  2306. */
  2307. TimeStep.prototype.next = function() {
  2308. var prev = this.current.valueOf();
  2309. // Two cases, needed to prevent issues with switching daylight savings
  2310. // (end of March and end of October)
  2311. if (this.current.getMonth() < 6) {
  2312. switch (this.scale) {
  2313. case TimeStep.SCALE.MILLISECOND:
  2314. this.current = new Date(this.current.valueOf() + this.step); break;
  2315. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2316. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2317. case TimeStep.SCALE.HOUR:
  2318. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2319. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2320. var h = this.current.getHours();
  2321. this.current.setHours(h - (h % this.step));
  2322. break;
  2323. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2324. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2325. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2326. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2327. default: break;
  2328. }
  2329. }
  2330. else {
  2331. switch (this.scale) {
  2332. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2333. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2334. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2335. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2336. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2337. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2338. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2339. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2340. default: break;
  2341. }
  2342. }
  2343. if (this.step != 1) {
  2344. // round down to the correct major value
  2345. switch (this.scale) {
  2346. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2347. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2348. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2349. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2350. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2351. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2352. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2353. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2354. default: break;
  2355. }
  2356. }
  2357. // safety mechanism: if current time is still unchanged, move to the end
  2358. if (this.current.valueOf() == prev) {
  2359. this.current = new Date(this._end.valueOf());
  2360. }
  2361. };
  2362. /**
  2363. * Get the current datetime
  2364. * @return {Date} current The current date
  2365. */
  2366. TimeStep.prototype.getCurrent = function() {
  2367. return this.current;
  2368. };
  2369. /**
  2370. * Set a custom scale. Autoscaling will be disabled.
  2371. * For example setScale(SCALE.MINUTES, 5) will result
  2372. * in minor steps of 5 minutes, and major steps of an hour.
  2373. *
  2374. * @param {TimeStep.SCALE} newScale
  2375. * A scale. Choose from SCALE.MILLISECOND,
  2376. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2377. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2378. * SCALE.YEAR.
  2379. * @param {Number} newStep A step size, by default 1. Choose for
  2380. * example 1, 2, 5, or 10.
  2381. */
  2382. TimeStep.prototype.setScale = function(newScale, newStep) {
  2383. this.scale = newScale;
  2384. if (newStep > 0) {
  2385. this.step = newStep;
  2386. }
  2387. this.autoScale = false;
  2388. };
  2389. /**
  2390. * Enable or disable autoscaling
  2391. * @param {boolean} enable If true, autoascaling is set true
  2392. */
  2393. TimeStep.prototype.setAutoScale = function (enable) {
  2394. this.autoScale = enable;
  2395. };
  2396. /**
  2397. * Automatically determine the scale that bests fits the provided minimum step
  2398. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2399. */
  2400. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2401. if (minimumStep == undefined) {
  2402. return;
  2403. }
  2404. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2405. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2406. var stepDay = (1000 * 60 * 60 * 24);
  2407. var stepHour = (1000 * 60 * 60);
  2408. var stepMinute = (1000 * 60);
  2409. var stepSecond = (1000);
  2410. var stepMillisecond= (1);
  2411. // find the smallest step that is larger than the provided minimumStep
  2412. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2413. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2414. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2415. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2416. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2417. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2418. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2419. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2420. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2421. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2422. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2423. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2424. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2425. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2426. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2427. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2428. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2429. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2430. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2431. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2432. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2433. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2434. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2435. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2436. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2437. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2438. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2439. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2440. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2441. };
  2442. /**
  2443. * Snap a date to a rounded value.
  2444. * The snap intervals are dependent on the current scale and step.
  2445. * @param {Date} date the date to be snapped.
  2446. * @return {Date} snappedDate
  2447. */
  2448. TimeStep.prototype.snap = function(date) {
  2449. var clone = new Date(date.valueOf());
  2450. if (this.scale == TimeStep.SCALE.YEAR) {
  2451. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2452. clone.setFullYear(Math.round(year / this.step) * this.step);
  2453. clone.setMonth(0);
  2454. clone.setDate(0);
  2455. clone.setHours(0);
  2456. clone.setMinutes(0);
  2457. clone.setSeconds(0);
  2458. clone.setMilliseconds(0);
  2459. }
  2460. else if (this.scale == TimeStep.SCALE.MONTH) {
  2461. if (clone.getDate() > 15) {
  2462. clone.setDate(1);
  2463. clone.setMonth(clone.getMonth() + 1);
  2464. // important: first set Date to 1, after that change the month.
  2465. }
  2466. else {
  2467. clone.setDate(1);
  2468. }
  2469. clone.setHours(0);
  2470. clone.setMinutes(0);
  2471. clone.setSeconds(0);
  2472. clone.setMilliseconds(0);
  2473. }
  2474. else if (this.scale == TimeStep.SCALE.DAY ||
  2475. this.scale == TimeStep.SCALE.WEEKDAY) {
  2476. //noinspection FallthroughInSwitchStatementJS
  2477. switch (this.step) {
  2478. case 5:
  2479. case 2:
  2480. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2481. default:
  2482. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2483. }
  2484. clone.setMinutes(0);
  2485. clone.setSeconds(0);
  2486. clone.setMilliseconds(0);
  2487. }
  2488. else if (this.scale == TimeStep.SCALE.HOUR) {
  2489. switch (this.step) {
  2490. case 4:
  2491. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2492. default:
  2493. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2494. }
  2495. clone.setSeconds(0);
  2496. clone.setMilliseconds(0);
  2497. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2498. //noinspection FallthroughInSwitchStatementJS
  2499. switch (this.step) {
  2500. case 15:
  2501. case 10:
  2502. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2503. clone.setSeconds(0);
  2504. break;
  2505. case 5:
  2506. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2507. default:
  2508. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2509. }
  2510. clone.setMilliseconds(0);
  2511. }
  2512. else if (this.scale == TimeStep.SCALE.SECOND) {
  2513. //noinspection FallthroughInSwitchStatementJS
  2514. switch (this.step) {
  2515. case 15:
  2516. case 10:
  2517. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2518. clone.setMilliseconds(0);
  2519. break;
  2520. case 5:
  2521. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2522. default:
  2523. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2524. }
  2525. }
  2526. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2527. var step = this.step > 5 ? this.step / 2 : 1;
  2528. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2529. }
  2530. return clone;
  2531. };
  2532. /**
  2533. * Check if the current value is a major value (for example when the step
  2534. * is DAY, a major value is each first day of the MONTH)
  2535. * @return {boolean} true if current date is major, else false.
  2536. */
  2537. TimeStep.prototype.isMajor = function() {
  2538. switch (this.scale) {
  2539. case TimeStep.SCALE.MILLISECOND:
  2540. return (this.current.getMilliseconds() == 0);
  2541. case TimeStep.SCALE.SECOND:
  2542. return (this.current.getSeconds() == 0);
  2543. case TimeStep.SCALE.MINUTE:
  2544. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2545. // Note: this is no bug. Major label is equal for both minute and hour scale
  2546. case TimeStep.SCALE.HOUR:
  2547. return (this.current.getHours() == 0);
  2548. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2549. case TimeStep.SCALE.DAY:
  2550. return (this.current.getDate() == 1);
  2551. case TimeStep.SCALE.MONTH:
  2552. return (this.current.getMonth() == 0);
  2553. case TimeStep.SCALE.YEAR:
  2554. return false;
  2555. default:
  2556. return false;
  2557. }
  2558. };
  2559. /**
  2560. * Returns formatted text for the minor axislabel, depending on the current
  2561. * date and the scale. For example when scale is MINUTE, the current time is
  2562. * formatted as "hh:mm".
  2563. * @param {Date} [date] custom date. if not provided, current date is taken
  2564. */
  2565. TimeStep.prototype.getLabelMinor = function(date) {
  2566. if (date == undefined) {
  2567. date = this.current;
  2568. }
  2569. switch (this.scale) {
  2570. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2571. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2572. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2573. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2574. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2575. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2576. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2577. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2578. default: return '';
  2579. }
  2580. };
  2581. /**
  2582. * Returns formatted text for the major axis label, depending on the current
  2583. * date and the scale. For example when scale is MINUTE, the major scale is
  2584. * hours, and the hour will be formatted as "hh".
  2585. * @param {Date} [date] custom date. if not provided, current date is taken
  2586. */
  2587. TimeStep.prototype.getLabelMajor = function(date) {
  2588. if (date == undefined) {
  2589. date = this.current;
  2590. }
  2591. //noinspection FallthroughInSwitchStatementJS
  2592. switch (this.scale) {
  2593. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2594. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2595. case TimeStep.SCALE.MINUTE:
  2596. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2597. case TimeStep.SCALE.WEEKDAY:
  2598. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2599. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2600. case TimeStep.SCALE.YEAR: return '';
  2601. default: return '';
  2602. }
  2603. };
  2604. // TODO: turn Stack into a Mixin?
  2605. /**
  2606. * @constructor Stack
  2607. * Stacks items on top of each other.
  2608. * @param {Object} [options]
  2609. */
  2610. function Stack (options) {
  2611. this.options = options || {};
  2612. this.defaultOptions = {
  2613. order: function (a, b) {
  2614. // Order: ranges over non-ranges, ranged ordered by width,
  2615. // and non-ranges ordered by start.
  2616. if (a instanceof ItemRange) {
  2617. if (b instanceof ItemRange) {
  2618. var aInt = (a.data.end - a.data.start);
  2619. var bInt = (b.data.end - b.data.start);
  2620. return (aInt - bInt) || (a.data.start - b.data.start);
  2621. }
  2622. else {
  2623. return -1;
  2624. }
  2625. }
  2626. else {
  2627. if (b instanceof ItemRange) {
  2628. return 1;
  2629. }
  2630. else {
  2631. return (a.data.start - b.data.start);
  2632. }
  2633. }
  2634. },
  2635. margin: {
  2636. item: 10,
  2637. axis: 20
  2638. }
  2639. };
  2640. }
  2641. /**
  2642. * Set options for the stack
  2643. * @param {Object} options Available options:
  2644. * {Number} [margin.item=10]
  2645. * {Number} [margin.axis=20]
  2646. * {function} [order] Stacking order
  2647. */
  2648. Stack.prototype.setOptions = function setOptions (options) {
  2649. util.extend(this.options, options);
  2650. };
  2651. /**
  2652. * Order an array with items using a predefined order function for items
  2653. * @param {Item[]} items
  2654. */
  2655. Stack.prototype.order = function order(items) {
  2656. //order the items
  2657. var order = this.options.order || this.defaultOptions.order;
  2658. if (!(typeof order === 'function')) {
  2659. throw new Error('Option order must be a function');
  2660. }
  2661. items.sort(order);
  2662. };
  2663. /**
  2664. * Order items by their start data
  2665. * @param {Item[]} items
  2666. */
  2667. Stack.prototype.orderByStart = function orderByStart(items) {
  2668. items.sort(function (a, b) {
  2669. return a.data.start - b.data.start;
  2670. });
  2671. };
  2672. /**
  2673. * Order items by their end date. If they have no end date, their start date
  2674. * is used.
  2675. * @param {Item[]} items
  2676. */
  2677. Stack.prototype.orderByEnd = function orderByEnd(items) {
  2678. items.sort(function (a, b) {
  2679. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2680. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2681. return aTime - bTime;
  2682. });
  2683. };
  2684. /**
  2685. * Adjust vertical positions of the events such that they don't overlap each
  2686. * other.
  2687. * @param {Item[]} items All visible items
  2688. * @param {boolean} [force=false] If true, all items will be re-stacked.
  2689. * If false (default), only items having a
  2690. * top===null will be re-stacked
  2691. * @private
  2692. */
  2693. Stack.prototype.stack = function stack (items, force) {
  2694. var i,
  2695. iMax,
  2696. options = this.options,
  2697. marginItem,
  2698. marginAxis;
  2699. if (options.margin && options.margin.item !== undefined) {
  2700. marginItem = options.margin.item;
  2701. }
  2702. else {
  2703. marginItem = this.defaultOptions.margin.item
  2704. }
  2705. if (options.margin && options.margin.axis !== undefined) {
  2706. marginAxis = options.margin.axis;
  2707. }
  2708. else {
  2709. marginAxis = this.defaultOptions.margin.axis
  2710. }
  2711. if (force) {
  2712. // reset top position of all items
  2713. for (i = 0, iMax = items.length; i < iMax; i++) {
  2714. items[i].top = null;
  2715. }
  2716. }
  2717. // calculate new, non-overlapping positions
  2718. for (i = 0, iMax = items.length; i < iMax; i++) {
  2719. var item = items[i];
  2720. if (item.top === null) {
  2721. // initialize top position
  2722. item.top = marginAxis;
  2723. do {
  2724. // TODO: optimize checking for overlap. when there is a gap without items,
  2725. // you only need to check for items from the next item on, not from zero
  2726. var collidingItem = null;
  2727. for (var j = 0, jj = items.length; j < jj; j++) {
  2728. var other = items[j];
  2729. if (other.top !== null && other !== item && this.collision(item, other, marginItem)) {
  2730. collidingItem = other;
  2731. break;
  2732. }
  2733. }
  2734. if (collidingItem != null) {
  2735. // There is a collision. Reposition the event above the colliding element
  2736. item.top = collidingItem.top + collidingItem.height + marginItem;
  2737. }
  2738. } while (collidingItem);
  2739. }
  2740. }
  2741. };
  2742. /**
  2743. * Test if the two provided items collide
  2744. * The items must have parameters left, width, top, and height.
  2745. * @param {Component} a The first item
  2746. * @param {Component} b The second item
  2747. * @param {Number} margin A minimum required margin.
  2748. * If margin is provided, the two items will be
  2749. * marked colliding when they overlap or
  2750. * when the margin between the two is smaller than
  2751. * the requested margin.
  2752. * @return {boolean} true if a and b collide, else false
  2753. */
  2754. Stack.prototype.collision = function collision (a, b, margin) {
  2755. return ((a.left - margin) < (b.left + b.width) &&
  2756. (a.left + a.width + margin) > b.left &&
  2757. (a.top - margin) < (b.top + b.height) &&
  2758. (a.top + a.height + margin) > b.top);
  2759. };
  2760. /**
  2761. * @constructor Range
  2762. * A Range controls a numeric range with a start and end value.
  2763. * The Range adjusts the range based on mouse events or programmatic changes,
  2764. * and triggers events when the range is changing or has been changed.
  2765. * @param {RootPanel} root Root panel, used to subscribe to events
  2766. * @param {Panel} parent Parent panel, used to attach to the DOM
  2767. * @param {Object} [options] See description at Range.setOptions
  2768. */
  2769. function Range(root, parent, options) {
  2770. this.id = util.randomUUID();
  2771. this.start = null; // Number
  2772. this.end = null; // Number
  2773. this.root = root;
  2774. this.parent = parent;
  2775. this.options = options || {};
  2776. // drag listeners for dragging
  2777. this.root.on('dragstart', this._onDragStart.bind(this));
  2778. this.root.on('drag', this._onDrag.bind(this));
  2779. this.root.on('dragend', this._onDragEnd.bind(this));
  2780. // ignore dragging when holding
  2781. this.root.on('hold', this._onHold.bind(this));
  2782. // mouse wheel for zooming
  2783. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2784. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2785. // pinch to zoom
  2786. this.root.on('touch', this._onTouch.bind(this));
  2787. this.root.on('pinch', this._onPinch.bind(this));
  2788. this.setOptions(options);
  2789. }
  2790. // turn Range into an event emitter
  2791. Emitter(Range.prototype);
  2792. /**
  2793. * Set options for the range controller
  2794. * @param {Object} options Available options:
  2795. * {Number} min Minimum value for start
  2796. * {Number} max Maximum value for end
  2797. * {Number} zoomMin Set a minimum value for
  2798. * (end - start).
  2799. * {Number} zoomMax Set a maximum value for
  2800. * (end - start).
  2801. */
  2802. Range.prototype.setOptions = function (options) {
  2803. util.extend(this.options, options);
  2804. // re-apply range with new limitations
  2805. if (this.start !== null && this.end !== null) {
  2806. this.setRange(this.start, this.end);
  2807. }
  2808. };
  2809. /**
  2810. * Test whether direction has a valid value
  2811. * @param {String} direction 'horizontal' or 'vertical'
  2812. */
  2813. function validateDirection (direction) {
  2814. if (direction != 'horizontal' && direction != 'vertical') {
  2815. throw new TypeError('Unknown direction "' + direction + '". ' +
  2816. 'Choose "horizontal" or "vertical".');
  2817. }
  2818. }
  2819. /**
  2820. * Set a new start and end range
  2821. * @param {Number} [start]
  2822. * @param {Number} [end]
  2823. */
  2824. Range.prototype.setRange = function(start, end) {
  2825. var changed = this._applyRange(start, end);
  2826. if (changed) {
  2827. var params = {
  2828. start: new Date(this.start),
  2829. end: new Date(this.end)
  2830. };
  2831. this.emit('rangechange', params);
  2832. this.emit('rangechanged', params);
  2833. }
  2834. };
  2835. /**
  2836. * Set a new start and end range. This method is the same as setRange, but
  2837. * does not trigger a range change and range changed event, and it returns
  2838. * true when the range is changed
  2839. * @param {Number} [start]
  2840. * @param {Number} [end]
  2841. * @return {Boolean} changed
  2842. * @private
  2843. */
  2844. Range.prototype._applyRange = function(start, end) {
  2845. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2846. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2847. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2848. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2849. diff;
  2850. // check for valid number
  2851. if (isNaN(newStart) || newStart === null) {
  2852. throw new Error('Invalid start "' + start + '"');
  2853. }
  2854. if (isNaN(newEnd) || newEnd === null) {
  2855. throw new Error('Invalid end "' + end + '"');
  2856. }
  2857. // prevent start < end
  2858. if (newEnd < newStart) {
  2859. newEnd = newStart;
  2860. }
  2861. // prevent start < min
  2862. if (min !== null) {
  2863. if (newStart < min) {
  2864. diff = (min - newStart);
  2865. newStart += diff;
  2866. newEnd += diff;
  2867. // prevent end > max
  2868. if (max != null) {
  2869. if (newEnd > max) {
  2870. newEnd = max;
  2871. }
  2872. }
  2873. }
  2874. }
  2875. // prevent end > max
  2876. if (max !== null) {
  2877. if (newEnd > max) {
  2878. diff = (newEnd - max);
  2879. newStart -= diff;
  2880. newEnd -= diff;
  2881. // prevent start < min
  2882. if (min != null) {
  2883. if (newStart < min) {
  2884. newStart = min;
  2885. }
  2886. }
  2887. }
  2888. }
  2889. // prevent (end-start) < zoomMin
  2890. if (this.options.zoomMin !== null) {
  2891. var zoomMin = parseFloat(this.options.zoomMin);
  2892. if (zoomMin < 0) {
  2893. zoomMin = 0;
  2894. }
  2895. if ((newEnd - newStart) < zoomMin) {
  2896. if ((this.end - this.start) === zoomMin) {
  2897. // ignore this action, we are already zoomed to the minimum
  2898. newStart = this.start;
  2899. newEnd = this.end;
  2900. }
  2901. else {
  2902. // zoom to the minimum
  2903. diff = (zoomMin - (newEnd - newStart));
  2904. newStart -= diff / 2;
  2905. newEnd += diff / 2;
  2906. }
  2907. }
  2908. }
  2909. // prevent (end-start) > zoomMax
  2910. if (this.options.zoomMax !== null) {
  2911. var zoomMax = parseFloat(this.options.zoomMax);
  2912. if (zoomMax < 0) {
  2913. zoomMax = 0;
  2914. }
  2915. if ((newEnd - newStart) > zoomMax) {
  2916. if ((this.end - this.start) === zoomMax) {
  2917. // ignore this action, we are already zoomed to the maximum
  2918. newStart = this.start;
  2919. newEnd = this.end;
  2920. }
  2921. else {
  2922. // zoom to the maximum
  2923. diff = ((newEnd - newStart) - zoomMax);
  2924. newStart += diff / 2;
  2925. newEnd -= diff / 2;
  2926. }
  2927. }
  2928. }
  2929. var changed = (this.start != newStart || this.end != newEnd);
  2930. this.start = newStart;
  2931. this.end = newEnd;
  2932. return changed;
  2933. };
  2934. /**
  2935. * Retrieve the current range.
  2936. * @return {Object} An object with start and end properties
  2937. */
  2938. Range.prototype.getRange = function() {
  2939. return {
  2940. start: this.start,
  2941. end: this.end
  2942. };
  2943. };
  2944. /**
  2945. * Calculate the conversion offset and scale for current range, based on
  2946. * the provided width
  2947. * @param {Number} width
  2948. * @returns {{offset: number, scale: number}} conversion
  2949. */
  2950. Range.prototype.conversion = function (width) {
  2951. return Range.conversion(this.start, this.end, width);
  2952. };
  2953. /**
  2954. * Static method to calculate the conversion offset and scale for a range,
  2955. * based on the provided start, end, and width
  2956. * @param {Number} start
  2957. * @param {Number} end
  2958. * @param {Number} width
  2959. * @returns {{offset: number, scale: number}} conversion
  2960. */
  2961. Range.conversion = function (start, end, width) {
  2962. if (width != 0 && (end - start != 0)) {
  2963. return {
  2964. offset: start,
  2965. scale: width / (end - start)
  2966. }
  2967. }
  2968. else {
  2969. return {
  2970. offset: 0,
  2971. scale: 1
  2972. };
  2973. }
  2974. };
  2975. // global (private) object to store drag params
  2976. var touchParams = {};
  2977. /**
  2978. * Start dragging horizontally or vertically
  2979. * @param {Event} event
  2980. * @private
  2981. */
  2982. Range.prototype._onDragStart = function(event) {
  2983. // refuse to drag when we where pinching to prevent the timeline make a jump
  2984. // when releasing the fingers in opposite order from the touch screen
  2985. if (touchParams.ignore) return;
  2986. // TODO: reckon with option movable
  2987. touchParams.start = this.start;
  2988. touchParams.end = this.end;
  2989. var frame = this.parent.frame;
  2990. if (frame) {
  2991. frame.style.cursor = 'move';
  2992. }
  2993. };
  2994. /**
  2995. * Perform dragging operating.
  2996. * @param {Event} event
  2997. * @private
  2998. */
  2999. Range.prototype._onDrag = function (event) {
  3000. var direction = this.options.direction;
  3001. validateDirection(direction);
  3002. // TODO: reckon with option movable
  3003. // refuse to drag when we where pinching to prevent the timeline make a jump
  3004. // when releasing the fingers in opposite order from the touch screen
  3005. if (touchParams.ignore) return;
  3006. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3007. interval = (touchParams.end - touchParams.start),
  3008. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  3009. diffRange = -delta / width * interval;
  3010. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3011. this.emit('rangechange', {
  3012. start: new Date(this.start),
  3013. end: new Date(this.end)
  3014. });
  3015. };
  3016. /**
  3017. * Stop dragging operating.
  3018. * @param {event} event
  3019. * @private
  3020. */
  3021. Range.prototype._onDragEnd = function (event) {
  3022. // refuse to drag when we where pinching to prevent the timeline make a jump
  3023. // when releasing the fingers in opposite order from the touch screen
  3024. if (touchParams.ignore) return;
  3025. // TODO: reckon with option movable
  3026. if (this.parent.frame) {
  3027. this.parent.frame.style.cursor = 'auto';
  3028. }
  3029. // fire a rangechanged event
  3030. this.emit('rangechanged', {
  3031. start: new Date(this.start),
  3032. end: new Date(this.end)
  3033. });
  3034. };
  3035. /**
  3036. * Event handler for mouse wheel event, used to zoom
  3037. * Code from http://adomas.org/javascript-mouse-wheel/
  3038. * @param {Event} event
  3039. * @private
  3040. */
  3041. Range.prototype._onMouseWheel = function(event) {
  3042. // TODO: reckon with option zoomable
  3043. // retrieve delta
  3044. var delta = 0;
  3045. if (event.wheelDelta) { /* IE/Opera. */
  3046. delta = event.wheelDelta / 120;
  3047. } else if (event.detail) { /* Mozilla case. */
  3048. // In Mozilla, sign of delta is different than in IE.
  3049. // Also, delta is multiple of 3.
  3050. delta = -event.detail / 3;
  3051. }
  3052. // If delta is nonzero, handle it.
  3053. // Basically, delta is now positive if wheel was scrolled up,
  3054. // and negative, if wheel was scrolled down.
  3055. if (delta) {
  3056. // perform the zoom action. Delta is normally 1 or -1
  3057. // adjust a negative delta such that zooming in with delta 0.1
  3058. // equals zooming out with a delta -0.1
  3059. var scale;
  3060. if (delta < 0) {
  3061. scale = 1 - (delta / 5);
  3062. }
  3063. else {
  3064. scale = 1 / (1 + (delta / 5)) ;
  3065. }
  3066. // calculate center, the date to zoom around
  3067. var gesture = util.fakeGesture(this, event),
  3068. pointer = getPointer(gesture.center, this.parent.frame),
  3069. pointerDate = this._pointerToDate(pointer);
  3070. this.zoom(scale, pointerDate);
  3071. }
  3072. // Prevent default actions caused by mouse wheel
  3073. // (else the page and timeline both zoom and scroll)
  3074. event.preventDefault();
  3075. };
  3076. /**
  3077. * Start of a touch gesture
  3078. * @private
  3079. */
  3080. Range.prototype._onTouch = function (event) {
  3081. touchParams.start = this.start;
  3082. touchParams.end = this.end;
  3083. touchParams.ignore = false;
  3084. touchParams.center = null;
  3085. // don't move the range when dragging a selected event
  3086. // TODO: it's not so neat to have to know about the state of the ItemSet
  3087. var item = ItemSet.itemFromTarget(event);
  3088. if (item && item.selected && this.options.editable) {
  3089. touchParams.ignore = true;
  3090. }
  3091. };
  3092. /**
  3093. * On start of a hold gesture
  3094. * @private
  3095. */
  3096. Range.prototype._onHold = function () {
  3097. touchParams.ignore = true;
  3098. };
  3099. /**
  3100. * Handle pinch event
  3101. * @param {Event} event
  3102. * @private
  3103. */
  3104. Range.prototype._onPinch = function (event) {
  3105. var direction = this.options.direction;
  3106. touchParams.ignore = true;
  3107. // TODO: reckon with option zoomable
  3108. if (event.gesture.touches.length > 1) {
  3109. if (!touchParams.center) {
  3110. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3111. }
  3112. var scale = 1 / event.gesture.scale,
  3113. initDate = this._pointerToDate(touchParams.center),
  3114. center = getPointer(event.gesture.center, this.parent.frame),
  3115. date = this._pointerToDate(this.parent, center),
  3116. delta = date - initDate; // TODO: utilize delta
  3117. // calculate new start and end
  3118. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3119. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3120. // apply new range
  3121. this.setRange(newStart, newEnd);
  3122. }
  3123. };
  3124. /**
  3125. * Helper function to calculate the center date for zooming
  3126. * @param {{x: Number, y: Number}} pointer
  3127. * @return {number} date
  3128. * @private
  3129. */
  3130. Range.prototype._pointerToDate = function (pointer) {
  3131. var conversion;
  3132. var direction = this.options.direction;
  3133. validateDirection(direction);
  3134. if (direction == 'horizontal') {
  3135. var width = this.parent.width;
  3136. conversion = this.conversion(width);
  3137. return pointer.x / conversion.scale + conversion.offset;
  3138. }
  3139. else {
  3140. var height = this.parent.height;
  3141. conversion = this.conversion(height);
  3142. return pointer.y / conversion.scale + conversion.offset;
  3143. }
  3144. };
  3145. /**
  3146. * Get the pointer location relative to the location of the dom element
  3147. * @param {{pageX: Number, pageY: Number}} touch
  3148. * @param {Element} element HTML DOM element
  3149. * @return {{x: Number, y: Number}} pointer
  3150. * @private
  3151. */
  3152. function getPointer (touch, element) {
  3153. return {
  3154. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3155. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3156. };
  3157. }
  3158. /**
  3159. * Zoom the range the given scale in or out. Start and end date will
  3160. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3161. * date around which to zoom.
  3162. * For example, try scale = 0.9 or 1.1
  3163. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3164. * values below 1 will zoom in.
  3165. * @param {Number} [center] Value representing a date around which will
  3166. * be zoomed.
  3167. */
  3168. Range.prototype.zoom = function(scale, center) {
  3169. // if centerDate is not provided, take it half between start Date and end Date
  3170. if (center == null) {
  3171. center = (this.start + this.end) / 2;
  3172. }
  3173. // calculate new start and end
  3174. var newStart = center + (this.start - center) * scale;
  3175. var newEnd = center + (this.end - center) * scale;
  3176. this.setRange(newStart, newEnd);
  3177. };
  3178. /**
  3179. * Move the range with a given delta to the left or right. Start and end
  3180. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3181. * @param {Number} delta Moving amount. Positive value will move right,
  3182. * negative value will move left
  3183. */
  3184. Range.prototype.move = function(delta) {
  3185. // zoom start Date and end Date relative to the centerDate
  3186. var diff = (this.end - this.start);
  3187. // apply new values
  3188. var newStart = this.start + diff * delta;
  3189. var newEnd = this.end + diff * delta;
  3190. // TODO: reckon with min and max range
  3191. this.start = newStart;
  3192. this.end = newEnd;
  3193. };
  3194. /**
  3195. * Move the range to a new center point
  3196. * @param {Number} moveTo New center point of the range
  3197. */
  3198. Range.prototype.moveTo = function(moveTo) {
  3199. var center = (this.start + this.end) / 2;
  3200. var diff = center - moveTo;
  3201. // calculate new start and end
  3202. var newStart = this.start - diff;
  3203. var newEnd = this.end - diff;
  3204. this.setRange(newStart, newEnd);
  3205. };
  3206. /**
  3207. * Prototype for visual components
  3208. */
  3209. function Component () {
  3210. this.id = null;
  3211. this.parent = null;
  3212. this.childs = null;
  3213. this.options = null;
  3214. this.top = 0;
  3215. this.left = 0;
  3216. this.width = 0;
  3217. this.height = 0;
  3218. }
  3219. // Turn the Component into an event emitter
  3220. Emitter(Component.prototype);
  3221. /**
  3222. * Set parameters for the frame. Parameters will be merged in current parameter
  3223. * set.
  3224. * @param {Object} options Available parameters:
  3225. * {String | function} [className]
  3226. * {String | Number | function} [left]
  3227. * {String | Number | function} [top]
  3228. * {String | Number | function} [width]
  3229. * {String | Number | function} [height]
  3230. */
  3231. Component.prototype.setOptions = function setOptions(options) {
  3232. if (options) {
  3233. util.extend(this.options, options);
  3234. this.repaint();
  3235. }
  3236. };
  3237. /**
  3238. * Get an option value by name
  3239. * The function will first check this.options object, and else will check
  3240. * this.defaultOptions.
  3241. * @param {String} name
  3242. * @return {*} value
  3243. */
  3244. Component.prototype.getOption = function getOption(name) {
  3245. var value;
  3246. if (this.options) {
  3247. value = this.options[name];
  3248. }
  3249. if (value === undefined && this.defaultOptions) {
  3250. value = this.defaultOptions[name];
  3251. }
  3252. return value;
  3253. };
  3254. /**
  3255. * Get the frame element of the component, the outer HTML DOM element.
  3256. * @returns {HTMLElement | null} frame
  3257. */
  3258. Component.prototype.getFrame = function getFrame() {
  3259. // should be implemented by the component
  3260. return null;
  3261. };
  3262. /**
  3263. * Repaint the component
  3264. * @return {boolean} Returns true if the component is resized
  3265. */
  3266. Component.prototype.repaint = function repaint() {
  3267. // should be implemented by the component
  3268. return false;
  3269. };
  3270. /**
  3271. * Test whether the component is resized since the last time _isResized() was
  3272. * called.
  3273. * @return {Boolean} Returns true if the component is resized
  3274. * @private
  3275. */
  3276. Component.prototype._isResized = function _isResized() {
  3277. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3278. this._previousWidth = this.width;
  3279. this._previousHeight = this.height;
  3280. return resized;
  3281. };
  3282. /**
  3283. * A panel can contain components
  3284. * @param {Object} [options] Available parameters:
  3285. * {String | Number | function} [left]
  3286. * {String | Number | function} [top]
  3287. * {String | Number | function} [width]
  3288. * {String | Number | function} [height]
  3289. * {String | function} [className]
  3290. * @constructor Panel
  3291. * @extends Component
  3292. */
  3293. function Panel(options) {
  3294. this.id = util.randomUUID();
  3295. this.parent = null;
  3296. this.childs = [];
  3297. this.options = options || {};
  3298. // create frame
  3299. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3300. }
  3301. Panel.prototype = new Component();
  3302. /**
  3303. * Set options. Will extend the current options.
  3304. * @param {Object} [options] Available parameters:
  3305. * {String | function} [className]
  3306. * {String | Number | function} [left]
  3307. * {String | Number | function} [top]
  3308. * {String | Number | function} [width]
  3309. * {String | Number | function} [height]
  3310. */
  3311. Panel.prototype.setOptions = Component.prototype.setOptions;
  3312. /**
  3313. * Get the outer frame of the panel
  3314. * @returns {HTMLElement} frame
  3315. */
  3316. Panel.prototype.getFrame = function () {
  3317. return this.frame;
  3318. };
  3319. /**
  3320. * Append a child to the panel
  3321. * @param {Component} child
  3322. */
  3323. Panel.prototype.appendChild = function (child) {
  3324. this.childs.push(child);
  3325. child.parent = this;
  3326. // attach to the DOM
  3327. var frame = child.getFrame();
  3328. if (frame) {
  3329. if (frame.parentNode) {
  3330. frame.parentNode.removeChild(frame);
  3331. }
  3332. this.frame.appendChild(frame);
  3333. }
  3334. };
  3335. /**
  3336. * Insert a child to the panel
  3337. * @param {Component} child
  3338. * @param {Component} beforeChild
  3339. */
  3340. Panel.prototype.insertBefore = function (child, beforeChild) {
  3341. var index = this.childs.indexOf(beforeChild);
  3342. if (index != -1) {
  3343. this.childs.splice(index, 0, child);
  3344. child.parent = this;
  3345. // attach to the DOM
  3346. var frame = child.getFrame();
  3347. if (frame) {
  3348. if (frame.parentNode) {
  3349. frame.parentNode.removeChild(frame);
  3350. }
  3351. var beforeFrame = beforeChild.getFrame();
  3352. if (beforeFrame) {
  3353. this.frame.insertBefore(frame, beforeFrame);
  3354. }
  3355. else {
  3356. this.frame.appendChild(frame);
  3357. }
  3358. }
  3359. }
  3360. };
  3361. /**
  3362. * Remove a child from the panel
  3363. * @param {Component} child
  3364. */
  3365. Panel.prototype.removeChild = function (child) {
  3366. var index = this.childs.indexOf(child);
  3367. if (index != -1) {
  3368. this.childs.splice(index, 1);
  3369. child.parent = null;
  3370. // remove from the DOM
  3371. var frame = child.getFrame();
  3372. if (frame && frame.parentNode) {
  3373. this.frame.removeChild(frame);
  3374. }
  3375. }
  3376. };
  3377. /**
  3378. * Test whether the panel contains given child
  3379. * @param {Component} child
  3380. */
  3381. Panel.prototype.hasChild = function (child) {
  3382. var index = this.childs.indexOf(child);
  3383. return (index != -1);
  3384. };
  3385. /**
  3386. * Repaint the component
  3387. * @return {boolean} Returns true if the component was resized since previous repaint
  3388. */
  3389. Panel.prototype.repaint = function () {
  3390. var asString = util.option.asString,
  3391. options = this.options,
  3392. frame = this.getFrame();
  3393. // update className
  3394. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3395. // repaint the child components
  3396. var childsResized = this._repaintChilds();
  3397. // update frame size
  3398. this._updateSize();
  3399. return this._isResized() || childsResized;
  3400. };
  3401. /**
  3402. * Repaint all childs of the panel
  3403. * @return {boolean} Returns true if the component is resized
  3404. * @private
  3405. */
  3406. Panel.prototype._repaintChilds = function () {
  3407. var resized = false;
  3408. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3409. resized = this.childs[i].repaint() || resized;
  3410. }
  3411. return resized;
  3412. };
  3413. /**
  3414. * Apply the size from options to the panel, and recalculate it's actual size.
  3415. * @private
  3416. */
  3417. Panel.prototype._updateSize = function () {
  3418. // apply size
  3419. this.frame.style.top = util.option.asSize(this.options.top);
  3420. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3421. this.frame.style.left = util.option.asSize(this.options.left);
  3422. this.frame.style.right = util.option.asSize(this.options.right);
  3423. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3424. this.frame.style.height = util.option.asSize(this.options.height, '');
  3425. // get actual size
  3426. this.top = this.frame.offsetTop;
  3427. this.left = this.frame.offsetLeft;
  3428. this.width = this.frame.offsetWidth;
  3429. this.height = this.frame.offsetHeight;
  3430. };
  3431. /**
  3432. * A root panel can hold components. The root panel must be initialized with
  3433. * a DOM element as container.
  3434. * @param {HTMLElement} container
  3435. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3436. * @constructor RootPanel
  3437. * @extends Panel
  3438. */
  3439. function RootPanel(container, options) {
  3440. this.id = util.randomUUID();
  3441. this.container = container;
  3442. this.options = options || {};
  3443. this.defaultOptions = {
  3444. autoResize: true
  3445. };
  3446. // create the HTML DOM
  3447. this._create();
  3448. // attach the root panel to the provided container
  3449. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3450. this.container.appendChild(this.getFrame());
  3451. this._initWatch();
  3452. }
  3453. RootPanel.prototype = new Panel();
  3454. /**
  3455. * Create the HTML DOM for the root panel
  3456. */
  3457. RootPanel.prototype._create = function _create() {
  3458. // create frame
  3459. this.frame = document.createElement('div');
  3460. // create event listeners for all interesting events, these events will be
  3461. // emitted via emitter
  3462. this.hammer = Hammer(this.frame, {
  3463. prevent_default: true
  3464. });
  3465. this.listeners = {};
  3466. var me = this;
  3467. var events = [
  3468. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3469. 'dragstart', 'drag', 'dragend',
  3470. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3471. ];
  3472. events.forEach(function (event) {
  3473. var listener = function () {
  3474. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3475. me.emit.apply(me, args);
  3476. };
  3477. me.hammer.on(event, listener);
  3478. me.listeners[event] = listener;
  3479. });
  3480. };
  3481. /**
  3482. * Set options. Will extend the current options.
  3483. * @param {Object} [options] Available parameters:
  3484. * {String | function} [className]
  3485. * {String | Number | function} [left]
  3486. * {String | Number | function} [top]
  3487. * {String | Number | function} [width]
  3488. * {String | Number | function} [height]
  3489. * {Boolean | function} [autoResize]
  3490. */
  3491. RootPanel.prototype.setOptions = function setOptions(options) {
  3492. if (options) {
  3493. util.extend(this.options, options);
  3494. this.repaint();
  3495. this._initWatch();
  3496. }
  3497. };
  3498. /**
  3499. * Get the frame of the root panel
  3500. */
  3501. RootPanel.prototype.getFrame = function getFrame() {
  3502. return this.frame;
  3503. };
  3504. /**
  3505. * Repaint the root panel
  3506. */
  3507. RootPanel.prototype.repaint = function repaint() {
  3508. // update class name
  3509. var options = this.options;
  3510. var className = 'vis timeline rootpanel ' + options.orientation + (options.editable ? ' editable' : '');
  3511. if (options.className) className += ' ' + util.option.asString(className);
  3512. this.frame.className = className;
  3513. // repaint the child components
  3514. var childsResized = this._repaintChilds();
  3515. // update frame size
  3516. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3517. this._updateSize();
  3518. // if the root panel or any of its childs is resized, repaint again,
  3519. // as other components may need to be resized accordingly
  3520. var resized = this._isResized() || childsResized;
  3521. if (resized) {
  3522. setTimeout(this.repaint.bind(this), 0);
  3523. }
  3524. };
  3525. /**
  3526. * Initialize watching when option autoResize is true
  3527. * @private
  3528. */
  3529. RootPanel.prototype._initWatch = function _initWatch() {
  3530. var autoResize = this.getOption('autoResize');
  3531. if (autoResize) {
  3532. this._watch();
  3533. }
  3534. else {
  3535. this._unwatch();
  3536. }
  3537. };
  3538. /**
  3539. * Watch for changes in the size of the frame. On resize, the Panel will
  3540. * automatically redraw itself.
  3541. * @private
  3542. */
  3543. RootPanel.prototype._watch = function _watch() {
  3544. var me = this;
  3545. this._unwatch();
  3546. var checkSize = function checkSize() {
  3547. var autoResize = me.getOption('autoResize');
  3548. if (!autoResize) {
  3549. // stop watching when the option autoResize is changed to false
  3550. me._unwatch();
  3551. return;
  3552. }
  3553. if (me.frame) {
  3554. // check whether the frame is resized
  3555. if ((me.frame.clientWidth != me.lastWidth) ||
  3556. (me.frame.clientHeight != me.lastHeight)) {
  3557. me.lastWidth = me.frame.clientWidth;
  3558. me.lastHeight = me.frame.clientHeight;
  3559. me.repaint();
  3560. // TODO: emit a resize event instead?
  3561. }
  3562. }
  3563. };
  3564. // TODO: automatically cleanup the event listener when the frame is deleted
  3565. util.addEventListener(window, 'resize', checkSize);
  3566. this.watchTimer = setInterval(checkSize, 1000);
  3567. };
  3568. /**
  3569. * Stop watching for a resize of the frame.
  3570. * @private
  3571. */
  3572. RootPanel.prototype._unwatch = function _unwatch() {
  3573. if (this.watchTimer) {
  3574. clearInterval(this.watchTimer);
  3575. this.watchTimer = undefined;
  3576. }
  3577. // TODO: remove event listener on window.resize
  3578. };
  3579. /**
  3580. * A horizontal time axis
  3581. * @param {Object} [options] See TimeAxis.setOptions for the available
  3582. * options.
  3583. * @constructor TimeAxis
  3584. * @extends Component
  3585. */
  3586. function TimeAxis (options) {
  3587. this.id = util.randomUUID();
  3588. this.dom = {
  3589. majorLines: [],
  3590. majorTexts: [],
  3591. minorLines: [],
  3592. minorTexts: [],
  3593. redundant: {
  3594. majorLines: [],
  3595. majorTexts: [],
  3596. minorLines: [],
  3597. minorTexts: []
  3598. }
  3599. };
  3600. this.props = {
  3601. range: {
  3602. start: 0,
  3603. end: 0,
  3604. minimumStep: 0
  3605. },
  3606. lineTop: 0
  3607. };
  3608. this.options = options || {};
  3609. this.defaultOptions = {
  3610. orientation: 'bottom', // supported: 'top', 'bottom'
  3611. // TODO: implement timeaxis orientations 'left' and 'right'
  3612. showMinorLabels: true,
  3613. showMajorLabels: true
  3614. };
  3615. this.range = null;
  3616. // create the HTML DOM
  3617. this._create();
  3618. }
  3619. TimeAxis.prototype = new Component();
  3620. // TODO: comment options
  3621. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3622. /**
  3623. * Create the HTML DOM for the TimeAxis
  3624. */
  3625. TimeAxis.prototype._create = function _create() {
  3626. this.frame = document.createElement('div');
  3627. };
  3628. /**
  3629. * Set a range (start and end)
  3630. * @param {Range | Object} range A Range or an object containing start and end.
  3631. */
  3632. TimeAxis.prototype.setRange = function (range) {
  3633. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3634. throw new TypeError('Range must be an instance of Range, ' +
  3635. 'or an object containing start and end.');
  3636. }
  3637. this.range = range;
  3638. };
  3639. /**
  3640. * Get the outer frame of the time axis
  3641. * @return {HTMLElement} frame
  3642. */
  3643. TimeAxis.prototype.getFrame = function getFrame() {
  3644. return this.frame;
  3645. };
  3646. /**
  3647. * Repaint the component
  3648. * @return {boolean} Returns true if the component is resized
  3649. */
  3650. TimeAxis.prototype.repaint = function () {
  3651. var asSize = util.option.asSize,
  3652. options = this.options,
  3653. props = this.props,
  3654. frame = this.frame;
  3655. // update classname
  3656. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3657. var parent = frame.parentNode;
  3658. if (parent) {
  3659. // calculate character width and height
  3660. this._calculateCharSize();
  3661. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3662. var orientation = this.getOption('orientation'),
  3663. showMinorLabels = this.getOption('showMinorLabels'),
  3664. showMajorLabels = this.getOption('showMajorLabels');
  3665. // determine the width and height of the elemens for the axis
  3666. var parentHeight = this.parent.height;
  3667. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3668. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3669. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3670. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3671. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3672. props.minorLineWidth = 1; // TODO: really calculate width
  3673. props.majorLineHeight = parentHeight + this.height;
  3674. props.majorLineWidth = 1; // TODO: really calculate width
  3675. // take frame offline while updating (is almost twice as fast)
  3676. var beforeChild = frame.nextSibling;
  3677. parent.removeChild(frame);
  3678. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3679. if (orientation == 'top') {
  3680. frame.style.top = '0';
  3681. frame.style.left = '0';
  3682. frame.style.bottom = '';
  3683. frame.style.width = asSize(options.width, '100%');
  3684. frame.style.height = this.height + 'px';
  3685. }
  3686. else { // bottom
  3687. frame.style.top = '';
  3688. frame.style.bottom = '0';
  3689. frame.style.left = '0';
  3690. frame.style.width = asSize(options.width, '100%');
  3691. frame.style.height = this.height + 'px';
  3692. }
  3693. this._repaintLabels();
  3694. this._repaintLine();
  3695. // put frame online again
  3696. if (beforeChild) {
  3697. parent.insertBefore(frame, beforeChild);
  3698. }
  3699. else {
  3700. parent.appendChild(frame)
  3701. }
  3702. }
  3703. return this._isResized();
  3704. };
  3705. /**
  3706. * Repaint major and minor text labels and vertical grid lines
  3707. * @private
  3708. */
  3709. TimeAxis.prototype._repaintLabels = function () {
  3710. var orientation = this.getOption('orientation');
  3711. // calculate range and step
  3712. var start = util.convert(this.range.start, 'Number'),
  3713. end = util.convert(this.range.end, 'Number'),
  3714. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 5).valueOf()
  3715. -this.options.toTime(0).valueOf();
  3716. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3717. this.step = step;
  3718. // Move all DOM elements to a "redundant" list, where they
  3719. // can be picked for re-use, and clear the lists with lines and texts.
  3720. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3721. var dom = this.dom;
  3722. dom.redundant.majorLines = dom.majorLines;
  3723. dom.redundant.majorTexts = dom.majorTexts;
  3724. dom.redundant.minorLines = dom.minorLines;
  3725. dom.redundant.minorTexts = dom.minorTexts;
  3726. dom.majorLines = [];
  3727. dom.majorTexts = [];
  3728. dom.minorLines = [];
  3729. dom.minorTexts = [];
  3730. step.first();
  3731. var xFirstMajorLabel = undefined;
  3732. var max = 0;
  3733. while (step.hasNext() && max < 1000) {
  3734. max++;
  3735. var cur = step.getCurrent(),
  3736. x = this.options.toScreen(cur),
  3737. isMajor = step.isMajor();
  3738. // TODO: lines must have a width, such that we can create css backgrounds
  3739. if (this.getOption('showMinorLabels')) {
  3740. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3741. }
  3742. if (isMajor && this.getOption('showMajorLabels')) {
  3743. if (x > 0) {
  3744. if (xFirstMajorLabel == undefined) {
  3745. xFirstMajorLabel = x;
  3746. }
  3747. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3748. }
  3749. this._repaintMajorLine(x, orientation);
  3750. }
  3751. else {
  3752. this._repaintMinorLine(x, orientation);
  3753. }
  3754. step.next();
  3755. }
  3756. // create a major label on the left when needed
  3757. if (this.getOption('showMajorLabels')) {
  3758. var leftTime = this.options.toTime(0),
  3759. leftText = step.getLabelMajor(leftTime),
  3760. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3761. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3762. this._repaintMajorText(0, leftText, orientation);
  3763. }
  3764. }
  3765. // Cleanup leftover DOM elements from the redundant list
  3766. util.forEach(this.dom.redundant, function (arr) {
  3767. while (arr.length) {
  3768. var elem = arr.pop();
  3769. if (elem && elem.parentNode) {
  3770. elem.parentNode.removeChild(elem);
  3771. }
  3772. }
  3773. });
  3774. };
  3775. /**
  3776. * Create a minor label for the axis at position x
  3777. * @param {Number} x
  3778. * @param {String} text
  3779. * @param {String} orientation "top" or "bottom" (default)
  3780. * @private
  3781. */
  3782. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3783. // reuse redundant label
  3784. var label = this.dom.redundant.minorTexts.shift();
  3785. if (!label) {
  3786. // create new label
  3787. var content = document.createTextNode('');
  3788. label = document.createElement('div');
  3789. label.appendChild(content);
  3790. label.className = 'text minor';
  3791. this.frame.appendChild(label);
  3792. }
  3793. this.dom.minorTexts.push(label);
  3794. label.childNodes[0].nodeValue = text;
  3795. if (orientation == 'top') {
  3796. label.style.top = this.props.majorLabelHeight + 'px';
  3797. label.style.bottom = '';
  3798. }
  3799. else {
  3800. label.style.top = '';
  3801. label.style.bottom = this.props.majorLabelHeight + 'px';
  3802. }
  3803. label.style.left = x + 'px';
  3804. //label.title = title; // TODO: this is a heavy operation
  3805. };
  3806. /**
  3807. * Create a Major label for the axis at position x
  3808. * @param {Number} x
  3809. * @param {String} text
  3810. * @param {String} orientation "top" or "bottom" (default)
  3811. * @private
  3812. */
  3813. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3814. // reuse redundant label
  3815. var label = this.dom.redundant.majorTexts.shift();
  3816. if (!label) {
  3817. // create label
  3818. var content = document.createTextNode(text);
  3819. label = document.createElement('div');
  3820. label.className = 'text major';
  3821. label.appendChild(content);
  3822. this.frame.appendChild(label);
  3823. }
  3824. this.dom.majorTexts.push(label);
  3825. label.childNodes[0].nodeValue = text;
  3826. //label.title = title; // TODO: this is a heavy operation
  3827. if (orientation == 'top') {
  3828. label.style.top = '0px';
  3829. label.style.bottom = '';
  3830. }
  3831. else {
  3832. label.style.top = '';
  3833. label.style.bottom = '0px';
  3834. }
  3835. label.style.left = x + 'px';
  3836. };
  3837. /**
  3838. * Create a minor line for the axis at position x
  3839. * @param {Number} x
  3840. * @param {String} orientation "top" or "bottom" (default)
  3841. * @private
  3842. */
  3843. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3844. // reuse redundant line
  3845. var line = this.dom.redundant.minorLines.shift();
  3846. if (!line) {
  3847. // create vertical line
  3848. line = document.createElement('div');
  3849. line.className = 'grid vertical minor';
  3850. this.frame.appendChild(line);
  3851. }
  3852. this.dom.minorLines.push(line);
  3853. var props = this.props;
  3854. if (orientation == 'top') {
  3855. line.style.top = this.props.majorLabelHeight + 'px';
  3856. line.style.bottom = '';
  3857. }
  3858. else {
  3859. line.style.top = '';
  3860. line.style.bottom = this.props.majorLabelHeight + 'px';
  3861. }
  3862. line.style.height = props.minorLineHeight + 'px';
  3863. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3864. };
  3865. /**
  3866. * Create a Major line for the axis at position x
  3867. * @param {Number} x
  3868. * @param {String} orientation "top" or "bottom" (default)
  3869. * @private
  3870. */
  3871. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3872. // reuse redundant line
  3873. var line = this.dom.redundant.majorLines.shift();
  3874. if (!line) {
  3875. // create vertical line
  3876. line = document.createElement('DIV');
  3877. line.className = 'grid vertical major';
  3878. this.frame.appendChild(line);
  3879. }
  3880. this.dom.majorLines.push(line);
  3881. var props = this.props;
  3882. if (orientation == 'top') {
  3883. line.style.top = '0px';
  3884. line.style.bottom = '';
  3885. }
  3886. else {
  3887. line.style.top = '';
  3888. line.style.bottom = '0px';
  3889. }
  3890. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3891. line.style.height = props.majorLineHeight + 'px';
  3892. };
  3893. /**
  3894. * Repaint the horizontal line for the axis
  3895. * @private
  3896. */
  3897. TimeAxis.prototype._repaintLine = function() {
  3898. var line = this.dom.line,
  3899. frame = this.frame,
  3900. orientation = this.getOption('orientation');
  3901. // line before all axis elements
  3902. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3903. if (line) {
  3904. // put this line at the end of all childs
  3905. frame.removeChild(line);
  3906. frame.appendChild(line);
  3907. }
  3908. else {
  3909. // create the axis line
  3910. line = document.createElement('div');
  3911. line.className = 'grid horizontal major';
  3912. frame.appendChild(line);
  3913. this.dom.line = line;
  3914. }
  3915. if (orientation == 'top') {
  3916. line.style.top = this.height + 'px';
  3917. line.style.bottom = '';
  3918. }
  3919. else {
  3920. line.style.top = '';
  3921. line.style.bottom = this.height + 'px';
  3922. }
  3923. }
  3924. else {
  3925. if (line && line.parentNode) {
  3926. line.parentNode.removeChild(line);
  3927. delete this.dom.line;
  3928. }
  3929. }
  3930. };
  3931. /**
  3932. * Determine the size of text on the axis (both major and minor axis).
  3933. * The size is calculated only once and then cached in this.props.
  3934. * @private
  3935. */
  3936. TimeAxis.prototype._calculateCharSize = function () {
  3937. // determine the char width and height on the minor axis
  3938. if (!('minorCharHeight' in this.props)) {
  3939. var textMinor = document.createTextNode('0');
  3940. var measureCharMinor = document.createElement('DIV');
  3941. measureCharMinor.className = 'text minor measure';
  3942. measureCharMinor.appendChild(textMinor);
  3943. this.frame.appendChild(measureCharMinor);
  3944. this.props.minorCharHeight = measureCharMinor.clientHeight;
  3945. this.props.minorCharWidth = measureCharMinor.clientWidth;
  3946. this.frame.removeChild(measureCharMinor);
  3947. }
  3948. if (!('majorCharHeight' in this.props)) {
  3949. var textMajor = document.createTextNode('0');
  3950. var measureCharMajor = document.createElement('DIV');
  3951. measureCharMajor.className = 'text major measure';
  3952. measureCharMajor.appendChild(textMajor);
  3953. this.frame.appendChild(measureCharMajor);
  3954. this.props.majorCharHeight = measureCharMajor.clientHeight;
  3955. this.props.majorCharWidth = measureCharMajor.clientWidth;
  3956. this.frame.removeChild(measureCharMajor);
  3957. }
  3958. };
  3959. /**
  3960. * Snap a date to a rounded value.
  3961. * The snap intervals are dependent on the current scale and step.
  3962. * @param {Date} date the date to be snapped.
  3963. * @return {Date} snappedDate
  3964. */
  3965. TimeAxis.prototype.snap = function snap (date) {
  3966. return this.step.snap(date);
  3967. };
  3968. /**
  3969. * A current time bar
  3970. * @param {Range} range
  3971. * @param {Object} [options] Available parameters:
  3972. * {Boolean} [showCurrentTime]
  3973. * @constructor CurrentTime
  3974. * @extends Component
  3975. */
  3976. function CurrentTime (range, options) {
  3977. this.id = util.randomUUID();
  3978. this.range = range;
  3979. this.options = options || {};
  3980. this.defaultOptions = {
  3981. showCurrentTime: false
  3982. };
  3983. this._create();
  3984. }
  3985. CurrentTime.prototype = new Component();
  3986. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3987. /**
  3988. * Create the HTML DOM for the current time bar
  3989. * @private
  3990. */
  3991. CurrentTime.prototype._create = function _create () {
  3992. var bar = document.createElement('div');
  3993. bar.className = 'currenttime';
  3994. bar.style.position = 'absolute';
  3995. bar.style.top = '0px';
  3996. bar.style.height = '100%';
  3997. this.bar = bar;
  3998. };
  3999. /**
  4000. * Get the frame element of the current time bar
  4001. * @returns {HTMLElement} frame
  4002. */
  4003. CurrentTime.prototype.getFrame = function getFrame() {
  4004. return this.bar;
  4005. };
  4006. /**
  4007. * Repaint the component
  4008. * @return {boolean} Returns true if the component is resized
  4009. */
  4010. CurrentTime.prototype.repaint = function repaint() {
  4011. var parent = this.parent;
  4012. var now = new Date();
  4013. var x = this.options.toScreen(now);
  4014. this.bar.style.left = x + 'px';
  4015. this.bar.title = 'Current time: ' + now;
  4016. return false;
  4017. };
  4018. /**
  4019. * Start auto refreshing the current time bar
  4020. */
  4021. CurrentTime.prototype.start = function start() {
  4022. var me = this;
  4023. function update () {
  4024. me.stop();
  4025. // determine interval to refresh
  4026. var scale = me.range.conversion(me.parent.width).scale;
  4027. var interval = 1 / scale / 10;
  4028. if (interval < 30) interval = 30;
  4029. if (interval > 1000) interval = 1000;
  4030. me.repaint();
  4031. // start a timer to adjust for the new time
  4032. me.currentTimeTimer = setTimeout(update, interval);
  4033. }
  4034. update();
  4035. };
  4036. /**
  4037. * Stop auto refreshing the current time bar
  4038. */
  4039. CurrentTime.prototype.stop = function stop() {
  4040. if (this.currentTimeTimer !== undefined) {
  4041. clearTimeout(this.currentTimeTimer);
  4042. delete this.currentTimeTimer;
  4043. }
  4044. };
  4045. /**
  4046. * A custom time bar
  4047. * @param {Object} [options] Available parameters:
  4048. * {Boolean} [showCustomTime]
  4049. * @constructor CustomTime
  4050. * @extends Component
  4051. */
  4052. function CustomTime (options) {
  4053. this.id = util.randomUUID();
  4054. this.options = options || {};
  4055. this.defaultOptions = {
  4056. showCustomTime: false
  4057. };
  4058. this.customTime = new Date();
  4059. this.eventParams = {}; // stores state parameters while dragging the bar
  4060. // create the DOM
  4061. this._create();
  4062. }
  4063. CustomTime.prototype = new Component();
  4064. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4065. /**
  4066. * Create the DOM for the custom time
  4067. * @private
  4068. */
  4069. CustomTime.prototype._create = function _create () {
  4070. var bar = document.createElement('div');
  4071. bar.className = 'customtime';
  4072. bar.style.position = 'absolute';
  4073. bar.style.top = '0px';
  4074. bar.style.height = '100%';
  4075. this.bar = bar;
  4076. var drag = document.createElement('div');
  4077. drag.style.position = 'relative';
  4078. drag.style.top = '0px';
  4079. drag.style.left = '-10px';
  4080. drag.style.height = '100%';
  4081. drag.style.width = '20px';
  4082. bar.appendChild(drag);
  4083. // attach event listeners
  4084. this.hammer = Hammer(bar, {
  4085. prevent_default: true
  4086. });
  4087. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4088. this.hammer.on('drag', this._onDrag.bind(this));
  4089. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4090. };
  4091. /**
  4092. * Get the frame element of the custom time bar
  4093. * @returns {HTMLElement} frame
  4094. */
  4095. CustomTime.prototype.getFrame = function getFrame() {
  4096. return this.bar;
  4097. };
  4098. /**
  4099. * Repaint the component
  4100. * @return {boolean} Returns true if the component is resized
  4101. */
  4102. CustomTime.prototype.repaint = function () {
  4103. var x = this.options.toScreen(this.customTime);
  4104. this.bar.style.left = x + 'px';
  4105. this.bar.title = 'Time: ' + this.customTime;
  4106. return false;
  4107. };
  4108. /**
  4109. * Set custom time.
  4110. * @param {Date} time
  4111. */
  4112. CustomTime.prototype.setCustomTime = function(time) {
  4113. this.customTime = new Date(time.valueOf());
  4114. this.repaint();
  4115. };
  4116. /**
  4117. * Retrieve the current custom time.
  4118. * @return {Date} customTime
  4119. */
  4120. CustomTime.prototype.getCustomTime = function() {
  4121. return new Date(this.customTime.valueOf());
  4122. };
  4123. /**
  4124. * Start moving horizontally
  4125. * @param {Event} event
  4126. * @private
  4127. */
  4128. CustomTime.prototype._onDragStart = function(event) {
  4129. this.eventParams.dragging = true;
  4130. this.eventParams.customTime = this.customTime;
  4131. event.stopPropagation();
  4132. event.preventDefault();
  4133. };
  4134. /**
  4135. * Perform moving operating.
  4136. * @param {Event} event
  4137. * @private
  4138. */
  4139. CustomTime.prototype._onDrag = function (event) {
  4140. if (!this.eventParams.dragging) return;
  4141. var deltaX = event.gesture.deltaX,
  4142. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4143. time = this.options.toTime(x);
  4144. this.setCustomTime(time);
  4145. // fire a timechange event
  4146. this.emit('timechange', {
  4147. time: new Date(this.customTime.valueOf())
  4148. });
  4149. event.stopPropagation();
  4150. event.preventDefault();
  4151. };
  4152. /**
  4153. * Stop moving operating.
  4154. * @param {event} event
  4155. * @private
  4156. */
  4157. CustomTime.prototype._onDragEnd = function (event) {
  4158. if (!this.eventParams.dragging) return;
  4159. // fire a timechanged event
  4160. this.emit('timechanged', {
  4161. time: new Date(this.customTime.valueOf())
  4162. });
  4163. event.stopPropagation();
  4164. event.preventDefault();
  4165. };
  4166. /**
  4167. * An ItemSet holds a set of items and ranges which can be displayed in a
  4168. * range. The width is determined by the parent of the ItemSet, and the height
  4169. * is determined by the size of the items.
  4170. * @param {Panel} backgroundPanel Panel which can be used to display the
  4171. * vertical lines of box items.
  4172. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4173. * can be displayed.
  4174. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4175. * @constructor ItemSet
  4176. * @extends Panel
  4177. */
  4178. function ItemSet(backgroundPanel, axisPanel, options) {
  4179. this.id = util.randomUUID();
  4180. // one options object is shared by this itemset and all its items
  4181. this.options = options || {};
  4182. this.backgroundPanel = backgroundPanel;
  4183. this.axisPanel = axisPanel;
  4184. this.itemOptions = Object.create(this.options);
  4185. this.dom = {};
  4186. this.hammer = null;
  4187. var me = this;
  4188. this.itemsData = null; // DataSet
  4189. this.range = null; // Range or Object {start: number, end: number}
  4190. // data change listeners
  4191. this.listeners = {
  4192. 'add': function (event, params, senderId) {
  4193. if (senderId != me.id) me._onAdd(params.items);
  4194. },
  4195. 'update': function (event, params, senderId) {
  4196. if (senderId != me.id) me._onUpdate(params.items);
  4197. },
  4198. 'remove': function (event, params, senderId) {
  4199. if (senderId != me.id) me._onRemove(params.items);
  4200. }
  4201. };
  4202. this.items = {}; // object with an Item for every data item
  4203. this.orderedItems = {
  4204. byStart: [],
  4205. byEnd: []
  4206. };
  4207. this.systemLoaded = false;
  4208. this.visibleItems = []; // visible, ordered items
  4209. this.selection = []; // list with the ids of all selected nodes
  4210. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4211. this.stack = new Stack(Object.create(this.options));
  4212. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4213. this.touchParams = {}; // stores properties while dragging
  4214. // create the HTML DOM
  4215. this._create();
  4216. }
  4217. ItemSet.prototype = new Panel();
  4218. // available item types will be registered here
  4219. ItemSet.types = {
  4220. box: ItemBox,
  4221. range: ItemRange,
  4222. rangeoverflow: ItemRangeOverflow,
  4223. point: ItemPoint
  4224. };
  4225. /**
  4226. * Create the HTML DOM for the ItemSet
  4227. */
  4228. ItemSet.prototype._create = function _create(){
  4229. var frame = document.createElement('div');
  4230. frame['timeline-itemset'] = this;
  4231. this.frame = frame;
  4232. // create background panel
  4233. var background = document.createElement('div');
  4234. background.className = 'background';
  4235. this.backgroundPanel.frame.appendChild(background);
  4236. this.dom.background = background;
  4237. // create foreground panel
  4238. var foreground = document.createElement('div');
  4239. foreground.className = 'foreground';
  4240. frame.appendChild(foreground);
  4241. this.dom.foreground = foreground;
  4242. // create axis panel
  4243. var axis = document.createElement('div');
  4244. axis.className = 'axis';
  4245. this.dom.axis = axis;
  4246. this.axisPanel.frame.appendChild(axis);
  4247. // attach event listeners
  4248. // TODO: use event listeners from the rootpanel to improve performance?
  4249. this.hammer = Hammer(frame, {
  4250. prevent_default: true
  4251. });
  4252. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4253. this.hammer.on('drag', this._onDrag.bind(this));
  4254. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4255. };
  4256. /**
  4257. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4258. * @param {Object} [options] The following options are available:
  4259. * {String | function} [className]
  4260. * class name for the itemset
  4261. * {String} [type]
  4262. * Default type for the items. Choose from 'box'
  4263. * (default), 'point', or 'range'. The default
  4264. * Style can be overwritten by individual items.
  4265. * {String} align
  4266. * Alignment for the items, only applicable for
  4267. * ItemBox. Choose 'center' (default), 'left', or
  4268. * 'right'.
  4269. * {String} orientation
  4270. * Orientation of the item set. Choose 'top' or
  4271. * 'bottom' (default).
  4272. * {Number} margin.axis
  4273. * Margin between the axis and the items in pixels.
  4274. * Default is 20.
  4275. * {Number} margin.item
  4276. * Margin between items in pixels. Default is 10.
  4277. * {Number} padding
  4278. * Padding of the contents of an item in pixels.
  4279. * Must correspond with the items css. Default is 5.
  4280. * {Function} snap
  4281. * Function to let items snap to nice dates when
  4282. * dragging items.
  4283. */
  4284. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4285. /**
  4286. * Hide the component from the DOM
  4287. */
  4288. ItemSet.prototype.hide = function hide() {
  4289. // remove the axis with dots
  4290. if (this.dom.axis.parentNode) {
  4291. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4292. }
  4293. // remove the background with vertical lines
  4294. if (this.dom.background.parentNode) {
  4295. this.dom.background.parentNode.removeChild(this.dom.background);
  4296. }
  4297. };
  4298. /**
  4299. * Show the component in the DOM (when not already visible).
  4300. * @return {Boolean} changed
  4301. */
  4302. ItemSet.prototype.show = function show() {
  4303. // show axis with dots
  4304. if (!this.dom.axis.parentNode) {
  4305. this.axisPanel.frame.appendChild(this.dom.axis);
  4306. }
  4307. // show background with vertical lines
  4308. if (!this.dom.background.parentNode) {
  4309. this.backgroundPanel.frame.appendChild(this.dom.background);
  4310. }
  4311. };
  4312. /**
  4313. * Set range (start and end).
  4314. * @param {Range | Object} range A Range or an object containing start and end.
  4315. */
  4316. ItemSet.prototype.setRange = function setRange(range) {
  4317. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4318. throw new TypeError('Range must be an instance of Range, ' +
  4319. 'or an object containing start and end.');
  4320. }
  4321. this.range = range;
  4322. };
  4323. /**
  4324. * Set selected items by their id. Replaces the current selection
  4325. * Unknown id's are silently ignored.
  4326. * @param {Array} [ids] An array with zero or more id's of the items to be
  4327. * selected. If ids is an empty array, all items will be
  4328. * unselected.
  4329. */
  4330. ItemSet.prototype.setSelection = function setSelection(ids) {
  4331. var i, ii, id, item;
  4332. if (ids) {
  4333. if (!Array.isArray(ids)) {
  4334. throw new TypeError('Array expected');
  4335. }
  4336. // unselect currently selected items
  4337. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4338. id = this.selection[i];
  4339. item = this.items[id];
  4340. if (item) item.unselect();
  4341. }
  4342. // select items
  4343. this.selection = [];
  4344. for (i = 0, ii = ids.length; i < ii; i++) {
  4345. id = ids[i];
  4346. item = this.items[id];
  4347. if (item) {
  4348. this.selection.push(id);
  4349. item.select();
  4350. }
  4351. }
  4352. }
  4353. };
  4354. /**
  4355. * Get the selected items by their id
  4356. * @return {Array} ids The ids of the selected items
  4357. */
  4358. ItemSet.prototype.getSelection = function getSelection() {
  4359. return this.selection.concat([]);
  4360. };
  4361. /**
  4362. * Deselect a selected item
  4363. * @param {String | Number} id
  4364. * @private
  4365. */
  4366. ItemSet.prototype._deselect = function _deselect(id) {
  4367. var selection = this.selection;
  4368. for (var i = 0, ii = selection.length; i < ii; i++) {
  4369. if (selection[i] == id) { // non-strict comparison!
  4370. selection.splice(i, 1);
  4371. break;
  4372. }
  4373. }
  4374. };
  4375. /**
  4376. * Return the item sets frame
  4377. * @returns {HTMLElement} frame
  4378. */
  4379. ItemSet.prototype.getFrame = function getFrame() {
  4380. return this.frame;
  4381. };
  4382. /**
  4383. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  4384. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  4385. * 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
  4386. * if the time we selected (start or end) is within the current range).
  4387. *
  4388. * 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
  4389. * 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,
  4390. * either the start OR end time has to be in the range.
  4391. *
  4392. * @param {Boolean} byEnd
  4393. * @returns {number}
  4394. * @private
  4395. */
  4396. ItemSet.prototype._binarySearch = function _binarySearch(byEnd) {
  4397. var array = []
  4398. var byTime = byEnd ? "end" : "start";
  4399. if (byEnd == true) {array = this.orderedItems.byEnd; }
  4400. else {array = this.orderedItems.byStart;}
  4401. var interval = this.range.end - this.range.start;
  4402. var found = false;
  4403. var low = 0;
  4404. var high = array.length;
  4405. var guess = Math.floor(0.5*(high+low));
  4406. var newGuess;
  4407. if (high == 0) {guess = -1;}
  4408. else if (high == 1) {
  4409. if ((array[guess].data[byTime] > this.range.start - interval) && (array[guess].data[byTime] < this.range.end + interval)) {
  4410. guess = 0;
  4411. }
  4412. else {
  4413. guess = -1;
  4414. }
  4415. }
  4416. else {
  4417. high -= 1;
  4418. while (found == false) {
  4419. if ((array[guess].data[byTime] > this.range.start - interval) && (array[guess].data[byTime] < this.range.end + interval)) {
  4420. found = true;
  4421. }
  4422. else {
  4423. if (array[guess].data[byTime] < this.range.start - interval) { // it is too small --> increase low
  4424. low = Math.floor(0.5*(high+low));
  4425. }
  4426. else { // it is too big --> decrease high
  4427. high = Math.floor(0.5*(high+low));
  4428. }
  4429. newGuess = Math.floor(0.5*(high+low));
  4430. // not in list;
  4431. if (guess == newGuess) {
  4432. guess = -1;
  4433. found = true;
  4434. }
  4435. else {
  4436. guess = newGuess;
  4437. }
  4438. }
  4439. }
  4440. }
  4441. return guess;
  4442. }
  4443. /**
  4444. * Repaint the component
  4445. * @return {boolean} Returns true if the component is resized
  4446. */
  4447. ItemSet.prototype.repaint = function repaint() {
  4448. var asSize = util.option.asSize,
  4449. asString = util.option.asString,
  4450. options = this.options,
  4451. orientation = this.getOption('orientation'),
  4452. frame = this.frame;
  4453. // update className
  4454. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4455. // check whether zoomed (in that case we need to re-stack everything)
  4456. var visibleInterval = this.range.end - this.range.start;
  4457. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4458. this.lastVisibleInterval = visibleInterval;
  4459. this.lastWidth = this.width;
  4460. var newVisibleItems = [];
  4461. var item;
  4462. var range = this.range;
  4463. var orderedItems = this.orderedItems;
  4464. // first check if the items that were in view previously are still in view.
  4465. // this handles the case for the ItemRange that is both before and after the current one.
  4466. if (this.visibleItems.length > 0) {
  4467. for (var i = 0; i < this.visibleItems.length; i++) {
  4468. item = this.visibleItems[i];
  4469. if (item.isVisible(range)) {
  4470. if (!item.displayed) item.show();
  4471. // reposition item horizontally
  4472. item.repositionX();
  4473. newVisibleItems.push(item);
  4474. }
  4475. else {
  4476. if (item.displayed) item.hide();
  4477. }
  4478. }
  4479. }
  4480. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  4481. if (newVisibleItems.length == 0) {var initialPosByStart = this._binarySearch(false);}
  4482. else {var initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);}
  4483. // use visible search to find a visible ItemRange (only based on endTime)
  4484. var initialPosByEnd = this._binarySearch(true);
  4485. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  4486. if (initialPosByStart != -1) {
  4487. for (var i = initialPosByStart; i >= 0; i--) {
  4488. item = orderedItems.byStart[i];
  4489. if (item.isVisible(range)) {
  4490. if (!item.displayed) item.show();
  4491. item.repositionX();
  4492. if (newVisibleItems.indexOf(item) == -1) {
  4493. newVisibleItems.push(item);
  4494. }
  4495. }
  4496. else {
  4497. break;
  4498. }
  4499. }
  4500. // and up
  4501. for (var i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  4502. item = orderedItems.byStart[i];
  4503. if (item.isVisible(range)) {
  4504. if (!item.displayed) item.show();
  4505. item.repositionX();
  4506. if (newVisibleItems.indexOf(item) == -1) {
  4507. newVisibleItems.push(item);
  4508. }
  4509. }
  4510. else {
  4511. break;
  4512. }
  4513. }
  4514. }
  4515. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  4516. if (initialPosByEnd != -1) {
  4517. for (var i = initialPosByEnd; i >= 0; i--) {
  4518. item = orderedItems.byEnd[i];
  4519. if (item.isVisible(range)) {
  4520. if (!item.displayed) item.show();
  4521. // reposition item horizontally
  4522. item.repositionX();
  4523. if (newVisibleItems.indexOf(item) == -1) {
  4524. newVisibleItems.push(item);
  4525. }
  4526. }
  4527. else {
  4528. break;
  4529. }
  4530. }
  4531. // and up
  4532. for (var i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  4533. item = orderedItems.byEnd[i];
  4534. if (item.isVisible(range)) {
  4535. if (!item.displayed) item.show();
  4536. // reposition item horizontally
  4537. item.repositionX();
  4538. if (newVisibleItems.indexOf(item) == -1) {
  4539. newVisibleItems.push(item);
  4540. }
  4541. }
  4542. else {
  4543. break;
  4544. }
  4545. }
  4546. }
  4547. if (!this.systemLoaded) {
  4548. // initial setup is brute force all the ranged items;
  4549. // TODO: implement this in the onUpdate function to only load the new items.
  4550. for (var i = 0; i < orderedItems.byEnd.length; i++) {
  4551. item = orderedItems.byEnd[i];
  4552. if (item.isVisible(range)) {
  4553. if (!item.displayed) item.show();
  4554. // reposition item horizontally
  4555. item.repositionX();
  4556. newVisibleItems.push(item);
  4557. }
  4558. else {
  4559. if (item.displayed) item.hide();
  4560. }
  4561. }
  4562. this.systemLoaded = true;
  4563. }
  4564. this.visibleItems = newVisibleItems;
  4565. // reposition visible items vertically
  4566. //this.stack.order(this.visibleItems); // TODO: improve ordering
  4567. var force = this.stackDirty || zoomed; // force re-stacking of all items if true
  4568. this.stack.stack(this.visibleItems, force);
  4569. this.stackDirty = false;
  4570. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  4571. this.visibleItems[i].repositionY();
  4572. }
  4573. // recalculate the height of the itemset
  4574. var marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.itemOptions.margin.axis,
  4575. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.itemOptions.margin.item,
  4576. height;
  4577. // determine the height from the stacked items
  4578. var visibleItems = this.visibleItems;
  4579. if (visibleItems.length) {
  4580. var min = visibleItems[0].top;
  4581. var max = visibleItems[0].top + visibleItems[0].height;
  4582. util.forEach(visibleItems, function (item) {
  4583. min = Math.min(min, item.top);
  4584. max = Math.max(max, (item.top + item.height));
  4585. });
  4586. height = (max - min) + marginAxis + marginItem;
  4587. }
  4588. else {
  4589. height = marginAxis + marginItem;
  4590. }
  4591. // reposition frame
  4592. frame.style.left = asSize(options.left, '');
  4593. frame.style.right = asSize(options.right, '');
  4594. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4595. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4596. frame.style.width = asSize(options.width, '100%');
  4597. frame.style.height = asSize(height);
  4598. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4599. // calculate actual size and position
  4600. this.top = frame.offsetTop;
  4601. this.left = frame.offsetLeft;
  4602. this.width = frame.offsetWidth;
  4603. this.height = height;
  4604. // reposition axis
  4605. this.dom.axis.style.left = asSize(options.left, '0');
  4606. this.dom.axis.style.right = asSize(options.right, '');
  4607. this.dom.axis.style.width = asSize(options.width, '100%');
  4608. this.dom.axis.style.height = asSize(0);
  4609. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4610. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4611. return this._isResized();
  4612. };
  4613. /**
  4614. * Get the foreground container element
  4615. * @return {HTMLElement} foreground
  4616. */
  4617. ItemSet.prototype.getForeground = function getForeground() {
  4618. return this.dom.foreground;
  4619. };
  4620. /**
  4621. * Get the background container element
  4622. * @return {HTMLElement} background
  4623. */
  4624. ItemSet.prototype.getBackground = function getBackground() {
  4625. return this.dom.background;
  4626. };
  4627. /**
  4628. * Get the axis container element
  4629. * @return {HTMLElement} axis
  4630. */
  4631. ItemSet.prototype.getAxis = function getAxis() {
  4632. return this.dom.axis;
  4633. };
  4634. /**
  4635. * Set items
  4636. * @param {vis.DataSet | null} items
  4637. */
  4638. ItemSet.prototype.setItems = function setItems(items) {
  4639. var me = this,
  4640. ids,
  4641. oldItemsData = this.itemsData;
  4642. // replace the dataset
  4643. if (!items) {
  4644. this.itemsData = null;
  4645. }
  4646. else if (items instanceof DataSet || items instanceof DataView) {
  4647. this.itemsData = items;
  4648. }
  4649. else {
  4650. throw new TypeError('Data must be an instance of DataSet');
  4651. }
  4652. if (oldItemsData) {
  4653. // unsubscribe from old dataset
  4654. util.forEach(this.listeners, function (callback, event) {
  4655. oldItemsData.unsubscribe(event, callback);
  4656. });
  4657. // remove all drawn items
  4658. ids = oldItemsData.getIds();
  4659. this._onRemove(ids);
  4660. }
  4661. if (this.itemsData) {
  4662. // subscribe to new dataset
  4663. var id = this.id;
  4664. util.forEach(this.listeners, function (callback, event) {
  4665. me.itemsData.on(event, callback, id);
  4666. });
  4667. // draw all new items
  4668. ids = this.itemsData.getIds();
  4669. this._onAdd(ids);
  4670. }
  4671. };
  4672. /**
  4673. * Get the current items items
  4674. * @returns {vis.DataSet | null}
  4675. */
  4676. ItemSet.prototype.getItems = function getItems() {
  4677. return this.itemsData;
  4678. };
  4679. /**
  4680. * Remove an item by its id
  4681. * @param {String | Number} id
  4682. */
  4683. ItemSet.prototype.removeItem = function removeItem (id) {
  4684. var item = this.itemsData.get(id),
  4685. dataset = this._myDataSet();
  4686. if (item) {
  4687. // confirm deletion
  4688. this.options.onRemove(item, function (item) {
  4689. if (item) {
  4690. // remove by id here, it is possible that an item has no id defined
  4691. // itself, so better not delete by the item itself
  4692. dataset.remove(id);
  4693. }
  4694. });
  4695. }
  4696. };
  4697. /**
  4698. * Handle updated items
  4699. * @param {Number[]} ids
  4700. * @private
  4701. */
  4702. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4703. var me = this,
  4704. items = this.items,
  4705. itemOptions = this.itemOptions;
  4706. ids.forEach(function (id) {
  4707. var itemData = me.itemsData.get(id),
  4708. item = items[id],
  4709. type = itemData.type ||
  4710. (itemData.start && itemData.end && 'range') ||
  4711. me.options.type ||
  4712. 'box';
  4713. var constructor = ItemSet.types[type];
  4714. if (item) {
  4715. // update item
  4716. if (!constructor || !(item instanceof constructor)) {
  4717. // item type has changed, hide and delete the item
  4718. item.hide();
  4719. item = null;
  4720. }
  4721. else {
  4722. item.data = itemData; // TODO: create a method item.setData ?
  4723. }
  4724. }
  4725. if (!item) {
  4726. // create item
  4727. if (constructor) {
  4728. item = new constructor(me, itemData, me.options, itemOptions);
  4729. item.id = id;
  4730. }
  4731. else {
  4732. throw new TypeError('Unknown item type "' + type + '"');
  4733. }
  4734. }
  4735. me.items[id] = item;
  4736. });
  4737. this._order();
  4738. this.systemLoaded = false;
  4739. this.stackDirty = true; // force re-stacking of all items next repaint
  4740. this.emit('change');
  4741. };
  4742. /**
  4743. * Handle added items
  4744. * @param {Number[]} ids
  4745. * @private
  4746. */
  4747. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4748. /**
  4749. * Handle removed items
  4750. * @param {Number[]} ids
  4751. * @private
  4752. */
  4753. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4754. var count = 0;
  4755. var me = this;
  4756. ids.forEach(function (id) {
  4757. var item = me.items[id];
  4758. if (item) {
  4759. count++;
  4760. item.hide();
  4761. delete me.items[id];
  4762. // remove from visible items
  4763. var index = me.visibleItems.indexOf(me.item);
  4764. me.visibleItems.splice(index,1);
  4765. // remove from selection
  4766. index = me.selection.indexOf(id);
  4767. if (index != -1) me.selection.splice(index, 1);
  4768. }
  4769. });
  4770. if (count) {
  4771. // update order
  4772. this._order();
  4773. this.stackDirty = true; // force re-stacking of all items next repaint
  4774. this.emit('change');
  4775. }
  4776. };
  4777. /**
  4778. * Order the items
  4779. * @private
  4780. */
  4781. ItemSet.prototype._order = function _order() {
  4782. var array = util.toArray(this.items);
  4783. this.orderedItems.byStart = array;
  4784. this.orderedItems.byEnd = this._constructByEndArray(array);
  4785. //this.orderedItems.byEnd = [].concat(array); // this copies the array
  4786. // reorder the items
  4787. this.stack.orderByStart(this.orderedItems.byStart);
  4788. this.stack.orderByEnd(this.orderedItems.byEnd);
  4789. };
  4790. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  4791. var endArray = [];
  4792. for (var i = 0; i < array.length; i++) {
  4793. if (array[i] instanceof ItemRange) {
  4794. endArray.push(array[i]);
  4795. }
  4796. }
  4797. return endArray;
  4798. };
  4799. /**
  4800. * Start dragging the selected events
  4801. * @param {Event} event
  4802. * @private
  4803. */
  4804. ItemSet.prototype._onDragStart = function (event) {
  4805. if (!this.options.editable) {
  4806. return;
  4807. }
  4808. var item = ItemSet.itemFromTarget(event),
  4809. me = this;
  4810. if (item && item.selected) {
  4811. var dragLeftItem = event.target.dragLeftItem;
  4812. var dragRightItem = event.target.dragRightItem;
  4813. if (dragLeftItem) {
  4814. this.touchParams.itemProps = [{
  4815. item: dragLeftItem,
  4816. start: item.data.start.valueOf()
  4817. }];
  4818. }
  4819. else if (dragRightItem) {
  4820. this.touchParams.itemProps = [{
  4821. item: dragRightItem,
  4822. end: item.data.end.valueOf()
  4823. }];
  4824. }
  4825. else {
  4826. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4827. var item = me.items[id];
  4828. var props = {
  4829. item: item
  4830. };
  4831. if ('start' in item.data) {
  4832. props.start = item.data.start.valueOf()
  4833. }
  4834. if ('end' in item.data) {
  4835. props.end = item.data.end.valueOf()
  4836. }
  4837. return props;
  4838. });
  4839. }
  4840. event.stopPropagation();
  4841. }
  4842. };
  4843. /**
  4844. * Drag selected items
  4845. * @param {Event} event
  4846. * @private
  4847. */
  4848. ItemSet.prototype._onDrag = function (event) {
  4849. if (this.touchParams.itemProps) {
  4850. var snap = this.options.snap || null,
  4851. deltaX = event.gesture.deltaX,
  4852. scale = (this.width / (this.range.end - this.range.start)),
  4853. offset = deltaX / scale;
  4854. // move
  4855. this.touchParams.itemProps.forEach(function (props) {
  4856. if ('start' in props) {
  4857. var start = new Date(props.start + offset);
  4858. props.item.data.start = snap ? snap(start) : start;
  4859. }
  4860. if ('end' in props) {
  4861. var end = new Date(props.end + offset);
  4862. props.item.data.end = snap ? snap(end) : end;
  4863. }
  4864. });
  4865. // TODO: implement onMoving handler
  4866. // TODO: implement dragging from one group to another
  4867. this.stackDirty = true; // force re-stacking of all items next repaint
  4868. this.emit('change');
  4869. event.stopPropagation();
  4870. }
  4871. };
  4872. /**
  4873. * End of dragging selected items
  4874. * @param {Event} event
  4875. * @private
  4876. */
  4877. ItemSet.prototype._onDragEnd = function (event) {
  4878. if (this.touchParams.itemProps) {
  4879. // prepare a change set for the changed items
  4880. var changes = [],
  4881. me = this,
  4882. dataset = this._myDataSet();
  4883. this.touchParams.itemProps.forEach(function (props) {
  4884. var id = props.item.id,
  4885. item = me.itemsData.get(id);
  4886. var changed = false;
  4887. if ('start' in props.item.data) {
  4888. changed = (props.start != props.item.data.start.valueOf());
  4889. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  4890. }
  4891. if ('end' in props.item.data) {
  4892. changed = changed || (props.end != props.item.data.end.valueOf());
  4893. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  4894. }
  4895. // only apply changes when start or end is actually changed
  4896. if (changed) {
  4897. me.options.onMove(item, function (item) {
  4898. if (item) {
  4899. // apply changes
  4900. item[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  4901. changes.push(item);
  4902. }
  4903. else {
  4904. // restore original values
  4905. if ('start' in props) props.item.data.start = props.start;
  4906. if ('end' in props) props.item.data.end = props.end;
  4907. me.stackDirty = true; // force re-stacking of all items next repaint
  4908. me.emit('change');
  4909. }
  4910. });
  4911. }
  4912. });
  4913. this.touchParams.itemProps = null;
  4914. // apply the changes to the data (if there are changes)
  4915. if (changes.length) {
  4916. dataset.update(changes);
  4917. }
  4918. event.stopPropagation();
  4919. }
  4920. };
  4921. /**
  4922. * Find an item from an event target:
  4923. * searches for the attribute 'timeline-item' in the event target's element tree
  4924. * @param {Event} event
  4925. * @return {Item | null} item
  4926. */
  4927. ItemSet.itemFromTarget = function itemFromTarget (event) {
  4928. var target = event.target;
  4929. while (target) {
  4930. if (target.hasOwnProperty('timeline-item')) {
  4931. return target['timeline-item'];
  4932. }
  4933. target = target.parentNode;
  4934. }
  4935. return null;
  4936. };
  4937. /**
  4938. * Find the ItemSet from an event target:
  4939. * searches for the attribute 'timeline-itemset' in the event target's element tree
  4940. * @param {Event} event
  4941. * @return {ItemSet | null} item
  4942. */
  4943. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  4944. var target = event.target;
  4945. while (target) {
  4946. if (target.hasOwnProperty('timeline-itemset')) {
  4947. return target['timeline-itemset'];
  4948. }
  4949. target = target.parentNode;
  4950. }
  4951. return null;
  4952. };
  4953. /**
  4954. * Find the DataSet to which this ItemSet is connected
  4955. * @returns {null | DataSet} dataset
  4956. * @private
  4957. */
  4958. ItemSet.prototype._myDataSet = function _myDataSet() {
  4959. // find the root DataSet
  4960. var dataset = this.itemsData;
  4961. while (dataset instanceof DataView) {
  4962. dataset = dataset.data;
  4963. }
  4964. return dataset;
  4965. };
  4966. /**
  4967. * @constructor Item
  4968. * @param {ItemSet} parent
  4969. * @param {Object} data Object containing (optional) parameters type,
  4970. * start, end, content, group, className.
  4971. * @param {Object} [options] Options to set initial property values
  4972. * @param {Object} [defaultOptions] default options
  4973. * // TODO: describe available options
  4974. */
  4975. function Item (parent, data, options, defaultOptions) {
  4976. this.parent = parent;
  4977. this.data = data;
  4978. this.dom = null;
  4979. this.options = options || {};
  4980. this.defaultOptions = defaultOptions || {};
  4981. this.selected = false;
  4982. this.displayed = false;
  4983. this.dirty = true;
  4984. this.top = null;
  4985. this.left = null;
  4986. this.width = null;
  4987. this.height = null;
  4988. }
  4989. /**
  4990. * Select current item
  4991. */
  4992. Item.prototype.select = function select() {
  4993. this.selected = true;
  4994. if (this.displayed) this.repaint();
  4995. };
  4996. /**
  4997. * Unselect current item
  4998. */
  4999. Item.prototype.unselect = function unselect() {
  5000. this.selected = false;
  5001. if (this.displayed) this.repaint();
  5002. };
  5003. /**
  5004. * Show the Item in the DOM (when not already visible)
  5005. * @return {Boolean} changed
  5006. */
  5007. Item.prototype.show = function show() {
  5008. return false;
  5009. };
  5010. /**
  5011. * Hide the Item from the DOM (when visible)
  5012. * @return {Boolean} changed
  5013. */
  5014. Item.prototype.hide = function hide() {
  5015. return false;
  5016. };
  5017. /**
  5018. * Repaint the item
  5019. */
  5020. Item.prototype.repaint = function repaint() {
  5021. // should be implemented by the item
  5022. };
  5023. /**
  5024. * Reposition the Item horizontally
  5025. */
  5026. Item.prototype.repositionX = function repositionX() {
  5027. // should be implemented by the item
  5028. };
  5029. /**
  5030. * Reposition the Item vertically
  5031. */
  5032. Item.prototype.repositionY = function repositionY() {
  5033. // should be implemented by the item
  5034. };
  5035. /**
  5036. * Repaint a delete button on the top right of the item when the item is selected
  5037. * @param {HTMLElement} anchor
  5038. * @private
  5039. */
  5040. Item.prototype._repaintDeleteButton = function (anchor) {
  5041. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5042. // create and show button
  5043. var parent = this.parent;
  5044. var id = this.id;
  5045. var deleteButton = document.createElement('div');
  5046. deleteButton.className = 'delete';
  5047. deleteButton.title = 'Delete this item';
  5048. Hammer(deleteButton, {
  5049. preventDefault: true
  5050. }).on('tap', function (event) {
  5051. parent.removeItem(id);
  5052. event.stopPropagation();
  5053. });
  5054. anchor.appendChild(deleteButton);
  5055. this.dom.deleteButton = deleteButton;
  5056. }
  5057. else if (!this.selected && this.dom.deleteButton) {
  5058. // remove button
  5059. if (this.dom.deleteButton.parentNode) {
  5060. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5061. }
  5062. this.dom.deleteButton = null;
  5063. }
  5064. };
  5065. /**
  5066. * @constructor ItemBox
  5067. * @extends Item
  5068. * @param {ItemSet} parent
  5069. * @param {Object} data Object containing parameters start
  5070. * content, className.
  5071. * @param {Object} [options] Options to set initial property values
  5072. * @param {Object} [defaultOptions] default options
  5073. * // TODO: describe available options
  5074. */
  5075. function ItemBox (parent, data, options, defaultOptions) {
  5076. this.props = {
  5077. dot: {
  5078. width: 0,
  5079. height: 0
  5080. },
  5081. line: {
  5082. width: 0,
  5083. height: 0
  5084. }
  5085. };
  5086. // validate data
  5087. if (data) {
  5088. if (data.start == undefined) {
  5089. throw new Error('Property "start" missing in item ' + data);
  5090. }
  5091. }
  5092. Item.call(this, parent, data, options, defaultOptions);
  5093. }
  5094. ItemBox.prototype = new Item (null, null);
  5095. /**
  5096. * Check whether this item is visible inside given range
  5097. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5098. * @returns {boolean} True if visible
  5099. */
  5100. ItemBox.prototype.isVisible = function isVisible (range) {
  5101. // determine visibility
  5102. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5103. var interval = (range.end - range.start) / 4;
  5104. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5105. };
  5106. /**
  5107. * Repaint the item
  5108. */
  5109. ItemBox.prototype.repaint = function repaint() {
  5110. var dom = this.dom;
  5111. if (!dom) {
  5112. // create DOM
  5113. this.dom = {};
  5114. dom = this.dom;
  5115. // create main box
  5116. dom.box = document.createElement('DIV');
  5117. // contents box (inside the background box). used for making margins
  5118. dom.content = document.createElement('DIV');
  5119. dom.content.className = 'content';
  5120. dom.box.appendChild(dom.content);
  5121. // line to axis
  5122. dom.line = document.createElement('DIV');
  5123. dom.line.className = 'line';
  5124. // dot on axis
  5125. dom.dot = document.createElement('DIV');
  5126. dom.dot.className = 'dot';
  5127. // attach this item as attribute
  5128. dom.box['timeline-item'] = this;
  5129. }
  5130. // append DOM to parent DOM
  5131. if (!this.parent) {
  5132. throw new Error('Cannot repaint item: no parent attached');
  5133. }
  5134. if (!dom.box.parentNode) {
  5135. var foreground = this.parent.getForeground();
  5136. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5137. foreground.appendChild(dom.box);
  5138. }
  5139. if (!dom.line.parentNode) {
  5140. var background = this.parent.getBackground();
  5141. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5142. background.appendChild(dom.line);
  5143. }
  5144. if (!dom.dot.parentNode) {
  5145. var axis = this.parent.getAxis();
  5146. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5147. axis.appendChild(dom.dot);
  5148. }
  5149. this.displayed = true;
  5150. // update contents
  5151. if (this.data.content != this.content) {
  5152. this.content = this.data.content;
  5153. if (this.content instanceof Element) {
  5154. dom.content.innerHTML = '';
  5155. dom.content.appendChild(this.content);
  5156. }
  5157. else if (this.data.content != undefined) {
  5158. dom.content.innerHTML = this.content;
  5159. }
  5160. else {
  5161. throw new Error('Property "content" missing in item ' + this.data.id);
  5162. }
  5163. this.dirty = true;
  5164. }
  5165. // update class
  5166. var className = (this.data.className? ' ' + this.data.className : '') +
  5167. (this.selected ? ' selected' : '');
  5168. if (this.className != className) {
  5169. this.className = className;
  5170. dom.box.className = 'item box' + className;
  5171. dom.line.className = 'item line' + className;
  5172. dom.dot.className = 'item dot' + className;
  5173. this.dirty = true;
  5174. }
  5175. // recalculate size
  5176. if (this.dirty) {
  5177. this.props.dot.height = dom.dot.offsetHeight;
  5178. this.props.dot.width = dom.dot.offsetWidth;
  5179. this.props.line.width = dom.line.offsetWidth;
  5180. this.width = dom.box.offsetWidth;
  5181. this.height = dom.box.offsetHeight;
  5182. this.dirty = false;
  5183. }
  5184. this._repaintDeleteButton(dom.box);
  5185. };
  5186. /**
  5187. * Show the item in the DOM (when not already displayed). The items DOM will
  5188. * be created when needed.
  5189. */
  5190. ItemBox.prototype.show = function show() {
  5191. if (!this.displayed) {
  5192. this.repaint();
  5193. }
  5194. };
  5195. /**
  5196. * Hide the item from the DOM (when visible)
  5197. */
  5198. ItemBox.prototype.hide = function hide() {
  5199. if (this.displayed) {
  5200. var dom = this.dom;
  5201. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5202. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5203. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5204. this.top = null;
  5205. this.left = null;
  5206. this.displayed = false;
  5207. }
  5208. };
  5209. /**
  5210. * Reposition the item horizontally
  5211. * @Override
  5212. */
  5213. ItemBox.prototype.repositionX = function repositionX() {
  5214. var start = this.defaultOptions.toScreen(this.data.start),
  5215. align = this.options.align || this.defaultOptions.align,
  5216. left,
  5217. box = this.dom.box,
  5218. line = this.dom.line,
  5219. dot = this.dom.dot;
  5220. // calculate left position of the box
  5221. if (align == 'right') {
  5222. this.left = start - this.width;
  5223. }
  5224. else if (align == 'left') {
  5225. this.left = start;
  5226. }
  5227. else {
  5228. // default or 'center'
  5229. this.left = start - this.width / 2;
  5230. }
  5231. // reposition box
  5232. box.style.left = this.left + 'px';
  5233. // reposition line
  5234. line.style.left = (start - this.props.line.width / 2) + 'px';
  5235. // reposition dot
  5236. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5237. };
  5238. /**
  5239. * Reposition the item vertically
  5240. * @Override
  5241. */
  5242. ItemBox.prototype.repositionY = function repositionY () {
  5243. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5244. box = this.dom.box,
  5245. line = this.dom.line,
  5246. dot = this.dom.dot;
  5247. if (orientation == 'top') {
  5248. box.style.top = (this.top || 0) + 'px';
  5249. box.style.bottom = '';
  5250. line.style.top = '0';
  5251. line.style.bottom = '';
  5252. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5253. }
  5254. else { // orientation 'bottom'
  5255. box.style.top = '';
  5256. box.style.bottom = (this.top || 0) + 'px';
  5257. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5258. line.style.bottom = '0';
  5259. line.style.height = '';
  5260. }
  5261. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5262. };
  5263. /**
  5264. * @constructor ItemPoint
  5265. * @extends Item
  5266. * @param {ItemSet} parent
  5267. * @param {Object} data Object containing parameters start
  5268. * content, className.
  5269. * @param {Object} [options] Options to set initial property values
  5270. * @param {Object} [defaultOptions] default options
  5271. * // TODO: describe available options
  5272. */
  5273. function ItemPoint (parent, data, options, defaultOptions) {
  5274. this.props = {
  5275. dot: {
  5276. top: 0,
  5277. width: 0,
  5278. height: 0
  5279. },
  5280. content: {
  5281. height: 0,
  5282. marginLeft: 0
  5283. }
  5284. };
  5285. // validate data
  5286. if (data) {
  5287. if (data.start == undefined) {
  5288. throw new Error('Property "start" missing in item ' + data);
  5289. }
  5290. }
  5291. Item.call(this, parent, data, options, defaultOptions);
  5292. }
  5293. ItemPoint.prototype = new Item (null, null);
  5294. /**
  5295. * Check whether this item is visible inside given range
  5296. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5297. * @returns {boolean} True if visible
  5298. */
  5299. ItemPoint.prototype.isVisible = function isVisible (range) {
  5300. // determine visibility
  5301. var interval = (range.end - range.start);
  5302. return (this.data.start > range.start - interval) && (this.data.start < range.end);
  5303. }
  5304. /**
  5305. * Repaint the item
  5306. */
  5307. ItemPoint.prototype.repaint = function repaint() {
  5308. var dom = this.dom;
  5309. if (!dom) {
  5310. // create DOM
  5311. this.dom = {};
  5312. dom = this.dom;
  5313. // background box
  5314. dom.point = document.createElement('div');
  5315. // className is updated in repaint()
  5316. // contents box, right from the dot
  5317. dom.content = document.createElement('div');
  5318. dom.content.className = 'content';
  5319. dom.point.appendChild(dom.content);
  5320. // dot at start
  5321. dom.dot = document.createElement('div');
  5322. dom.dot.className = 'dot';
  5323. dom.point.appendChild(dom.dot);
  5324. // attach this item as attribute
  5325. dom.point['timeline-item'] = this;
  5326. }
  5327. // append DOM to parent DOM
  5328. if (!this.parent) {
  5329. throw new Error('Cannot repaint item: no parent attached');
  5330. }
  5331. if (!dom.point.parentNode) {
  5332. var foreground = this.parent.getForeground();
  5333. if (!foreground) {
  5334. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5335. }
  5336. foreground.appendChild(dom.point);
  5337. }
  5338. this.displayed = true;
  5339. // update contents
  5340. if (this.data.content != this.content) {
  5341. this.content = this.data.content;
  5342. if (this.content instanceof Element) {
  5343. dom.content.innerHTML = '';
  5344. dom.content.appendChild(this.content);
  5345. }
  5346. else if (this.data.content != undefined) {
  5347. dom.content.innerHTML = this.content;
  5348. }
  5349. else {
  5350. throw new Error('Property "content" missing in item ' + this.data.id);
  5351. }
  5352. this.dirty = true;
  5353. }
  5354. // update class
  5355. var className = (this.data.className? ' ' + this.data.className : '') +
  5356. (this.selected ? ' selected' : '');
  5357. if (this.className != className) {
  5358. this.className = className;
  5359. dom.point.className = 'item point' + className;
  5360. this.dirty = true;
  5361. }
  5362. // recalculate size
  5363. if (this.dirty) {
  5364. this.width = dom.point.offsetWidth;
  5365. this.height = dom.point.offsetHeight;
  5366. this.props.dot.width = dom.dot.offsetWidth;
  5367. this.props.dot.height = dom.dot.offsetHeight;
  5368. this.props.content.height = dom.content.offsetHeight;
  5369. // resize contents
  5370. dom.content.style.marginLeft = 1.5 * this.props.dot.width + 'px';
  5371. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5372. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5373. this.dirty = false;
  5374. }
  5375. this._repaintDeleteButton(dom.point);
  5376. };
  5377. /**
  5378. * Show the item in the DOM (when not already visible). The items DOM will
  5379. * be created when needed.
  5380. */
  5381. ItemPoint.prototype.show = function show() {
  5382. if (!this.displayed) {
  5383. this.repaint();
  5384. }
  5385. };
  5386. /**
  5387. * Hide the item from the DOM (when visible)
  5388. */
  5389. ItemPoint.prototype.hide = function hide() {
  5390. if (this.displayed) {
  5391. if (this.dom.point.parentNode) {
  5392. this.dom.point.parentNode.removeChild(this.dom.point);
  5393. }
  5394. this.top = null;
  5395. this.left = null;
  5396. this.displayed = false;
  5397. }
  5398. };
  5399. /**
  5400. * Reposition the item horizontally
  5401. * @Override
  5402. */
  5403. ItemPoint.prototype.repositionX = function repositionX() {
  5404. var start = this.defaultOptions.toScreen(this.data.start);
  5405. this.left = start - this.props.dot.width / 2;
  5406. // reposition point
  5407. this.dom.point.style.left = this.left + 'px';
  5408. };
  5409. /**
  5410. * Reposition the item vertically
  5411. * @Override
  5412. */
  5413. ItemPoint.prototype.repositionY = function repositionY () {
  5414. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5415. point = this.dom.point;
  5416. if (orientation == 'top') {
  5417. point.style.top = this.top + 'px';
  5418. point.style.bottom = '';
  5419. }
  5420. else {
  5421. point.style.top = '';
  5422. point.style.bottom = this.top + 'px';
  5423. }
  5424. }
  5425. /**
  5426. * @constructor ItemRange
  5427. * @extends Item
  5428. * @param {ItemSet} parent
  5429. * @param {Object} data Object containing parameters start, end
  5430. * content, className.
  5431. * @param {Object} [options] Options to set initial property values
  5432. * @param {Object} [defaultOptions] default options
  5433. * // TODO: describe available options
  5434. */
  5435. function ItemRange (parent, data, options, defaultOptions) {
  5436. this.props = {
  5437. content: {
  5438. width: 0
  5439. }
  5440. };
  5441. // validate data
  5442. if (data) {
  5443. if (data.start == undefined) {
  5444. throw new Error('Property "start" missing in item ' + data.id);
  5445. }
  5446. if (data.end == undefined) {
  5447. throw new Error('Property "end" missing in item ' + data.id);
  5448. }
  5449. }
  5450. Item.call(this, parent, data, options, defaultOptions);
  5451. }
  5452. ItemRange.prototype = new Item (null, null);
  5453. ItemRange.prototype.baseClassName = 'item range';
  5454. /**
  5455. * Check whether this item is visible inside given range
  5456. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5457. * @returns {boolean} True if visible
  5458. */
  5459. ItemRange.prototype.isVisible = function isVisible (range) {
  5460. // determine visibility
  5461. return (this.data.start < range.end) && (this.data.end > range.start);
  5462. };
  5463. /**
  5464. * Repaint the item
  5465. */
  5466. ItemRange.prototype.repaint = function repaint() {
  5467. var dom = this.dom;
  5468. if (!dom) {
  5469. // create DOM
  5470. this.dom = {};
  5471. dom = this.dom;
  5472. // background box
  5473. dom.box = document.createElement('div');
  5474. // className is updated in repaint()
  5475. // contents box
  5476. dom.content = document.createElement('div');
  5477. dom.content.className = 'content';
  5478. dom.box.appendChild(dom.content);
  5479. // attach this item as attribute
  5480. dom.box['timeline-item'] = this;
  5481. }
  5482. // append DOM to parent DOM
  5483. if (!this.parent) {
  5484. throw new Error('Cannot repaint item: no parent attached');
  5485. }
  5486. if (!dom.box.parentNode) {
  5487. var foreground = this.parent.getForeground();
  5488. if (!foreground) {
  5489. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5490. }
  5491. foreground.appendChild(dom.box);
  5492. }
  5493. this.displayed = true;
  5494. // update contents
  5495. if (this.data.content != this.content) {
  5496. this.content = this.data.content;
  5497. if (this.content instanceof Element) {
  5498. dom.content.innerHTML = '';
  5499. dom.content.appendChild(this.content);
  5500. }
  5501. else if (this.data.content != undefined) {
  5502. dom.content.innerHTML = this.content;
  5503. }
  5504. else {
  5505. throw new Error('Property "content" missing in item ' + this.data.id);
  5506. }
  5507. this.dirty = true;
  5508. }
  5509. // update class
  5510. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5511. (this.selected ? ' selected' : '');
  5512. if (this.className != className) {
  5513. this.className = className;
  5514. dom.box.className = this.baseClassName + className;
  5515. this.dirty = true;
  5516. }
  5517. // recalculate size
  5518. if (this.dirty) {
  5519. this.props.content.width = this.dom.content.offsetWidth;
  5520. this.height = this.dom.box.offsetHeight;
  5521. this.dirty = false;
  5522. }
  5523. this._repaintDeleteButton(dom.box);
  5524. this._repaintDragLeft();
  5525. this._repaintDragRight();
  5526. };
  5527. /**
  5528. * Show the item in the DOM (when not already visible). The items DOM will
  5529. * be created when needed.
  5530. */
  5531. ItemRange.prototype.show = function show() {
  5532. if (!this.displayed) {
  5533. this.repaint();
  5534. }
  5535. };
  5536. /**
  5537. * Hide the item from the DOM (when visible)
  5538. * @return {Boolean} changed
  5539. */
  5540. ItemRange.prototype.hide = function hide() {
  5541. if (this.displayed) {
  5542. var box = this.dom.box;
  5543. if (box.parentNode) {
  5544. box.parentNode.removeChild(box);
  5545. }
  5546. this.top = null;
  5547. this.left = null;
  5548. this.displayed = false;
  5549. }
  5550. };
  5551. /**
  5552. * Reposition the item horizontally
  5553. * @Override
  5554. */
  5555. ItemRange.prototype.repositionX = function repositionX() {
  5556. var props = this.props,
  5557. parentWidth = this.parent.width,
  5558. start = this.defaultOptions.toScreen(this.data.start),
  5559. end = this.defaultOptions.toScreen(this.data.end),
  5560. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5561. contentLeft;
  5562. // limit the width of the this, as browsers cannot draw very wide divs
  5563. if (start < -parentWidth) {
  5564. start = -parentWidth;
  5565. }
  5566. if (end > 2 * parentWidth) {
  5567. end = 2 * parentWidth;
  5568. }
  5569. // when range exceeds left of the window, position the contents at the left of the visible area
  5570. if (start < 0) {
  5571. contentLeft = Math.min(-start,
  5572. (end - start - props.content.width - 2 * padding));
  5573. // TODO: remove the need for options.padding. it's terrible.
  5574. }
  5575. else {
  5576. contentLeft = 0;
  5577. }
  5578. this.left = start;
  5579. this.width = Math.max(end - start, 1);
  5580. this.dom.box.style.left = this.left + 'px';
  5581. this.dom.box.style.width = this.width + 'px';
  5582. this.dom.content.style.left = contentLeft + 'px';
  5583. };
  5584. /**
  5585. * Reposition the item vertically
  5586. * @Override
  5587. */
  5588. ItemRange.prototype.repositionY = function repositionY() {
  5589. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5590. box = this.dom.box;
  5591. if (orientation == 'top') {
  5592. box.style.top = this.top + 'px';
  5593. box.style.bottom = '';
  5594. }
  5595. else {
  5596. box.style.top = '';
  5597. box.style.bottom = this.top + 'px';
  5598. }
  5599. };
  5600. /**
  5601. * Repaint a drag area on the left side of the range when the range is selected
  5602. * @private
  5603. */
  5604. ItemRange.prototype._repaintDragLeft = function () {
  5605. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  5606. // create and show drag area
  5607. var dragLeft = document.createElement('div');
  5608. dragLeft.className = 'drag-left';
  5609. dragLeft.dragLeftItem = this;
  5610. // TODO: this should be redundant?
  5611. Hammer(dragLeft, {
  5612. preventDefault: true
  5613. }).on('drag', function () {
  5614. //console.log('drag left')
  5615. });
  5616. this.dom.box.appendChild(dragLeft);
  5617. this.dom.dragLeft = dragLeft;
  5618. }
  5619. else if (!this.selected && this.dom.dragLeft) {
  5620. // delete drag area
  5621. if (this.dom.dragLeft.parentNode) {
  5622. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5623. }
  5624. this.dom.dragLeft = null;
  5625. }
  5626. };
  5627. /**
  5628. * Repaint a drag area on the right side of the range when the range is selected
  5629. * @private
  5630. */
  5631. ItemRange.prototype._repaintDragRight = function () {
  5632. if (this.selected && this.options.editable && !this.dom.dragRight) {
  5633. // create and show drag area
  5634. var dragRight = document.createElement('div');
  5635. dragRight.className = 'drag-right';
  5636. dragRight.dragRightItem = this;
  5637. // TODO: this should be redundant?
  5638. Hammer(dragRight, {
  5639. preventDefault: true
  5640. }).on('drag', function () {
  5641. //console.log('drag right')
  5642. });
  5643. this.dom.box.appendChild(dragRight);
  5644. this.dom.dragRight = dragRight;
  5645. }
  5646. else if (!this.selected && this.dom.dragRight) {
  5647. // delete drag area
  5648. if (this.dom.dragRight.parentNode) {
  5649. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5650. }
  5651. this.dom.dragRight = null;
  5652. }
  5653. };
  5654. /**
  5655. * @constructor ItemRangeOverflow
  5656. * @extends ItemRange
  5657. * @param {ItemSet} parent
  5658. * @param {Object} data Object containing parameters start, end
  5659. * content, className.
  5660. * @param {Object} [options] Options to set initial property values
  5661. * @param {Object} [defaultOptions] default options
  5662. * // TODO: describe available options
  5663. */
  5664. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5665. this.props = {
  5666. content: {
  5667. left: 0,
  5668. width: 0
  5669. }
  5670. };
  5671. ItemRange.call(this, parent, data, options, defaultOptions);
  5672. }
  5673. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5674. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5675. /**
  5676. * Reposition the item horizontally
  5677. * @Override
  5678. */
  5679. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5680. var parentWidth = this.parent.width,
  5681. start = this.defaultOptions.toScreen(this.data.start),
  5682. end = this.defaultOptions.toScreen(this.data.end),
  5683. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5684. contentLeft;
  5685. // limit the width of the this, as browsers cannot draw very wide divs
  5686. if (start < -parentWidth) {
  5687. start = -parentWidth;
  5688. }
  5689. if (end > 2 * parentWidth) {
  5690. end = 2 * parentWidth;
  5691. }
  5692. // when range exceeds left of the window, position the contents at the left of the visible area
  5693. contentLeft = Math.max(-start, 0);
  5694. this.left = start;
  5695. var boxWidth = Math.max(end - start, 1);
  5696. this.width = (this.props.content.width < boxWidth) ?
  5697. boxWidth :
  5698. start + contentLeft + this.props.content.width;
  5699. this.dom.box.style.left = this.left + 'px';
  5700. this.dom.box.style.width = boxWidth + 'px';
  5701. this.dom.content.style.left = contentLeft + 'px';
  5702. };
  5703. /**
  5704. * @constructor Group
  5705. * @param {Panel} groupPanel
  5706. * @param {Panel} labelPanel
  5707. * @param {Panel} backgroundPanel
  5708. * @param {Panel} axisPanel
  5709. * @param {Number | String} groupId
  5710. * @param {Object} [options] Options to set initial property values
  5711. * // TODO: describe available options
  5712. * @extends Component
  5713. */
  5714. function Group (groupPanel, labelPanel, backgroundPanel, axisPanel, groupId, options) {
  5715. this.id = util.randomUUID();
  5716. this.groupPanel = groupPanel;
  5717. this.labelPanel = labelPanel;
  5718. this.backgroundPanel = backgroundPanel;
  5719. this.axisPanel = axisPanel;
  5720. this.groupId = groupId;
  5721. this.itemSet = null; // ItemSet
  5722. this.options = options || {};
  5723. this.options.top = 0;
  5724. this.props = {
  5725. label: {
  5726. width: 0,
  5727. height: 0
  5728. }
  5729. };
  5730. this.dom = {};
  5731. this.top = 0;
  5732. this.left = 0;
  5733. this.width = 0;
  5734. this.height = 0;
  5735. this._create();
  5736. }
  5737. Group.prototype = new Component();
  5738. // TODO: comment
  5739. Group.prototype.setOptions = Component.prototype.setOptions;
  5740. /**
  5741. * Create DOM elements for the group
  5742. * @private
  5743. */
  5744. Group.prototype._create = function() {
  5745. var label = document.createElement('div');
  5746. label.className = 'vlabel';
  5747. this.dom.label = label;
  5748. var inner = document.createElement('div');
  5749. inner.className = 'inner';
  5750. label.appendChild(inner);
  5751. this.dom.inner = inner;
  5752. };
  5753. /**
  5754. * Set the group data for this group
  5755. * @param {Object} data Group data, can contain properties content and className
  5756. */
  5757. Group.prototype.setData = function setData(data) {
  5758. // update contents
  5759. var content = data && data.content;
  5760. if (content instanceof Element) {
  5761. this.dom.inner.appendChild(content);
  5762. }
  5763. else if (content != undefined) {
  5764. this.dom.inner.innerHTML = content;
  5765. }
  5766. else {
  5767. this.dom.inner.innerHTML = this.groupId;
  5768. }
  5769. // update className
  5770. var className = data && data.className;
  5771. if (className) {
  5772. util.addClassName(this.dom.label, className);
  5773. }
  5774. };
  5775. /**
  5776. * Set item set for the group. The group will create a view on the itemSet,
  5777. * filtered by the groups id.
  5778. * @param {DataSet | DataView} itemsData
  5779. */
  5780. Group.prototype.setItems = function setItems(itemsData) {
  5781. if (this.itemSet) {
  5782. // remove current item set
  5783. this.itemSet.setItems();
  5784. this.itemSet.hide();
  5785. this.groupPanel.frame.removeChild(this.itemSet.getFrame());
  5786. this.itemSet = null;
  5787. }
  5788. if (itemsData) {
  5789. var groupId = this.groupId;
  5790. var me = this;
  5791. var itemSetOptions = util.extend(this.options, {
  5792. height: function () {
  5793. // FIXME: setting height doesn't yet work
  5794. return Math.max(me.props.label.height, me.itemSet.height);
  5795. }
  5796. });
  5797. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, itemSetOptions);
  5798. this.itemSet.on('change', this.emit.bind(this, 'change')); // propagate change event
  5799. this.itemSet.parent = this;
  5800. this.groupPanel.frame.appendChild(this.itemSet.getFrame());
  5801. if (this.range) this.itemSet.setRange(this.range);
  5802. this.view = new DataView(itemsData, {
  5803. filter: function (item) {
  5804. return item.group == groupId;
  5805. }
  5806. });
  5807. this.itemSet.setItems(this.view);
  5808. }
  5809. };
  5810. /**
  5811. * hide the group, detach from DOM if needed
  5812. */
  5813. Group.prototype.show = function show() {
  5814. if (!this.dom.label.parentNode) {
  5815. this.labelPanel.frame.appendChild(this.dom.label);
  5816. }
  5817. var itemSetFrame = this.itemSet && this.itemSet.getFrame();
  5818. if (itemSetFrame) {
  5819. if (itemSetFrame.parentNode) {
  5820. itemSetFrame.parentNode.removeChild(itemSetFrame);
  5821. }
  5822. this.groupPanel.frame.appendChild(itemSetFrame);
  5823. this.itemSet.show();
  5824. }
  5825. };
  5826. /**
  5827. * hide the group, detach from DOM if needed
  5828. */
  5829. Group.prototype.hide = function hide() {
  5830. if (this.dom.label.parentNode) {
  5831. this.dom.label.parentNode.removeChild(this.dom.label);
  5832. }
  5833. if (this.itemSet) {
  5834. this.itemSet.hide();
  5835. }
  5836. var itemSetFrame = this.itemset && this.itemSet.getFrame();
  5837. if (itemSetFrame && itemSetFrame.parentNode) {
  5838. itemSetFrame.parentNode.removeChild(itemSetFrame);
  5839. }
  5840. };
  5841. /**
  5842. * Set range (start and end).
  5843. * @param {Range | Object} range A Range or an object containing start and end.
  5844. */
  5845. Group.prototype.setRange = function (range) {
  5846. this.range = range;
  5847. if (this.itemSet) this.itemSet.setRange(range);
  5848. };
  5849. /**
  5850. * Set selected items by their id. Replaces the current selection.
  5851. * Unknown id's are silently ignored.
  5852. * @param {Array} [ids] An array with zero or more id's of the items to be
  5853. * selected. If ids is an empty array, all items will be
  5854. * unselected.
  5855. */
  5856. Group.prototype.setSelection = function setSelection(ids) {
  5857. if (this.itemSet) this.itemSet.setSelection(ids);
  5858. };
  5859. /**
  5860. * Get the selected items by their id
  5861. * @return {Array} ids The ids of the selected items
  5862. */
  5863. Group.prototype.getSelection = function getSelection() {
  5864. return this.itemSet ? this.itemSet.getSelection() : [];
  5865. };
  5866. /**
  5867. * Repaint the group
  5868. * @return {boolean} Returns true if the component is resized
  5869. */
  5870. Group.prototype.repaint = function repaint() {
  5871. var resized = false;
  5872. this.show();
  5873. if (this.itemSet) {
  5874. resized = this.itemSet.repaint() || resized;
  5875. }
  5876. // calculate inner size of the label
  5877. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  5878. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  5879. this.height = this.itemSet ? this.itemSet.height : 0;
  5880. this.dom.label.style.height = this.height + 'px';
  5881. return resized;
  5882. };
  5883. /**
  5884. * An GroupSet holds a set of groups
  5885. * @param {Panel} contentPanel Panel where the ItemSets will be created
  5886. * @param {Panel} labelPanel Panel where the labels will be created
  5887. * @param {Panel} backgroundPanel Panel where the vertical lines of box
  5888. * items are created
  5889. * @param {Panel} axisPanel Panel on the axis where the dots of box
  5890. * items will be created
  5891. * @param {Object} [options] See GroupSet.setOptions for the available
  5892. * options.
  5893. * @constructor GroupSet
  5894. * @extends Panel
  5895. */
  5896. function GroupSet(contentPanel, labelPanel, backgroundPanel, axisPanel, options) {
  5897. this.id = util.randomUUID();
  5898. this.contentPanel = contentPanel;
  5899. this.labelPanel = labelPanel;
  5900. this.backgroundPanel = backgroundPanel;
  5901. this.axisPanel = axisPanel;
  5902. this.options = options || {};
  5903. this.range = null; // Range or Object {start: number, end: number}
  5904. this.itemsData = null; // DataSet with items
  5905. this.groupsData = null; // DataSet with groups
  5906. this.groups = {}; // map with groups
  5907. this.groupIds = []; // list with ordered group ids
  5908. this.dom = {};
  5909. this.props = {
  5910. labels: {
  5911. width: 0
  5912. }
  5913. };
  5914. // TODO: implement right orientation of the labels (left/right)
  5915. var me = this;
  5916. this.listeners = {
  5917. 'add': function (event, params) {
  5918. me._onAdd(params.items);
  5919. },
  5920. 'update': function (event, params) {
  5921. me._onUpdate(params.items);
  5922. },
  5923. 'remove': function (event, params) {
  5924. me._onRemove(params.items);
  5925. }
  5926. };
  5927. // create HTML DOM
  5928. this._create();
  5929. }
  5930. GroupSet.prototype = new Panel();
  5931. /**
  5932. * Create the HTML DOM elements for the GroupSet
  5933. * @private
  5934. */
  5935. GroupSet.prototype._create = function _create () {
  5936. // TODO: reimplement groupSet DOM elements
  5937. var frame = document.createElement('div');
  5938. frame.className = 'groupset';
  5939. frame['timeline-groupset'] = this;
  5940. this.frame = frame;
  5941. this.labelSet = new Panel({
  5942. className: 'labelset',
  5943. width: '100%',
  5944. height: '100%'
  5945. });
  5946. this.labelPanel.appendChild(this.labelSet);
  5947. };
  5948. /**
  5949. * Get the frame element of component
  5950. * @returns {null} Get frame is not supported by GroupSet
  5951. */
  5952. GroupSet.prototype.getFrame = function getFrame() {
  5953. return this.frame;
  5954. };
  5955. /**
  5956. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5957. * @param {Object} [options] The following options are available:
  5958. * {String | function} groupsOrder
  5959. * TODO: describe options
  5960. */
  5961. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5962. /**
  5963. * Set range (start and end).
  5964. * @param {Range | Object} range A Range or an object containing start and end.
  5965. */
  5966. GroupSet.prototype.setRange = function (range) {
  5967. this.range = range;
  5968. for (var id in this.groups) {
  5969. if (this.groups.hasOwnProperty(id)) {
  5970. this.groups[id].setRange(range);
  5971. }
  5972. }
  5973. };
  5974. /**
  5975. * Set items
  5976. * @param {vis.DataSet | null} items
  5977. */
  5978. GroupSet.prototype.setItems = function setItems(items) {
  5979. this.itemsData = items;
  5980. for (var id in this.groups) {
  5981. if (this.groups.hasOwnProperty(id)) {
  5982. var group = this.groups[id];
  5983. // TODO: every group will emit a change event, causing a lot of unnecessary repaints. improve this.
  5984. group.setItems(items);
  5985. }
  5986. }
  5987. };
  5988. /**
  5989. * Get items
  5990. * @return {vis.DataSet | null} items
  5991. */
  5992. GroupSet.prototype.getItems = function getItems() {
  5993. return this.itemsData;
  5994. };
  5995. /**
  5996. * Set range (start and end).
  5997. * @param {Range | Object} range A Range or an object containing start and end.
  5998. */
  5999. GroupSet.prototype.setRange = function setRange(range) {
  6000. this.range = range;
  6001. };
  6002. /**
  6003. * Set groups
  6004. * @param {vis.DataSet} groups
  6005. */
  6006. GroupSet.prototype.setGroups = function setGroups(groups) {
  6007. var me = this,
  6008. ids;
  6009. // unsubscribe from current dataset
  6010. if (this.groupsData) {
  6011. util.forEach(this.listeners, function (callback, event) {
  6012. me.groupsData.unsubscribe(event, callback);
  6013. });
  6014. // remove all drawn groups
  6015. ids = this.groupsData.getIds();
  6016. this._onRemove(ids);
  6017. }
  6018. // replace the dataset
  6019. if (!groups) {
  6020. this.groupsData = null;
  6021. }
  6022. else if (groups instanceof DataSet) {
  6023. this.groupsData = groups;
  6024. }
  6025. else {
  6026. this.groupsData = new DataSet({
  6027. convert: {
  6028. start: 'Date',
  6029. end: 'Date'
  6030. }
  6031. });
  6032. this.groupsData.add(groups);
  6033. }
  6034. if (this.groupsData) {
  6035. // subscribe to new dataset
  6036. var id = this.id;
  6037. util.forEach(this.listeners, function (callback, event) {
  6038. me.groupsData.on(event, callback, id);
  6039. });
  6040. // draw all new groups
  6041. ids = this.groupsData.getIds();
  6042. this._onAdd(ids);
  6043. }
  6044. this.emit('change');
  6045. };
  6046. /**
  6047. * Get groups
  6048. * @return {vis.DataSet | null} groups
  6049. */
  6050. GroupSet.prototype.getGroups = function getGroups() {
  6051. return this.groupsData;
  6052. };
  6053. /**
  6054. * Set selected items by their id. Replaces the current selection.
  6055. * Unknown id's are silently ignored.
  6056. * @param {Array} [ids] An array with zero or more id's of the items to be
  6057. * selected. If ids is an empty array, all items will be
  6058. * unselected.
  6059. */
  6060. GroupSet.prototype.setSelection = function setSelection(ids) {
  6061. var selection = [],
  6062. groups = this.groups;
  6063. // iterate over each of the groups
  6064. for (var id in groups) {
  6065. if (groups.hasOwnProperty(id)) {
  6066. var group = groups[id];
  6067. group.setSelection(ids);
  6068. }
  6069. }
  6070. return selection;
  6071. };
  6072. /**
  6073. * Get the selected items by their id
  6074. * @return {Array} ids The ids of the selected items
  6075. */
  6076. GroupSet.prototype.getSelection = function getSelection() {
  6077. var selection = [],
  6078. groups = this.groups;
  6079. // iterate over each of the groups
  6080. for (var id in groups) {
  6081. if (groups.hasOwnProperty(id)) {
  6082. var group = groups[id];
  6083. selection = selection.concat(group.getSelection());
  6084. }
  6085. }
  6086. return selection;
  6087. };
  6088. /**
  6089. * Repaint the component
  6090. * @return {boolean} Returns true if the component was resized since previous repaint
  6091. */
  6092. GroupSet.prototype.repaint = function repaint() {
  6093. var i, id, group,
  6094. asSize = util.option.asSize,
  6095. asString = util.option.asString,
  6096. options = this.options,
  6097. orientation = this.getOption('orientation'),
  6098. frame = this.frame,
  6099. resized = false,
  6100. groups = this.groups;
  6101. // repaint all groups in order
  6102. this.groupIds.forEach(function (id) {
  6103. var groupResized = groups[id].repaint();
  6104. resized = resized || groupResized;
  6105. });
  6106. // reposition the labels and calculate the maximum label width
  6107. var maxWidth = 0;
  6108. for (id in groups) {
  6109. if (groups.hasOwnProperty(id)) {
  6110. group = groups[id];
  6111. maxWidth = Math.max(maxWidth, group.props.label.width);
  6112. }
  6113. }
  6114. resized = util.updateProperty(this.props.labels, 'width', maxWidth) || resized;
  6115. // recalculate the height of the groupset, and recalculate top positions of the groups
  6116. var fixedHeight = (asSize(options.height) != null);
  6117. var height;
  6118. if (!fixedHeight) {
  6119. // height is not specified, calculate the sum of the height of all groups
  6120. height = 0;
  6121. this.groupIds.forEach(function (id) {
  6122. var group = groups[id];
  6123. group.top = height;
  6124. if (group.itemSet) group.itemSet.top = group.top; // TODO: this is an ugly hack
  6125. height += group.height;
  6126. });
  6127. }
  6128. // update classname
  6129. frame.className = 'groupset' + (options.className ? (' ' + asString(options.className)) : '');
  6130. // calculate actual size and position
  6131. this.top = frame.offsetTop;
  6132. this.left = frame.offsetLeft;
  6133. this.width = frame.offsetWidth;
  6134. this.height = height;
  6135. return resized;
  6136. };
  6137. /**
  6138. * Update the groupIds. Requires a repaint afterwards
  6139. * @private
  6140. */
  6141. GroupSet.prototype._updateGroupIds = function () {
  6142. // reorder the groups
  6143. this.groupIds = this.groupsData.getIds({
  6144. order: this.options.groupOrder
  6145. });
  6146. // hide the groups now, they will be shown again in the next repaint
  6147. // in correct order
  6148. var groups = this.groups;
  6149. this.groupIds.forEach(function (id) {
  6150. groups[id].hide();
  6151. });
  6152. };
  6153. /**
  6154. * Get the width of the group labels
  6155. * @return {Number} width
  6156. */
  6157. GroupSet.prototype.getLabelsWidth = function getLabelsWidth() {
  6158. return this.props.labels.width;
  6159. };
  6160. /**
  6161. * Hide the component from the DOM
  6162. */
  6163. GroupSet.prototype.hide = function hide() {
  6164. // hide labelset
  6165. this.labelPanel.removeChild(this.labelSet);
  6166. // hide each of the groups
  6167. for (var groupId in this.groups) {
  6168. if (this.groups.hasOwnProperty(groupId)) {
  6169. this.groups[groupId].hide();
  6170. }
  6171. }
  6172. };
  6173. /**
  6174. * Show the component in the DOM (when not already visible).
  6175. * @return {Boolean} changed
  6176. */
  6177. GroupSet.prototype.show = function show() {
  6178. // show label set
  6179. if (!this.labelPanel.hasChild(this.labelSet)) {
  6180. this.labelPanel.removeChild(this.labelSet);
  6181. }
  6182. // show each of the groups
  6183. for (var groupId in this.groups) {
  6184. if (this.groups.hasOwnProperty(groupId)) {
  6185. this.groups[groupId].show();
  6186. }
  6187. }
  6188. };
  6189. /**
  6190. * Handle updated groups
  6191. * @param {Number[]} ids
  6192. * @private
  6193. */
  6194. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6195. this._onAdd(ids);
  6196. };
  6197. /**
  6198. * Handle changed groups
  6199. * @param {Number[]} ids
  6200. * @private
  6201. */
  6202. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6203. var me = this;
  6204. ids.forEach(function (id) {
  6205. var group = me.groups[id];
  6206. if (!group) {
  6207. var groupOptions = Object.create(me.options);
  6208. util.extend(groupOptions, {
  6209. height: null
  6210. });
  6211. group = new Group(me, me.labelSet, me.backgroundPanel, me.axisPanel, id, groupOptions);
  6212. group.on('change', me.emit.bind(me, 'change')); // propagate change event
  6213. group.setRange(me.range);
  6214. group.setItems(me.itemsData); // attach items data
  6215. me.groups[id] = group;
  6216. group.parent = me;
  6217. }
  6218. // update group data
  6219. group.setData(me.groupsData.get(id));
  6220. });
  6221. this._updateGroupIds();
  6222. this.emit('change');
  6223. };
  6224. /**
  6225. * Handle removed groups
  6226. * @param {Number[]} ids
  6227. * @private
  6228. */
  6229. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6230. var groups = this.groups;
  6231. ids.forEach(function (id) {
  6232. var group = groups[id];
  6233. if (group) {
  6234. group.setItems(); // detach items data
  6235. group.hide(); // FIXME: for some reason when doing setItems after hide, setItems again makes the label visible
  6236. delete groups[id];
  6237. }
  6238. });
  6239. this._updateGroupIds();
  6240. this.emit('change');
  6241. };
  6242. /**
  6243. * Find the GroupSet from an event target:
  6244. * searches for the attribute 'timeline-groupset' in the event target's element
  6245. * tree, then finds the right group in this groupset
  6246. * @param {Event} event
  6247. * @return {Group | null} group
  6248. */
  6249. GroupSet.groupSetFromTarget = function groupSetFromTarget (event) {
  6250. var target = event.target;
  6251. while (target) {
  6252. if (target.hasOwnProperty('timeline-groupset')) {
  6253. return target['timeline-groupset'];
  6254. }
  6255. target = target.parentNode;
  6256. }
  6257. return null;
  6258. };
  6259. /**
  6260. * Find the Group from an event target:
  6261. * searches for the two elements having attributes 'timeline-groupset' and
  6262. * 'timeline-itemset' in the event target's element, then finds the right group.
  6263. * @param {Event} event
  6264. * @return {Group | null} group
  6265. */
  6266. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6267. // find the groupSet
  6268. var groupSet = GroupSet.groupSetFromTarget(event);
  6269. // find the ItemSet
  6270. var itemSet = ItemSet.itemSetFromTarget(event);
  6271. // find the right group
  6272. if (groupSet && itemSet) {
  6273. for (var groupId in groupSet.groups) {
  6274. if (groupSet.groups.hasOwnProperty(groupId)) {
  6275. var group = groupSet.groups[groupId];
  6276. if (group.itemSet == itemSet) {
  6277. return group;
  6278. }
  6279. }
  6280. }
  6281. }
  6282. return null;
  6283. };
  6284. /**
  6285. * Create a timeline visualization
  6286. * @param {HTMLElement} container
  6287. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6288. * @param {Object} [options] See Timeline.setOptions for the available options.
  6289. * @constructor
  6290. */
  6291. function Timeline (container, items, options) {
  6292. // validate arguments
  6293. if (!container) throw new Error('No container element provided');
  6294. var me = this;
  6295. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6296. this.options = {
  6297. orientation: 'bottom',
  6298. direction: 'horizontal', // 'horizontal' or 'vertical'
  6299. autoResize: true,
  6300. editable: false,
  6301. selectable: true,
  6302. snap: null, // will be specified after timeaxis is created
  6303. min: null,
  6304. max: null,
  6305. zoomMin: 10, // milliseconds
  6306. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6307. // moveable: true, // TODO: option moveable
  6308. // zoomable: true, // TODO: option zoomable
  6309. showMinorLabels: true,
  6310. showMajorLabels: true,
  6311. showCurrentTime: false,
  6312. showCustomTime: false,
  6313. type: 'box',
  6314. align: 'center',
  6315. margin: {
  6316. axis: 20,
  6317. item: 10
  6318. },
  6319. padding: 5,
  6320. onAdd: function (item, callback) {
  6321. callback(item);
  6322. },
  6323. onUpdate: function (item, callback) {
  6324. callback(item);
  6325. },
  6326. onMove: function (item, callback) {
  6327. callback(item);
  6328. },
  6329. onRemove: function (item, callback) {
  6330. callback(item);
  6331. },
  6332. toScreen: me._toScreen.bind(me),
  6333. toTime: me._toTime.bind(me)
  6334. };
  6335. // root panel
  6336. var rootOptions = util.extend(Object.create(this.options), {
  6337. height: function () {
  6338. if (me.options.height) {
  6339. // fixed height
  6340. return me.options.height;
  6341. }
  6342. else {
  6343. // auto height
  6344. // TODO: implement a css based solution to automatically have the right hight
  6345. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6346. }
  6347. }
  6348. });
  6349. this.rootPanel = new RootPanel(container, rootOptions);
  6350. // single select (or unselect) when tapping an item
  6351. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6352. // multi select when holding mouse/touch, or on ctrl+click
  6353. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6354. // add item on doubletap
  6355. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6356. // side panel
  6357. var sideOptions = util.extend(Object.create(this.options), {
  6358. top: function () {
  6359. return (sideOptions.orientation == 'top') ? '0' : '';
  6360. },
  6361. bottom: function () {
  6362. return (sideOptions.orientation == 'top') ? '' : '0';
  6363. },
  6364. left: '0',
  6365. right: null,
  6366. height: '100%',
  6367. width: function () {
  6368. if (me.groupSet) {
  6369. return me.groupSet.getLabelsWidth();
  6370. }
  6371. else {
  6372. return 0;
  6373. }
  6374. },
  6375. className: function () {
  6376. return 'side' + (me.groupsData ? '' : ' hidden');
  6377. }
  6378. });
  6379. this.sidePanel = new Panel(sideOptions);
  6380. this.rootPanel.appendChild(this.sidePanel);
  6381. // main panel (contains time axis and itemsets)
  6382. var mainOptions = util.extend(Object.create(this.options), {
  6383. left: function () {
  6384. // we align left to enable a smooth resizing of the window
  6385. return me.sidePanel.width;
  6386. },
  6387. right: null,
  6388. height: '100%',
  6389. width: function () {
  6390. return me.rootPanel.width - me.sidePanel.width;
  6391. },
  6392. className: 'main'
  6393. });
  6394. this.mainPanel = new Panel(mainOptions);
  6395. this.rootPanel.appendChild(this.mainPanel);
  6396. // range
  6397. // TODO: move range inside rootPanel?
  6398. var rangeOptions = Object.create(this.options);
  6399. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6400. this.range.setRange(
  6401. now.clone().add('days', -3).valueOf(),
  6402. now.clone().add('days', 4).valueOf()
  6403. );
  6404. this.range.on('rangechange', function (properties) {
  6405. me.rootPanel.repaint();
  6406. me.emit('rangechange', properties);
  6407. });
  6408. this.range.on('rangechanged', function (properties) {
  6409. me.rootPanel.repaint();
  6410. me.emit('rangechanged', properties);
  6411. });
  6412. // panel with time axis
  6413. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6414. range: this.range,
  6415. left: null,
  6416. top: null,
  6417. width: null,
  6418. height: null
  6419. });
  6420. this.timeAxis = new TimeAxis(timeAxisOptions);
  6421. this.timeAxis.setRange(this.range);
  6422. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6423. this.mainPanel.appendChild(this.timeAxis);
  6424. // content panel (contains itemset(s))
  6425. var contentOptions = util.extend(Object.create(this.options), {
  6426. top: function () {
  6427. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6428. },
  6429. bottom: function () {
  6430. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6431. },
  6432. left: null,
  6433. right: null,
  6434. height: null,
  6435. width: null,
  6436. className: 'content'
  6437. });
  6438. this.contentPanel = new Panel(contentOptions);
  6439. this.mainPanel.appendChild(this.contentPanel);
  6440. // content panel (contains the vertical lines of box items)
  6441. var backgroundOptions = util.extend(Object.create(this.options), {
  6442. top: function () {
  6443. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6444. },
  6445. bottom: function () {
  6446. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6447. },
  6448. left: null,
  6449. right: null,
  6450. height: function () {
  6451. return me.contentPanel.height;
  6452. },
  6453. width: null,
  6454. className: 'background'
  6455. });
  6456. this.backgroundPanel = new Panel(backgroundOptions);
  6457. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6458. // panel with axis holding the dots of item boxes
  6459. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6460. left: 0,
  6461. top: function () {
  6462. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6463. },
  6464. bottom: function () {
  6465. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6466. },
  6467. width: '100%',
  6468. height: 0,
  6469. className: 'axis'
  6470. });
  6471. this.axisPanel = new Panel(axisPanelOptions);
  6472. this.mainPanel.appendChild(this.axisPanel);
  6473. // content panel (contains itemset(s))
  6474. var sideContentOptions = util.extend(Object.create(this.options), {
  6475. top: function () {
  6476. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6477. },
  6478. bottom: function () {
  6479. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6480. },
  6481. left: null,
  6482. right: null,
  6483. height: null,
  6484. width: null,
  6485. className: 'side-content'
  6486. });
  6487. this.sideContentPanel = new Panel(sideContentOptions);
  6488. this.sidePanel.appendChild(this.sideContentPanel);
  6489. // current time bar
  6490. // Note: time bar will be attached in this.setOptions when selected
  6491. this.currentTime = new CurrentTime(this.range, rootOptions);
  6492. // custom time bar
  6493. // Note: time bar will be attached in this.setOptions when selected
  6494. this.customTime = new CustomTime(rootOptions);
  6495. this.customTime.on('timechange', function (time) {
  6496. me.emit('timechange', time);
  6497. });
  6498. this.customTime.on('timechanged', function (time) {
  6499. me.emit('timechanged', time);
  6500. });
  6501. this.itemSet = null;
  6502. this.groupSet = null;
  6503. // create groupset
  6504. this.setGroups(null);
  6505. this.itemsData = null; // DataSet
  6506. this.groupsData = null; // DataSet
  6507. // apply options
  6508. if (options) {
  6509. this.setOptions(options);
  6510. }
  6511. // create itemset and groupset
  6512. if (items) {
  6513. this.setItems(items);
  6514. }
  6515. }
  6516. // turn Timeline into an event emitter
  6517. Emitter(Timeline.prototype);
  6518. /**
  6519. * Set options
  6520. * @param {Object} options TODO: describe the available options
  6521. */
  6522. Timeline.prototype.setOptions = function (options) {
  6523. util.extend(this.options, options);
  6524. // force update of range (apply new min/max etc.)
  6525. // both start and end are optional
  6526. this.range.setRange(options.start, options.end);
  6527. if ('editable' in options || 'selectable' in options) {
  6528. if (this.options.selectable) {
  6529. // force update of selection
  6530. this.setSelection(this.getSelection());
  6531. }
  6532. else {
  6533. // remove selection
  6534. this.setSelection([]);
  6535. }
  6536. }
  6537. // validate the callback functions
  6538. var validateCallback = (function (fn) {
  6539. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6540. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6541. }
  6542. }).bind(this);
  6543. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6544. // add/remove the current time bar
  6545. if (this.options.showCurrentTime) {
  6546. if (!this.mainPanel.hasChild(this.currentTime)) {
  6547. this.mainPanel.appendChild(this.currentTime);
  6548. this.currentTime.start();
  6549. }
  6550. }
  6551. else {
  6552. if (this.mainPanel.hasChild(this.currentTime)) {
  6553. this.currentTime.stop();
  6554. this.mainPanel.removeChild(this.currentTime);
  6555. }
  6556. }
  6557. // add/remove the custom time bar
  6558. if (this.options.showCustomTime) {
  6559. if (!this.mainPanel.hasChild(this.customTime)) {
  6560. this.mainPanel.appendChild(this.customTime);
  6561. }
  6562. }
  6563. else {
  6564. if (this.mainPanel.hasChild(this.customTime)) {
  6565. this.mainPanel.removeChild(this.customTime);
  6566. }
  6567. }
  6568. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  6569. if (options && options.order) {
  6570. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  6571. }
  6572. // repaint everything
  6573. this.rootPanel.repaint();
  6574. };
  6575. /**
  6576. * Set a custom time bar
  6577. * @param {Date} time
  6578. */
  6579. Timeline.prototype.setCustomTime = function (time) {
  6580. if (!this.customTime) {
  6581. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6582. }
  6583. this.customTime.setCustomTime(time);
  6584. };
  6585. /**
  6586. * Retrieve the current custom time.
  6587. * @return {Date} customTime
  6588. */
  6589. Timeline.prototype.getCustomTime = function() {
  6590. if (!this.customTime) {
  6591. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6592. }
  6593. return this.customTime.getCustomTime();
  6594. };
  6595. /**
  6596. * Set items
  6597. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6598. */
  6599. Timeline.prototype.setItems = function(items) {
  6600. var initialLoad = (this.itemsData == null);
  6601. // convert to type DataSet when needed
  6602. var newDataSet;
  6603. if (!items) {
  6604. newDataSet = null;
  6605. }
  6606. else if (items instanceof DataSet) {
  6607. newDataSet = items;
  6608. }
  6609. if (!(items instanceof DataSet)) {
  6610. newDataSet = new DataSet({
  6611. convert: {
  6612. start: 'Date',
  6613. end: 'Date'
  6614. }
  6615. });
  6616. newDataSet.add(items);
  6617. }
  6618. // set items
  6619. this.itemsData = newDataSet;
  6620. (this.itemSet || this.groupSet).setItems(newDataSet);
  6621. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6622. // apply the data range as range
  6623. var dataRange = this.getItemRange();
  6624. // add 5% space on both sides
  6625. var start = dataRange.min;
  6626. var end = dataRange.max;
  6627. if (start != null && end != null) {
  6628. var interval = (end.valueOf() - start.valueOf());
  6629. if (interval <= 0) {
  6630. // prevent an empty interval
  6631. interval = 24 * 60 * 60 * 1000; // 1 day
  6632. }
  6633. start = new Date(start.valueOf() - interval * 0.05);
  6634. end = new Date(end.valueOf() + interval * 0.05);
  6635. }
  6636. // override specified start and/or end date
  6637. if (this.options.start != undefined) {
  6638. start = util.convert(this.options.start, 'Date');
  6639. }
  6640. if (this.options.end != undefined) {
  6641. end = util.convert(this.options.end, 'Date');
  6642. }
  6643. // skip range set if there is no start and end date
  6644. if (start === null && end === null) {
  6645. return;
  6646. }
  6647. // if start and end dates are set but cannot be satisfyed due to zoom restrictions — correct end date
  6648. if (start != null && end != null) {
  6649. var diff = end.valueOf() - start.valueOf();
  6650. if (this.options.zoomMax != undefined && this.options.zoomMax < diff) {
  6651. end = new Date(start.valueOf() + this.options.zoomMax);
  6652. }
  6653. if (this.options.zoomMin != undefined && this.options.zoomMin > diff) {
  6654. end = new Date(start.valueOf() + this.options.zoomMin);
  6655. }
  6656. }
  6657. this.range.setRange(start, end);
  6658. }
  6659. };
  6660. /**
  6661. * Set groups
  6662. * @param {vis.DataSet | Array | google.visualization.DataTable} groupSet
  6663. */
  6664. Timeline.prototype.setGroups = function(groupSet) {
  6665. var me = this;
  6666. this.groupsData = groupSet;
  6667. // create options for the itemset or groupset
  6668. var options = util.extend(Object.create(this.options), {
  6669. top: null,
  6670. bottom: null,
  6671. right: null,
  6672. left: null,
  6673. width: null,
  6674. height: null
  6675. });
  6676. if (this.groupsData) {
  6677. // Create a GroupSet
  6678. // remove itemset if existing
  6679. if (this.itemSet) {
  6680. this.itemSet.hide(); // TODO: not so nice having to hide here
  6681. this.contentPanel.removeChild(this.itemSet);
  6682. this.itemSet.setItems(); // disconnect from itemset
  6683. this.itemSet = null;
  6684. }
  6685. // create new GroupSet when needed
  6686. if (!this.groupSet) {
  6687. this.groupSet = new GroupSet(this.contentPanel, this.sideContentPanel, this.backgroundPanel, this.axisPanel, options);
  6688. this.groupSet.on('change', this.rootPanel.repaint.bind(this.rootPanel));
  6689. this.groupSet.setRange(this.range);
  6690. this.groupSet.setItems(this.itemsData);
  6691. this.groupSet.setGroups(this.groupsData);
  6692. this.contentPanel.appendChild(this.groupSet);
  6693. }
  6694. else {
  6695. this.groupSet.setGroups(this.groupsData);
  6696. }
  6697. }
  6698. else {
  6699. // ItemSet
  6700. if (this.groupSet) {
  6701. this.groupSet.hide(); // TODO: not so nice having to hide here
  6702. //this.groupSet.setGroups(); // disconnect from groupset
  6703. this.groupSet.setItems(); // disconnect from itemset
  6704. this.contentPanel.removeChild(this.groupSet);
  6705. this.groupSet = null;
  6706. }
  6707. // create new items
  6708. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, options);
  6709. this.itemSet.setRange(this.range);
  6710. this.itemSet.setItems(this.itemsData);
  6711. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6712. this.contentPanel.appendChild(this.itemSet);
  6713. }
  6714. };
  6715. /**
  6716. * Get the data range of the item set.
  6717. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6718. * When no minimum is found, min==null
  6719. * When no maximum is found, max==null
  6720. */
  6721. Timeline.prototype.getItemRange = function getItemRange() {
  6722. // calculate min from start filed
  6723. var itemsData = this.itemsData,
  6724. min = null,
  6725. max = null;
  6726. if (itemsData) {
  6727. // calculate the minimum value of the field 'start'
  6728. var minItem = itemsData.min('start');
  6729. min = minItem ? minItem.start.valueOf() : null;
  6730. // calculate maximum value of fields 'start' and 'end'
  6731. var maxStartItem = itemsData.max('start');
  6732. if (maxStartItem) {
  6733. max = maxStartItem.start.valueOf();
  6734. }
  6735. var maxEndItem = itemsData.max('end');
  6736. if (maxEndItem) {
  6737. if (max == null) {
  6738. max = maxEndItem.end.valueOf();
  6739. }
  6740. else {
  6741. max = Math.max(max, maxEndItem.end.valueOf());
  6742. }
  6743. }
  6744. }
  6745. return {
  6746. min: (min != null) ? new Date(min) : null,
  6747. max: (max != null) ? new Date(max) : null
  6748. };
  6749. };
  6750. /**
  6751. * Set selected items by their id. Replaces the current selection
  6752. * Unknown id's are silently ignored.
  6753. * @param {Array} [ids] An array with zero or more id's of the items to be
  6754. * selected. If ids is an empty array, all items will be
  6755. * unselected.
  6756. */
  6757. Timeline.prototype.setSelection = function setSelection (ids) {
  6758. var itemOrGroupSet = (this.itemSet || this.groupSet);
  6759. if (itemOrGroupSet) itemOrGroupSet.setSelection(ids);
  6760. };
  6761. /**
  6762. * Get the selected items by their id
  6763. * @return {Array} ids The ids of the selected items
  6764. */
  6765. Timeline.prototype.getSelection = function getSelection() {
  6766. var itemOrGroupSet = (this.itemSet || this.groupSet);
  6767. return itemOrGroupSet ? itemOrGroupSet.getSelection() : [];
  6768. };
  6769. /**
  6770. * Set the visible window. Both parameters are optional, you can change only
  6771. * start or only end. Syntax:
  6772. *
  6773. * TimeLine.setWindow(start, end)
  6774. * TimeLine.setWindow(range)
  6775. *
  6776. * Where start and end can be a Date, number, or string, and range is an
  6777. * object with properties start and end.
  6778. *
  6779. * @param {Date | Number | String} [start] Start date of visible window
  6780. * @param {Date | Number | String} [end] End date of visible window
  6781. */
  6782. Timeline.prototype.setWindow = function setWindow(start, end) {
  6783. if (arguments.length == 1) {
  6784. var range = arguments[0];
  6785. this.range.setRange(range.start, range.end);
  6786. }
  6787. else {
  6788. this.range.setRange(start, end);
  6789. }
  6790. };
  6791. /**
  6792. * Get the visible window
  6793. * @return {{start: Date, end: Date}} Visible range
  6794. */
  6795. Timeline.prototype.getWindow = function setWindow() {
  6796. var range = this.range.getRange();
  6797. return {
  6798. start: new Date(range.start),
  6799. end: new Date(range.end)
  6800. };
  6801. };
  6802. /**
  6803. * Handle selecting/deselecting an item when tapping it
  6804. * @param {Event} event
  6805. * @private
  6806. */
  6807. // TODO: move this function to ItemSet
  6808. Timeline.prototype._onSelectItem = function (event) {
  6809. if (!this.options.selectable) return;
  6810. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6811. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6812. if (ctrlKey || shiftKey) {
  6813. this._onMultiSelectItem(event);
  6814. return;
  6815. }
  6816. var oldSelection = this.getSelection();
  6817. var item = ItemSet.itemFromTarget(event);
  6818. var selection = item ? [item.id] : [];
  6819. this.setSelection(selection);
  6820. var newSelection = this.getSelection();
  6821. // if selection is changed, emit a select event
  6822. if (!util.equalArray(oldSelection, newSelection)) {
  6823. this.emit('select', {
  6824. items: this.getSelection()
  6825. });
  6826. }
  6827. event.stopPropagation();
  6828. };
  6829. /**
  6830. * Handle creation and updates of an item on double tap
  6831. * @param event
  6832. * @private
  6833. */
  6834. Timeline.prototype._onAddItem = function (event) {
  6835. if (!this.options.selectable) return;
  6836. if (!this.options.editable) return;
  6837. var me = this,
  6838. item = ItemSet.itemFromTarget(event);
  6839. if (item) {
  6840. // update item
  6841. // execute async handler to update the item (or cancel it)
  6842. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6843. this.options.onUpdate(itemData, function (itemData) {
  6844. if (itemData) {
  6845. me.itemsData.update(itemData);
  6846. }
  6847. });
  6848. }
  6849. else {
  6850. // add item
  6851. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  6852. var x = event.gesture.center.pageX - xAbs;
  6853. var newItem = {
  6854. start: this.timeAxis.snap(this._toTime(x)),
  6855. content: 'new item'
  6856. };
  6857. var id = util.randomUUID();
  6858. newItem[this.itemsData.fieldId] = id;
  6859. var group = GroupSet.groupFromTarget(event);
  6860. if (group) {
  6861. newItem.group = group.groupId;
  6862. }
  6863. // execute async handler to customize (or cancel) adding an item
  6864. this.options.onAdd(newItem, function (item) {
  6865. if (item) {
  6866. me.itemsData.add(newItem);
  6867. // TODO: need to trigger a repaint?
  6868. }
  6869. });
  6870. }
  6871. };
  6872. /**
  6873. * Handle selecting/deselecting multiple items when holding an item
  6874. * @param {Event} event
  6875. * @private
  6876. */
  6877. // TODO: move this function to ItemSet
  6878. Timeline.prototype._onMultiSelectItem = function (event) {
  6879. if (!this.options.selectable) return;
  6880. var selection,
  6881. item = ItemSet.itemFromTarget(event);
  6882. if (item) {
  6883. // multi select items
  6884. selection = this.getSelection(); // current selection
  6885. var index = selection.indexOf(item.id);
  6886. if (index == -1) {
  6887. // item is not yet selected -> select it
  6888. selection.push(item.id);
  6889. }
  6890. else {
  6891. // item is already selected -> deselect it
  6892. selection.splice(index, 1);
  6893. }
  6894. this.setSelection(selection);
  6895. this.emit('select', {
  6896. items: this.getSelection()
  6897. });
  6898. event.stopPropagation();
  6899. }
  6900. };
  6901. /**
  6902. * Convert a position on screen (pixels) to a datetime
  6903. * @param {int} x Position on the screen in pixels
  6904. * @return {Date} time The datetime the corresponds with given position x
  6905. * @private
  6906. */
  6907. Timeline.prototype._toTime = function _toTime(x) {
  6908. var conversion = this.range.conversion(this.mainPanel.width);
  6909. return new Date(x / conversion.scale + conversion.offset);
  6910. };
  6911. /**
  6912. * Convert a datetime (Date object) into a position on the screen
  6913. * @param {Date} time A date
  6914. * @return {int} x The position on the screen in pixels which corresponds
  6915. * with the given date.
  6916. * @private
  6917. */
  6918. Timeline.prototype._toScreen = function _toScreen(time) {
  6919. var conversion = this.range.conversion(this.mainPanel.width);
  6920. return (time.valueOf() - conversion.offset) * conversion.scale;
  6921. };
  6922. (function(exports) {
  6923. /**
  6924. * Parse a text source containing data in DOT language into a JSON object.
  6925. * The object contains two lists: one with nodes and one with edges.
  6926. *
  6927. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6928. *
  6929. * @param {String} data Text containing a graph in DOT-notation
  6930. * @return {Object} graph An object containing two parameters:
  6931. * {Object[]} nodes
  6932. * {Object[]} edges
  6933. */
  6934. function parseDOT (data) {
  6935. dot = data;
  6936. return parseGraph();
  6937. }
  6938. // token types enumeration
  6939. var TOKENTYPE = {
  6940. NULL : 0,
  6941. DELIMITER : 1,
  6942. IDENTIFIER: 2,
  6943. UNKNOWN : 3
  6944. };
  6945. // map with all delimiters
  6946. var DELIMITERS = {
  6947. '{': true,
  6948. '}': true,
  6949. '[': true,
  6950. ']': true,
  6951. ';': true,
  6952. '=': true,
  6953. ',': true,
  6954. '->': true,
  6955. '--': true
  6956. };
  6957. var dot = ''; // current dot file
  6958. var index = 0; // current index in dot file
  6959. var c = ''; // current token character in expr
  6960. var token = ''; // current token
  6961. var tokenType = TOKENTYPE.NULL; // type of the token
  6962. /**
  6963. * Get the first character from the dot file.
  6964. * The character is stored into the char c. If the end of the dot file is
  6965. * reached, the function puts an empty string in c.
  6966. */
  6967. function first() {
  6968. index = 0;
  6969. c = dot.charAt(0);
  6970. }
  6971. /**
  6972. * Get the next character from the dot file.
  6973. * The character is stored into the char c. If the end of the dot file is
  6974. * reached, the function puts an empty string in c.
  6975. */
  6976. function next() {
  6977. index++;
  6978. c = dot.charAt(index);
  6979. }
  6980. /**
  6981. * Preview the next character from the dot file.
  6982. * @return {String} cNext
  6983. */
  6984. function nextPreview() {
  6985. return dot.charAt(index + 1);
  6986. }
  6987. /**
  6988. * Test whether given character is alphabetic or numeric
  6989. * @param {String} c
  6990. * @return {Boolean} isAlphaNumeric
  6991. */
  6992. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6993. function isAlphaNumeric(c) {
  6994. return regexAlphaNumeric.test(c);
  6995. }
  6996. /**
  6997. * Merge all properties of object b into object b
  6998. * @param {Object} a
  6999. * @param {Object} b
  7000. * @return {Object} a
  7001. */
  7002. function merge (a, b) {
  7003. if (!a) {
  7004. a = {};
  7005. }
  7006. if (b) {
  7007. for (var name in b) {
  7008. if (b.hasOwnProperty(name)) {
  7009. a[name] = b[name];
  7010. }
  7011. }
  7012. }
  7013. return a;
  7014. }
  7015. /**
  7016. * Set a value in an object, where the provided parameter name can be a
  7017. * path with nested parameters. For example:
  7018. *
  7019. * var obj = {a: 2};
  7020. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7021. *
  7022. * @param {Object} obj
  7023. * @param {String} path A parameter name or dot-separated parameter path,
  7024. * like "color.highlight.border".
  7025. * @param {*} value
  7026. */
  7027. function setValue(obj, path, value) {
  7028. var keys = path.split('.');
  7029. var o = obj;
  7030. while (keys.length) {
  7031. var key = keys.shift();
  7032. if (keys.length) {
  7033. // this isn't the end point
  7034. if (!o[key]) {
  7035. o[key] = {};
  7036. }
  7037. o = o[key];
  7038. }
  7039. else {
  7040. // this is the end point
  7041. o[key] = value;
  7042. }
  7043. }
  7044. }
  7045. /**
  7046. * Add a node to a graph object. If there is already a node with
  7047. * the same id, their attributes will be merged.
  7048. * @param {Object} graph
  7049. * @param {Object} node
  7050. */
  7051. function addNode(graph, node) {
  7052. var i, len;
  7053. var current = null;
  7054. // find root graph (in case of subgraph)
  7055. var graphs = [graph]; // list with all graphs from current graph to root graph
  7056. var root = graph;
  7057. while (root.parent) {
  7058. graphs.push(root.parent);
  7059. root = root.parent;
  7060. }
  7061. // find existing node (at root level) by its id
  7062. if (root.nodes) {
  7063. for (i = 0, len = root.nodes.length; i < len; i++) {
  7064. if (node.id === root.nodes[i].id) {
  7065. current = root.nodes[i];
  7066. break;
  7067. }
  7068. }
  7069. }
  7070. if (!current) {
  7071. // this is a new node
  7072. current = {
  7073. id: node.id
  7074. };
  7075. if (graph.node) {
  7076. // clone default attributes
  7077. current.attr = merge(current.attr, graph.node);
  7078. }
  7079. }
  7080. // add node to this (sub)graph and all its parent graphs
  7081. for (i = graphs.length - 1; i >= 0; i--) {
  7082. var g = graphs[i];
  7083. if (!g.nodes) {
  7084. g.nodes = [];
  7085. }
  7086. if (g.nodes.indexOf(current) == -1) {
  7087. g.nodes.push(current);
  7088. }
  7089. }
  7090. // merge attributes
  7091. if (node.attr) {
  7092. current.attr = merge(current.attr, node.attr);
  7093. }
  7094. }
  7095. /**
  7096. * Add an edge to a graph object
  7097. * @param {Object} graph
  7098. * @param {Object} edge
  7099. */
  7100. function addEdge(graph, edge) {
  7101. if (!graph.edges) {
  7102. graph.edges = [];
  7103. }
  7104. graph.edges.push(edge);
  7105. if (graph.edge) {
  7106. var attr = merge({}, graph.edge); // clone default attributes
  7107. edge.attr = merge(attr, edge.attr); // merge attributes
  7108. }
  7109. }
  7110. /**
  7111. * Create an edge to a graph object
  7112. * @param {Object} graph
  7113. * @param {String | Number | Object} from
  7114. * @param {String | Number | Object} to
  7115. * @param {String} type
  7116. * @param {Object | null} attr
  7117. * @return {Object} edge
  7118. */
  7119. function createEdge(graph, from, to, type, attr) {
  7120. var edge = {
  7121. from: from,
  7122. to: to,
  7123. type: type
  7124. };
  7125. if (graph.edge) {
  7126. edge.attr = merge({}, graph.edge); // clone default attributes
  7127. }
  7128. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7129. return edge;
  7130. }
  7131. /**
  7132. * Get next token in the current dot file.
  7133. * The token and token type are available as token and tokenType
  7134. */
  7135. function getToken() {
  7136. tokenType = TOKENTYPE.NULL;
  7137. token = '';
  7138. // skip over whitespaces
  7139. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7140. next();
  7141. }
  7142. do {
  7143. var isComment = false;
  7144. // skip comment
  7145. if (c == '#') {
  7146. // find the previous non-space character
  7147. var i = index - 1;
  7148. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7149. i--;
  7150. }
  7151. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7152. // the # is at the start of a line, this is indeed a line comment
  7153. while (c != '' && c != '\n') {
  7154. next();
  7155. }
  7156. isComment = true;
  7157. }
  7158. }
  7159. if (c == '/' && nextPreview() == '/') {
  7160. // skip line comment
  7161. while (c != '' && c != '\n') {
  7162. next();
  7163. }
  7164. isComment = true;
  7165. }
  7166. if (c == '/' && nextPreview() == '*') {
  7167. // skip block comment
  7168. while (c != '') {
  7169. if (c == '*' && nextPreview() == '/') {
  7170. // end of block comment found. skip these last two characters
  7171. next();
  7172. next();
  7173. break;
  7174. }
  7175. else {
  7176. next();
  7177. }
  7178. }
  7179. isComment = true;
  7180. }
  7181. // skip over whitespaces
  7182. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7183. next();
  7184. }
  7185. }
  7186. while (isComment);
  7187. // check for end of dot file
  7188. if (c == '') {
  7189. // token is still empty
  7190. tokenType = TOKENTYPE.DELIMITER;
  7191. return;
  7192. }
  7193. // check for delimiters consisting of 2 characters
  7194. var c2 = c + nextPreview();
  7195. if (DELIMITERS[c2]) {
  7196. tokenType = TOKENTYPE.DELIMITER;
  7197. token = c2;
  7198. next();
  7199. next();
  7200. return;
  7201. }
  7202. // check for delimiters consisting of 1 character
  7203. if (DELIMITERS[c]) {
  7204. tokenType = TOKENTYPE.DELIMITER;
  7205. token = c;
  7206. next();
  7207. return;
  7208. }
  7209. // check for an identifier (number or string)
  7210. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7211. if (isAlphaNumeric(c) || c == '-') {
  7212. token += c;
  7213. next();
  7214. while (isAlphaNumeric(c)) {
  7215. token += c;
  7216. next();
  7217. }
  7218. if (token == 'false') {
  7219. token = false; // convert to boolean
  7220. }
  7221. else if (token == 'true') {
  7222. token = true; // convert to boolean
  7223. }
  7224. else if (!isNaN(Number(token))) {
  7225. token = Number(token); // convert to number
  7226. }
  7227. tokenType = TOKENTYPE.IDENTIFIER;
  7228. return;
  7229. }
  7230. // check for a string enclosed by double quotes
  7231. if (c == '"') {
  7232. next();
  7233. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7234. token += c;
  7235. if (c == '"') { // skip the escape character
  7236. next();
  7237. }
  7238. next();
  7239. }
  7240. if (c != '"') {
  7241. throw newSyntaxError('End of string " expected');
  7242. }
  7243. next();
  7244. tokenType = TOKENTYPE.IDENTIFIER;
  7245. return;
  7246. }
  7247. // something unknown is found, wrong characters, a syntax error
  7248. tokenType = TOKENTYPE.UNKNOWN;
  7249. while (c != '') {
  7250. token += c;
  7251. next();
  7252. }
  7253. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7254. }
  7255. /**
  7256. * Parse a graph.
  7257. * @returns {Object} graph
  7258. */
  7259. function parseGraph() {
  7260. var graph = {};
  7261. first();
  7262. getToken();
  7263. // optional strict keyword
  7264. if (token == 'strict') {
  7265. graph.strict = true;
  7266. getToken();
  7267. }
  7268. // graph or digraph keyword
  7269. if (token == 'graph' || token == 'digraph') {
  7270. graph.type = token;
  7271. getToken();
  7272. }
  7273. // optional graph id
  7274. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7275. graph.id = token;
  7276. getToken();
  7277. }
  7278. // open angle bracket
  7279. if (token != '{') {
  7280. throw newSyntaxError('Angle bracket { expected');
  7281. }
  7282. getToken();
  7283. // statements
  7284. parseStatements(graph);
  7285. // close angle bracket
  7286. if (token != '}') {
  7287. throw newSyntaxError('Angle bracket } expected');
  7288. }
  7289. getToken();
  7290. // end of file
  7291. if (token !== '') {
  7292. throw newSyntaxError('End of file expected');
  7293. }
  7294. getToken();
  7295. // remove temporary default properties
  7296. delete graph.node;
  7297. delete graph.edge;
  7298. delete graph.graph;
  7299. return graph;
  7300. }
  7301. /**
  7302. * Parse a list with statements.
  7303. * @param {Object} graph
  7304. */
  7305. function parseStatements (graph) {
  7306. while (token !== '' && token != '}') {
  7307. parseStatement(graph);
  7308. if (token == ';') {
  7309. getToken();
  7310. }
  7311. }
  7312. }
  7313. /**
  7314. * Parse a single statement. Can be a an attribute statement, node
  7315. * statement, a series of node statements and edge statements, or a
  7316. * parameter.
  7317. * @param {Object} graph
  7318. */
  7319. function parseStatement(graph) {
  7320. // parse subgraph
  7321. var subgraph = parseSubgraph(graph);
  7322. if (subgraph) {
  7323. // edge statements
  7324. parseEdge(graph, subgraph);
  7325. return;
  7326. }
  7327. // parse an attribute statement
  7328. var attr = parseAttributeStatement(graph);
  7329. if (attr) {
  7330. return;
  7331. }
  7332. // parse node
  7333. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7334. throw newSyntaxError('Identifier expected');
  7335. }
  7336. var id = token; // id can be a string or a number
  7337. getToken();
  7338. if (token == '=') {
  7339. // id statement
  7340. getToken();
  7341. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7342. throw newSyntaxError('Identifier expected');
  7343. }
  7344. graph[id] = token;
  7345. getToken();
  7346. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7347. }
  7348. else {
  7349. parseNodeStatement(graph, id);
  7350. }
  7351. }
  7352. /**
  7353. * Parse a subgraph
  7354. * @param {Object} graph parent graph object
  7355. * @return {Object | null} subgraph
  7356. */
  7357. function parseSubgraph (graph) {
  7358. var subgraph = null;
  7359. // optional subgraph keyword
  7360. if (token == 'subgraph') {
  7361. subgraph = {};
  7362. subgraph.type = 'subgraph';
  7363. getToken();
  7364. // optional graph id
  7365. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7366. subgraph.id = token;
  7367. getToken();
  7368. }
  7369. }
  7370. // open angle bracket
  7371. if (token == '{') {
  7372. getToken();
  7373. if (!subgraph) {
  7374. subgraph = {};
  7375. }
  7376. subgraph.parent = graph;
  7377. subgraph.node = graph.node;
  7378. subgraph.edge = graph.edge;
  7379. subgraph.graph = graph.graph;
  7380. // statements
  7381. parseStatements(subgraph);
  7382. // close angle bracket
  7383. if (token != '}') {
  7384. throw newSyntaxError('Angle bracket } expected');
  7385. }
  7386. getToken();
  7387. // remove temporary default properties
  7388. delete subgraph.node;
  7389. delete subgraph.edge;
  7390. delete subgraph.graph;
  7391. delete subgraph.parent;
  7392. // register at the parent graph
  7393. if (!graph.subgraphs) {
  7394. graph.subgraphs = [];
  7395. }
  7396. graph.subgraphs.push(subgraph);
  7397. }
  7398. return subgraph;
  7399. }
  7400. /**
  7401. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7402. * Available keywords are 'node', 'edge', 'graph'.
  7403. * The previous list with default attributes will be replaced
  7404. * @param {Object} graph
  7405. * @returns {String | null} keyword Returns the name of the parsed attribute
  7406. * (node, edge, graph), or null if nothing
  7407. * is parsed.
  7408. */
  7409. function parseAttributeStatement (graph) {
  7410. // attribute statements
  7411. if (token == 'node') {
  7412. getToken();
  7413. // node attributes
  7414. graph.node = parseAttributeList();
  7415. return 'node';
  7416. }
  7417. else if (token == 'edge') {
  7418. getToken();
  7419. // edge attributes
  7420. graph.edge = parseAttributeList();
  7421. return 'edge';
  7422. }
  7423. else if (token == 'graph') {
  7424. getToken();
  7425. // graph attributes
  7426. graph.graph = parseAttributeList();
  7427. return 'graph';
  7428. }
  7429. return null;
  7430. }
  7431. /**
  7432. * parse a node statement
  7433. * @param {Object} graph
  7434. * @param {String | Number} id
  7435. */
  7436. function parseNodeStatement(graph, id) {
  7437. // node statement
  7438. var node = {
  7439. id: id
  7440. };
  7441. var attr = parseAttributeList();
  7442. if (attr) {
  7443. node.attr = attr;
  7444. }
  7445. addNode(graph, node);
  7446. // edge statements
  7447. parseEdge(graph, id);
  7448. }
  7449. /**
  7450. * Parse an edge or a series of edges
  7451. * @param {Object} graph
  7452. * @param {String | Number} from Id of the from node
  7453. */
  7454. function parseEdge(graph, from) {
  7455. while (token == '->' || token == '--') {
  7456. var to;
  7457. var type = token;
  7458. getToken();
  7459. var subgraph = parseSubgraph(graph);
  7460. if (subgraph) {
  7461. to = subgraph;
  7462. }
  7463. else {
  7464. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7465. throw newSyntaxError('Identifier or subgraph expected');
  7466. }
  7467. to = token;
  7468. addNode(graph, {
  7469. id: to
  7470. });
  7471. getToken();
  7472. }
  7473. // parse edge attributes
  7474. var attr = parseAttributeList();
  7475. // create edge
  7476. var edge = createEdge(graph, from, to, type, attr);
  7477. addEdge(graph, edge);
  7478. from = to;
  7479. }
  7480. }
  7481. /**
  7482. * Parse a set with attributes,
  7483. * for example [label="1.000", shape=solid]
  7484. * @return {Object | null} attr
  7485. */
  7486. function parseAttributeList() {
  7487. var attr = null;
  7488. while (token == '[') {
  7489. getToken();
  7490. attr = {};
  7491. while (token !== '' && token != ']') {
  7492. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7493. throw newSyntaxError('Attribute name expected');
  7494. }
  7495. var name = token;
  7496. getToken();
  7497. if (token != '=') {
  7498. throw newSyntaxError('Equal sign = expected');
  7499. }
  7500. getToken();
  7501. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7502. throw newSyntaxError('Attribute value expected');
  7503. }
  7504. var value = token;
  7505. setValue(attr, name, value); // name can be a path
  7506. getToken();
  7507. if (token ==',') {
  7508. getToken();
  7509. }
  7510. }
  7511. if (token != ']') {
  7512. throw newSyntaxError('Bracket ] expected');
  7513. }
  7514. getToken();
  7515. }
  7516. return attr;
  7517. }
  7518. /**
  7519. * Create a syntax error with extra information on current token and index.
  7520. * @param {String} message
  7521. * @returns {SyntaxError} err
  7522. */
  7523. function newSyntaxError(message) {
  7524. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7525. }
  7526. /**
  7527. * Chop off text after a maximum length
  7528. * @param {String} text
  7529. * @param {Number} maxLength
  7530. * @returns {String}
  7531. */
  7532. function chop (text, maxLength) {
  7533. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7534. }
  7535. /**
  7536. * Execute a function fn for each pair of elements in two arrays
  7537. * @param {Array | *} array1
  7538. * @param {Array | *} array2
  7539. * @param {function} fn
  7540. */
  7541. function forEach2(array1, array2, fn) {
  7542. if (array1 instanceof Array) {
  7543. array1.forEach(function (elem1) {
  7544. if (array2 instanceof Array) {
  7545. array2.forEach(function (elem2) {
  7546. fn(elem1, elem2);
  7547. });
  7548. }
  7549. else {
  7550. fn(elem1, array2);
  7551. }
  7552. });
  7553. }
  7554. else {
  7555. if (array2 instanceof Array) {
  7556. array2.forEach(function (elem2) {
  7557. fn(array1, elem2);
  7558. });
  7559. }
  7560. else {
  7561. fn(array1, array2);
  7562. }
  7563. }
  7564. }
  7565. /**
  7566. * Convert a string containing a graph in DOT language into a map containing
  7567. * with nodes and edges in the format of graph.
  7568. * @param {String} data Text containing a graph in DOT-notation
  7569. * @return {Object} graphData
  7570. */
  7571. function DOTToGraph (data) {
  7572. // parse the DOT file
  7573. var dotData = parseDOT(data);
  7574. var graphData = {
  7575. nodes: [],
  7576. edges: [],
  7577. options: {}
  7578. };
  7579. // copy the nodes
  7580. if (dotData.nodes) {
  7581. dotData.nodes.forEach(function (dotNode) {
  7582. var graphNode = {
  7583. id: dotNode.id,
  7584. label: String(dotNode.label || dotNode.id)
  7585. };
  7586. merge(graphNode, dotNode.attr);
  7587. if (graphNode.image) {
  7588. graphNode.shape = 'image';
  7589. }
  7590. graphData.nodes.push(graphNode);
  7591. });
  7592. }
  7593. // copy the edges
  7594. if (dotData.edges) {
  7595. /**
  7596. * Convert an edge in DOT format to an edge with VisGraph format
  7597. * @param {Object} dotEdge
  7598. * @returns {Object} graphEdge
  7599. */
  7600. function convertEdge(dotEdge) {
  7601. var graphEdge = {
  7602. from: dotEdge.from,
  7603. to: dotEdge.to
  7604. };
  7605. merge(graphEdge, dotEdge.attr);
  7606. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7607. return graphEdge;
  7608. }
  7609. dotData.edges.forEach(function (dotEdge) {
  7610. var from, to;
  7611. if (dotEdge.from instanceof Object) {
  7612. from = dotEdge.from.nodes;
  7613. }
  7614. else {
  7615. from = {
  7616. id: dotEdge.from
  7617. }
  7618. }
  7619. if (dotEdge.to instanceof Object) {
  7620. to = dotEdge.to.nodes;
  7621. }
  7622. else {
  7623. to = {
  7624. id: dotEdge.to
  7625. }
  7626. }
  7627. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7628. dotEdge.from.edges.forEach(function (subEdge) {
  7629. var graphEdge = convertEdge(subEdge);
  7630. graphData.edges.push(graphEdge);
  7631. });
  7632. }
  7633. forEach2(from, to, function (from, to) {
  7634. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7635. var graphEdge = convertEdge(subEdge);
  7636. graphData.edges.push(graphEdge);
  7637. });
  7638. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7639. dotEdge.to.edges.forEach(function (subEdge) {
  7640. var graphEdge = convertEdge(subEdge);
  7641. graphData.edges.push(graphEdge);
  7642. });
  7643. }
  7644. });
  7645. }
  7646. // copy the options
  7647. if (dotData.attr) {
  7648. graphData.options = dotData.attr;
  7649. }
  7650. return graphData;
  7651. }
  7652. // exports
  7653. exports.parseDOT = parseDOT;
  7654. exports.DOTToGraph = DOTToGraph;
  7655. })(typeof util !== 'undefined' ? util : exports);
  7656. /**
  7657. * Canvas shapes used by the Graph
  7658. */
  7659. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7660. /**
  7661. * Draw a circle shape
  7662. */
  7663. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7664. this.beginPath();
  7665. this.arc(x, y, r, 0, 2*Math.PI, false);
  7666. };
  7667. /**
  7668. * Draw a square shape
  7669. * @param {Number} x horizontal center
  7670. * @param {Number} y vertical center
  7671. * @param {Number} r size, width and height of the square
  7672. */
  7673. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7674. this.beginPath();
  7675. this.rect(x - r, y - r, r * 2, r * 2);
  7676. };
  7677. /**
  7678. * Draw a triangle shape
  7679. * @param {Number} x horizontal center
  7680. * @param {Number} y vertical center
  7681. * @param {Number} r radius, half the length of the sides of the triangle
  7682. */
  7683. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7684. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7685. this.beginPath();
  7686. var s = r * 2;
  7687. var s2 = s / 2;
  7688. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7689. var h = Math.sqrt(s * s - s2 * s2); // height
  7690. this.moveTo(x, y - (h - ir));
  7691. this.lineTo(x + s2, y + ir);
  7692. this.lineTo(x - s2, y + ir);
  7693. this.lineTo(x, y - (h - ir));
  7694. this.closePath();
  7695. };
  7696. /**
  7697. * Draw a triangle shape in downward orientation
  7698. * @param {Number} x horizontal center
  7699. * @param {Number} y vertical center
  7700. * @param {Number} r radius
  7701. */
  7702. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7703. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7704. this.beginPath();
  7705. var s = r * 2;
  7706. var s2 = s / 2;
  7707. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7708. var h = Math.sqrt(s * s - s2 * s2); // height
  7709. this.moveTo(x, y + (h - ir));
  7710. this.lineTo(x + s2, y - ir);
  7711. this.lineTo(x - s2, y - ir);
  7712. this.lineTo(x, y + (h - ir));
  7713. this.closePath();
  7714. };
  7715. /**
  7716. * Draw a star shape, a star with 5 points
  7717. * @param {Number} x horizontal center
  7718. * @param {Number} y vertical center
  7719. * @param {Number} r radius, half the length of the sides of the triangle
  7720. */
  7721. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7722. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7723. this.beginPath();
  7724. for (var n = 0; n < 10; n++) {
  7725. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7726. this.lineTo(
  7727. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7728. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7729. );
  7730. }
  7731. this.closePath();
  7732. };
  7733. /**
  7734. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7735. */
  7736. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7737. var r2d = Math.PI/180;
  7738. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7739. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7740. this.beginPath();
  7741. this.moveTo(x+r,y);
  7742. this.lineTo(x+w-r,y);
  7743. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7744. this.lineTo(x+w,y+h-r);
  7745. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7746. this.lineTo(x+r,y+h);
  7747. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7748. this.lineTo(x,y+r);
  7749. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7750. };
  7751. /**
  7752. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7753. */
  7754. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7755. var kappa = .5522848,
  7756. ox = (w / 2) * kappa, // control point offset horizontal
  7757. oy = (h / 2) * kappa, // control point offset vertical
  7758. xe = x + w, // x-end
  7759. ye = y + h, // y-end
  7760. xm = x + w / 2, // x-middle
  7761. ym = y + h / 2; // y-middle
  7762. this.beginPath();
  7763. this.moveTo(x, ym);
  7764. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7765. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7766. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7767. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7768. };
  7769. /**
  7770. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7771. */
  7772. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7773. var f = 1/3;
  7774. var wEllipse = w;
  7775. var hEllipse = h * f;
  7776. var kappa = .5522848,
  7777. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7778. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7779. xe = x + wEllipse, // x-end
  7780. ye = y + hEllipse, // y-end
  7781. xm = x + wEllipse / 2, // x-middle
  7782. ym = y + hEllipse / 2, // y-middle
  7783. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7784. yeb = y + h; // y-end, bottom ellipse
  7785. this.beginPath();
  7786. this.moveTo(xe, ym);
  7787. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7788. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7789. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7790. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7791. this.lineTo(xe, ymb);
  7792. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7793. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7794. this.lineTo(x, ym);
  7795. };
  7796. /**
  7797. * Draw an arrow point (no line)
  7798. */
  7799. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7800. // tail
  7801. var xt = x - length * Math.cos(angle);
  7802. var yt = y - length * Math.sin(angle);
  7803. // inner tail
  7804. // TODO: allow to customize different shapes
  7805. var xi = x - length * 0.9 * Math.cos(angle);
  7806. var yi = y - length * 0.9 * Math.sin(angle);
  7807. // left
  7808. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7809. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7810. // right
  7811. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7812. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7813. this.beginPath();
  7814. this.moveTo(x, y);
  7815. this.lineTo(xl, yl);
  7816. this.lineTo(xi, yi);
  7817. this.lineTo(xr, yr);
  7818. this.closePath();
  7819. };
  7820. /**
  7821. * Sets up the dashedLine functionality for drawing
  7822. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7823. * @author David Jordan
  7824. * @date 2012-08-08
  7825. */
  7826. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7827. if (!dashArray) dashArray=[10,5];
  7828. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7829. var dashCount = dashArray.length;
  7830. this.moveTo(x, y);
  7831. var dx = (x2-x), dy = (y2-y);
  7832. var slope = dy/dx;
  7833. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7834. var dashIndex=0, draw=true;
  7835. while (distRemaining>=0.1){
  7836. var dashLength = dashArray[dashIndex++%dashCount];
  7837. if (dashLength > distRemaining) dashLength = distRemaining;
  7838. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7839. if (dx<0) xStep = -xStep;
  7840. x += xStep;
  7841. y += slope*xStep;
  7842. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7843. distRemaining -= dashLength;
  7844. draw = !draw;
  7845. }
  7846. };
  7847. // TODO: add diamond shape
  7848. }
  7849. /**
  7850. * @class Node
  7851. * A node. A node can be connected to other nodes via one or multiple edges.
  7852. * @param {object} properties An object containing properties for the node. All
  7853. * properties are optional, except for the id.
  7854. * {number} id Id of the node. Required
  7855. * {string} label Text label for the node
  7856. * {number} x Horizontal position of the node
  7857. * {number} y Vertical position of the node
  7858. * {string} shape Node shape, available:
  7859. * "database", "circle", "ellipse",
  7860. * "box", "image", "text", "dot",
  7861. * "star", "triangle", "triangleDown",
  7862. * "square"
  7863. * {string} image An image url
  7864. * {string} title An title text, can be HTML
  7865. * {anytype} group A group name or number
  7866. * @param {Graph.Images} imagelist A list with images. Only needed
  7867. * when the node has an image
  7868. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7869. * retrieving group properties
  7870. * @param {Object} constants An object with default values for
  7871. * example for the color
  7872. *
  7873. */
  7874. function Node(properties, imagelist, grouplist, constants) {
  7875. this.selected = false;
  7876. this.edges = []; // all edges connected to this node
  7877. this.dynamicEdges = [];
  7878. this.reroutedEdges = {};
  7879. this.group = constants.nodes.group;
  7880. this.fontSize = constants.nodes.fontSize;
  7881. this.fontFace = constants.nodes.fontFace;
  7882. this.fontColor = constants.nodes.fontColor;
  7883. this.fontDrawThreshold = 3;
  7884. this.color = constants.nodes.color;
  7885. // set defaults for the properties
  7886. this.id = undefined;
  7887. this.shape = constants.nodes.shape;
  7888. this.image = constants.nodes.image;
  7889. this.x = null;
  7890. this.y = null;
  7891. this.xFixed = false;
  7892. this.yFixed = false;
  7893. this.horizontalAlignLeft = true; // these are for the navigation controls
  7894. this.verticalAlignTop = true; // these are for the navigation controls
  7895. this.radius = constants.nodes.radius;
  7896. this.baseRadiusValue = constants.nodes.radius;
  7897. this.radiusFixed = false;
  7898. this.radiusMin = constants.nodes.radiusMin;
  7899. this.radiusMax = constants.nodes.radiusMax;
  7900. this.level = -1;
  7901. this.preassignedLevel = false;
  7902. this.imagelist = imagelist;
  7903. this.grouplist = grouplist;
  7904. // physics properties
  7905. this.fx = 0.0; // external force x
  7906. this.fy = 0.0; // external force y
  7907. this.vx = 0.0; // velocity x
  7908. this.vy = 0.0; // velocity y
  7909. this.minForce = constants.minForce;
  7910. this.damping = constants.physics.damping;
  7911. this.mass = 1; // kg
  7912. this.fixedData = {x:null,y:null};
  7913. this.setProperties(properties, constants);
  7914. // creating the variables for clustering
  7915. this.resetCluster();
  7916. this.dynamicEdgesLength = 0;
  7917. this.clusterSession = 0;
  7918. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7919. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7920. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7921. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7922. this.growthIndicator = 0;
  7923. // variables to tell the node about the graph.
  7924. this.graphScaleInv = 1;
  7925. this.graphScale = 1;
  7926. this.canvasTopLeft = {"x": -300, "y": -300};
  7927. this.canvasBottomRight = {"x": 300, "y": 300};
  7928. this.parentEdgeId = null;
  7929. }
  7930. /**
  7931. * (re)setting the clustering variables and objects
  7932. */
  7933. Node.prototype.resetCluster = function() {
  7934. // clustering variables
  7935. this.formationScale = undefined; // this is used to determine when to open the cluster
  7936. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7937. this.containedNodes = {};
  7938. this.containedEdges = {};
  7939. this.clusterSessions = [];
  7940. };
  7941. /**
  7942. * Attach a edge to the node
  7943. * @param {Edge} edge
  7944. */
  7945. Node.prototype.attachEdge = function(edge) {
  7946. if (this.edges.indexOf(edge) == -1) {
  7947. this.edges.push(edge);
  7948. }
  7949. if (this.dynamicEdges.indexOf(edge) == -1) {
  7950. this.dynamicEdges.push(edge);
  7951. }
  7952. this.dynamicEdgesLength = this.dynamicEdges.length;
  7953. };
  7954. /**
  7955. * Detach a edge from the node
  7956. * @param {Edge} edge
  7957. */
  7958. Node.prototype.detachEdge = function(edge) {
  7959. var index = this.edges.indexOf(edge);
  7960. if (index != -1) {
  7961. this.edges.splice(index, 1);
  7962. this.dynamicEdges.splice(index, 1);
  7963. }
  7964. this.dynamicEdgesLength = this.dynamicEdges.length;
  7965. };
  7966. /**
  7967. * Set or overwrite properties for the node
  7968. * @param {Object} properties an object with properties
  7969. * @param {Object} constants and object with default, global properties
  7970. */
  7971. Node.prototype.setProperties = function(properties, constants) {
  7972. if (!properties) {
  7973. return;
  7974. }
  7975. this.originalLabel = undefined;
  7976. // basic properties
  7977. if (properties.id !== undefined) {this.id = properties.id;}
  7978. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7979. if (properties.title !== undefined) {this.title = properties.title;}
  7980. if (properties.group !== undefined) {this.group = properties.group;}
  7981. if (properties.x !== undefined) {this.x = properties.x;}
  7982. if (properties.y !== undefined) {this.y = properties.y;}
  7983. if (properties.value !== undefined) {this.value = properties.value;}
  7984. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  7985. // physics
  7986. if (properties.mass !== undefined) {this.mass = properties.mass;}
  7987. // navigation controls properties
  7988. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  7989. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  7990. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  7991. if (this.id === undefined) {
  7992. throw "Node must have an id";
  7993. }
  7994. // copy group properties
  7995. if (this.group) {
  7996. var groupObj = this.grouplist.get(this.group);
  7997. for (var prop in groupObj) {
  7998. if (groupObj.hasOwnProperty(prop)) {
  7999. this[prop] = groupObj[prop];
  8000. }
  8001. }
  8002. }
  8003. // individual shape properties
  8004. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8005. if (properties.image !== undefined) {this.image = properties.image;}
  8006. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8007. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  8008. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8009. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8010. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8011. if (this.image !== undefined && this.image != "") {
  8012. if (this.imagelist) {
  8013. this.imageObj = this.imagelist.load(this.image);
  8014. }
  8015. else {
  8016. throw "No imagelist provided";
  8017. }
  8018. }
  8019. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8020. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8021. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8022. if (this.shape == 'image') {
  8023. this.radiusMin = constants.nodes.widthMin;
  8024. this.radiusMax = constants.nodes.widthMax;
  8025. }
  8026. // choose draw method depending on the shape
  8027. switch (this.shape) {
  8028. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8029. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8030. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8031. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8032. // TODO: add diamond shape
  8033. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8034. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8035. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8036. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8037. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8038. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8039. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8040. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8041. }
  8042. // reset the size of the node, this can be changed
  8043. this._reset();
  8044. };
  8045. /**
  8046. * select this node
  8047. */
  8048. Node.prototype.select = function() {
  8049. this.selected = true;
  8050. this._reset();
  8051. };
  8052. /**
  8053. * unselect this node
  8054. */
  8055. Node.prototype.unselect = function() {
  8056. this.selected = false;
  8057. this._reset();
  8058. };
  8059. /**
  8060. * Reset the calculated size of the node, forces it to recalculate its size
  8061. */
  8062. Node.prototype.clearSizeCache = function() {
  8063. this._reset();
  8064. };
  8065. /**
  8066. * Reset the calculated size of the node, forces it to recalculate its size
  8067. * @private
  8068. */
  8069. Node.prototype._reset = function() {
  8070. this.width = undefined;
  8071. this.height = undefined;
  8072. };
  8073. /**
  8074. * get the title of this node.
  8075. * @return {string} title The title of the node, or undefined when no title
  8076. * has been set.
  8077. */
  8078. Node.prototype.getTitle = function() {
  8079. return typeof this.title === "function" ? this.title() : this.title;
  8080. };
  8081. /**
  8082. * Calculate the distance to the border of the Node
  8083. * @param {CanvasRenderingContext2D} ctx
  8084. * @param {Number} angle Angle in radians
  8085. * @returns {number} distance Distance to the border in pixels
  8086. */
  8087. Node.prototype.distanceToBorder = function (ctx, angle) {
  8088. var borderWidth = 1;
  8089. if (!this.width) {
  8090. this.resize(ctx);
  8091. }
  8092. switch (this.shape) {
  8093. case 'circle':
  8094. case 'dot':
  8095. return this.radius + borderWidth;
  8096. case 'ellipse':
  8097. var a = this.width / 2;
  8098. var b = this.height / 2;
  8099. var w = (Math.sin(angle) * a);
  8100. var h = (Math.cos(angle) * b);
  8101. return a * b / Math.sqrt(w * w + h * h);
  8102. // TODO: implement distanceToBorder for database
  8103. // TODO: implement distanceToBorder for triangle
  8104. // TODO: implement distanceToBorder for triangleDown
  8105. case 'box':
  8106. case 'image':
  8107. case 'text':
  8108. default:
  8109. if (this.width) {
  8110. return Math.min(
  8111. Math.abs(this.width / 2 / Math.cos(angle)),
  8112. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8113. // TODO: reckon with border radius too in case of box
  8114. }
  8115. else {
  8116. return 0;
  8117. }
  8118. }
  8119. // TODO: implement calculation of distance to border for all shapes
  8120. };
  8121. /**
  8122. * Set forces acting on the node
  8123. * @param {number} fx Force in horizontal direction
  8124. * @param {number} fy Force in vertical direction
  8125. */
  8126. Node.prototype._setForce = function(fx, fy) {
  8127. this.fx = fx;
  8128. this.fy = fy;
  8129. };
  8130. /**
  8131. * Add forces acting on the node
  8132. * @param {number} fx Force in horizontal direction
  8133. * @param {number} fy Force in vertical direction
  8134. * @private
  8135. */
  8136. Node.prototype._addForce = function(fx, fy) {
  8137. this.fx += fx;
  8138. this.fy += fy;
  8139. };
  8140. /**
  8141. * Perform one discrete step for the node
  8142. * @param {number} interval Time interval in seconds
  8143. */
  8144. Node.prototype.discreteStep = function(interval) {
  8145. if (!this.xFixed) {
  8146. var dx = this.damping * this.vx; // damping force
  8147. var ax = (this.fx - dx) / this.mass; // acceleration
  8148. this.vx += ax * interval; // velocity
  8149. this.x += this.vx * interval; // position
  8150. }
  8151. if (!this.yFixed) {
  8152. var dy = this.damping * this.vy; // damping force
  8153. var ay = (this.fy - dy) / this.mass; // acceleration
  8154. this.vy += ay * interval; // velocity
  8155. this.y += this.vy * interval; // position
  8156. }
  8157. };
  8158. /**
  8159. * Perform one discrete step for the node
  8160. * @param {number} interval Time interval in seconds
  8161. */
  8162. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8163. if (!this.xFixed) {
  8164. var dx = this.damping * this.vx; // damping force
  8165. var ax = (this.fx - dx) / this.mass; // acceleration
  8166. this.vx += ax * interval; // velocity
  8167. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8168. this.x += this.vx * interval; // position
  8169. }
  8170. else {
  8171. this.fx = 0;
  8172. }
  8173. if (!this.yFixed) {
  8174. var dy = this.damping * this.vy; // damping force
  8175. var ay = (this.fy - dy) / this.mass; // acceleration
  8176. this.vy += ay * interval; // velocity
  8177. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8178. this.y += this.vy * interval; // position
  8179. }
  8180. else {
  8181. this.fy = 0;
  8182. }
  8183. };
  8184. /**
  8185. * Check if this node has a fixed x and y position
  8186. * @return {boolean} true if fixed, false if not
  8187. */
  8188. Node.prototype.isFixed = function() {
  8189. return (this.xFixed && this.yFixed);
  8190. };
  8191. /**
  8192. * Check if this node is moving
  8193. * @param {number} vmin the minimum velocity considered as "moving"
  8194. * @return {boolean} true if moving, false if it has no velocity
  8195. */
  8196. // TODO: replace this method with calculating the kinetic energy
  8197. Node.prototype.isMoving = function(vmin) {
  8198. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8199. };
  8200. /**
  8201. * check if this node is selecte
  8202. * @return {boolean} selected True if node is selected, else false
  8203. */
  8204. Node.prototype.isSelected = function() {
  8205. return this.selected;
  8206. };
  8207. /**
  8208. * Retrieve the value of the node. Can be undefined
  8209. * @return {Number} value
  8210. */
  8211. Node.prototype.getValue = function() {
  8212. return this.value;
  8213. };
  8214. /**
  8215. * Calculate the distance from the nodes location to the given location (x,y)
  8216. * @param {Number} x
  8217. * @param {Number} y
  8218. * @return {Number} value
  8219. */
  8220. Node.prototype.getDistance = function(x, y) {
  8221. var dx = this.x - x,
  8222. dy = this.y - y;
  8223. return Math.sqrt(dx * dx + dy * dy);
  8224. };
  8225. /**
  8226. * Adjust the value range of the node. The node will adjust it's radius
  8227. * based on its value.
  8228. * @param {Number} min
  8229. * @param {Number} max
  8230. */
  8231. Node.prototype.setValueRange = function(min, max) {
  8232. if (!this.radiusFixed && this.value !== undefined) {
  8233. if (max == min) {
  8234. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8235. }
  8236. else {
  8237. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8238. this.radius = (this.value - min) * scale + this.radiusMin;
  8239. }
  8240. }
  8241. this.baseRadiusValue = this.radius;
  8242. };
  8243. /**
  8244. * Draw this node in the given canvas
  8245. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8246. * @param {CanvasRenderingContext2D} ctx
  8247. */
  8248. Node.prototype.draw = function(ctx) {
  8249. throw "Draw method not initialized for node";
  8250. };
  8251. /**
  8252. * Recalculate the size of this node in the given canvas
  8253. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8254. * @param {CanvasRenderingContext2D} ctx
  8255. */
  8256. Node.prototype.resize = function(ctx) {
  8257. throw "Resize method not initialized for node";
  8258. };
  8259. /**
  8260. * Check if this object is overlapping with the provided object
  8261. * @param {Object} obj an object with parameters left, top, right, bottom
  8262. * @return {boolean} True if location is located on node
  8263. */
  8264. Node.prototype.isOverlappingWith = function(obj) {
  8265. return (this.left < obj.right &&
  8266. this.left + this.width > obj.left &&
  8267. this.top < obj.bottom &&
  8268. this.top + this.height > obj.top);
  8269. };
  8270. Node.prototype._resizeImage = function (ctx) {
  8271. // TODO: pre calculate the image size
  8272. if (!this.width || !this.height) { // undefined or 0
  8273. var width, height;
  8274. if (this.value) {
  8275. this.radius = this.baseRadiusValue;
  8276. var scale = this.imageObj.height / this.imageObj.width;
  8277. if (scale !== undefined) {
  8278. width = this.radius || this.imageObj.width;
  8279. height = this.radius * scale || this.imageObj.height;
  8280. }
  8281. else {
  8282. width = 0;
  8283. height = 0;
  8284. }
  8285. }
  8286. else {
  8287. width = this.imageObj.width;
  8288. height = this.imageObj.height;
  8289. }
  8290. this.width = width;
  8291. this.height = height;
  8292. this.growthIndicator = 0;
  8293. if (this.width > 0 && this.height > 0) {
  8294. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8295. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8296. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8297. this.growthIndicator = this.width - width;
  8298. }
  8299. }
  8300. };
  8301. Node.prototype._drawImage = function (ctx) {
  8302. this._resizeImage(ctx);
  8303. this.left = this.x - this.width / 2;
  8304. this.top = this.y - this.height / 2;
  8305. var yLabel;
  8306. if (this.imageObj.width != 0 ) {
  8307. // draw the shade
  8308. if (this.clusterSize > 1) {
  8309. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8310. lineWidth *= this.graphScaleInv;
  8311. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8312. ctx.globalAlpha = 0.5;
  8313. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8314. }
  8315. // draw the image
  8316. ctx.globalAlpha = 1.0;
  8317. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8318. yLabel = this.y + this.height / 2;
  8319. }
  8320. else {
  8321. // image still loading... just draw the label for now
  8322. yLabel = this.y;
  8323. }
  8324. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8325. };
  8326. Node.prototype._resizeBox = function (ctx) {
  8327. if (!this.width) {
  8328. var margin = 5;
  8329. var textSize = this.getTextSize(ctx);
  8330. this.width = textSize.width + 2 * margin;
  8331. this.height = textSize.height + 2 * margin;
  8332. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8333. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8334. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8335. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8336. }
  8337. };
  8338. Node.prototype._drawBox = function (ctx) {
  8339. this._resizeBox(ctx);
  8340. this.left = this.x - this.width / 2;
  8341. this.top = this.y - this.height / 2;
  8342. var clusterLineWidth = 2.5;
  8343. var selectionLineWidth = 2;
  8344. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8345. // draw the outer border
  8346. if (this.clusterSize > 1) {
  8347. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8348. ctx.lineWidth *= this.graphScaleInv;
  8349. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8350. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8351. ctx.stroke();
  8352. }
  8353. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8354. ctx.lineWidth *= this.graphScaleInv;
  8355. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8356. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8357. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8358. ctx.fill();
  8359. ctx.stroke();
  8360. this._label(ctx, this.label, this.x, this.y);
  8361. };
  8362. Node.prototype._resizeDatabase = function (ctx) {
  8363. if (!this.width) {
  8364. var margin = 5;
  8365. var textSize = this.getTextSize(ctx);
  8366. var size = textSize.width + 2 * margin;
  8367. this.width = size;
  8368. this.height = size;
  8369. // scaling used for clustering
  8370. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8371. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8372. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8373. this.growthIndicator = this.width - size;
  8374. }
  8375. };
  8376. Node.prototype._drawDatabase = function (ctx) {
  8377. this._resizeDatabase(ctx);
  8378. this.left = this.x - this.width / 2;
  8379. this.top = this.y - this.height / 2;
  8380. var clusterLineWidth = 2.5;
  8381. var selectionLineWidth = 2;
  8382. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8383. // draw the outer border
  8384. if (this.clusterSize > 1) {
  8385. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8386. ctx.lineWidth *= this.graphScaleInv;
  8387. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8388. 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);
  8389. ctx.stroke();
  8390. }
  8391. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8392. ctx.lineWidth *= this.graphScaleInv;
  8393. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8394. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8395. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8396. ctx.fill();
  8397. ctx.stroke();
  8398. this._label(ctx, this.label, this.x, this.y);
  8399. };
  8400. Node.prototype._resizeCircle = function (ctx) {
  8401. if (!this.width) {
  8402. var margin = 5;
  8403. var textSize = this.getTextSize(ctx);
  8404. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8405. this.radius = diameter / 2;
  8406. this.width = diameter;
  8407. this.height = diameter;
  8408. // scaling used for clustering
  8409. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8410. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8411. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8412. this.growthIndicator = this.radius - 0.5*diameter;
  8413. }
  8414. };
  8415. Node.prototype._drawCircle = function (ctx) {
  8416. this._resizeCircle(ctx);
  8417. this.left = this.x - this.width / 2;
  8418. this.top = this.y - this.height / 2;
  8419. var clusterLineWidth = 2.5;
  8420. var selectionLineWidth = 2;
  8421. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8422. // draw the outer border
  8423. if (this.clusterSize > 1) {
  8424. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8425. ctx.lineWidth *= this.graphScaleInv;
  8426. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8427. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8428. ctx.stroke();
  8429. }
  8430. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8431. ctx.lineWidth *= this.graphScaleInv;
  8432. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8433. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8434. ctx.circle(this.x, this.y, this.radius);
  8435. ctx.fill();
  8436. ctx.stroke();
  8437. this._label(ctx, this.label, this.x, this.y);
  8438. };
  8439. Node.prototype._resizeEllipse = function (ctx) {
  8440. if (!this.width) {
  8441. var textSize = this.getTextSize(ctx);
  8442. this.width = textSize.width * 1.5;
  8443. this.height = textSize.height * 2;
  8444. if (this.width < this.height) {
  8445. this.width = this.height;
  8446. }
  8447. var defaultSize = this.width;
  8448. // scaling used for clustering
  8449. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8450. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8451. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8452. this.growthIndicator = this.width - defaultSize;
  8453. }
  8454. };
  8455. Node.prototype._drawEllipse = function (ctx) {
  8456. this._resizeEllipse(ctx);
  8457. this.left = this.x - this.width / 2;
  8458. this.top = this.y - this.height / 2;
  8459. var clusterLineWidth = 2.5;
  8460. var selectionLineWidth = 2;
  8461. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8462. // draw the outer border
  8463. if (this.clusterSize > 1) {
  8464. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8465. ctx.lineWidth *= this.graphScaleInv;
  8466. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8467. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8468. ctx.stroke();
  8469. }
  8470. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8471. ctx.lineWidth *= this.graphScaleInv;
  8472. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8473. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8474. ctx.ellipse(this.left, this.top, this.width, this.height);
  8475. ctx.fill();
  8476. ctx.stroke();
  8477. this._label(ctx, this.label, this.x, this.y);
  8478. };
  8479. Node.prototype._drawDot = function (ctx) {
  8480. this._drawShape(ctx, 'circle');
  8481. };
  8482. Node.prototype._drawTriangle = function (ctx) {
  8483. this._drawShape(ctx, 'triangle');
  8484. };
  8485. Node.prototype._drawTriangleDown = function (ctx) {
  8486. this._drawShape(ctx, 'triangleDown');
  8487. };
  8488. Node.prototype._drawSquare = function (ctx) {
  8489. this._drawShape(ctx, 'square');
  8490. };
  8491. Node.prototype._drawStar = function (ctx) {
  8492. this._drawShape(ctx, 'star');
  8493. };
  8494. Node.prototype._resizeShape = function (ctx) {
  8495. if (!this.width) {
  8496. this.radius = this.baseRadiusValue;
  8497. var size = 2 * this.radius;
  8498. this.width = size;
  8499. this.height = size;
  8500. // scaling used for clustering
  8501. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8502. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8503. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8504. this.growthIndicator = this.width - size;
  8505. }
  8506. };
  8507. Node.prototype._drawShape = function (ctx, shape) {
  8508. this._resizeShape(ctx);
  8509. this.left = this.x - this.width / 2;
  8510. this.top = this.y - this.height / 2;
  8511. var clusterLineWidth = 2.5;
  8512. var selectionLineWidth = 2;
  8513. var radiusMultiplier = 2;
  8514. // choose draw method depending on the shape
  8515. switch (shape) {
  8516. case 'dot': radiusMultiplier = 2; break;
  8517. case 'square': radiusMultiplier = 2; break;
  8518. case 'triangle': radiusMultiplier = 3; break;
  8519. case 'triangleDown': radiusMultiplier = 3; break;
  8520. case 'star': radiusMultiplier = 4; break;
  8521. }
  8522. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8523. // draw the outer border
  8524. if (this.clusterSize > 1) {
  8525. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8526. ctx.lineWidth *= this.graphScaleInv;
  8527. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8528. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8529. ctx.stroke();
  8530. }
  8531. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8532. ctx.lineWidth *= this.graphScaleInv;
  8533. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8534. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8535. ctx[shape](this.x, this.y, this.radius);
  8536. ctx.fill();
  8537. ctx.stroke();
  8538. if (this.label) {
  8539. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8540. }
  8541. };
  8542. Node.prototype._resizeText = function (ctx) {
  8543. if (!this.width) {
  8544. var margin = 5;
  8545. var textSize = this.getTextSize(ctx);
  8546. this.width = textSize.width + 2 * margin;
  8547. this.height = textSize.height + 2 * margin;
  8548. // scaling used for clustering
  8549. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8550. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8551. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8552. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8553. }
  8554. };
  8555. Node.prototype._drawText = function (ctx) {
  8556. this._resizeText(ctx);
  8557. this.left = this.x - this.width / 2;
  8558. this.top = this.y - this.height / 2;
  8559. this._label(ctx, this.label, this.x, this.y);
  8560. };
  8561. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8562. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8563. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8564. ctx.fillStyle = this.fontColor || "black";
  8565. ctx.textAlign = align || "center";
  8566. ctx.textBaseline = baseline || "middle";
  8567. var lines = text.split('\n'),
  8568. lineCount = lines.length,
  8569. fontSize = (this.fontSize + 4),
  8570. yLine = y + (1 - lineCount) / 2 * fontSize;
  8571. for (var i = 0; i < lineCount; i++) {
  8572. ctx.fillText(lines[i], x, yLine);
  8573. yLine += fontSize;
  8574. }
  8575. }
  8576. };
  8577. Node.prototype.getTextSize = function(ctx) {
  8578. if (this.label !== undefined) {
  8579. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8580. var lines = this.label.split('\n'),
  8581. height = (this.fontSize + 4) * lines.length,
  8582. width = 0;
  8583. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8584. width = Math.max(width, ctx.measureText(lines[i]).width);
  8585. }
  8586. return {"width": width, "height": height};
  8587. }
  8588. else {
  8589. return {"width": 0, "height": 0};
  8590. }
  8591. };
  8592. /**
  8593. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8594. * there is a safety margin of 0.3 * width;
  8595. *
  8596. * @returns {boolean}
  8597. */
  8598. Node.prototype.inArea = function() {
  8599. if (this.width !== undefined) {
  8600. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8601. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8602. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8603. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8604. }
  8605. else {
  8606. return true;
  8607. }
  8608. };
  8609. /**
  8610. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8611. * @returns {boolean}
  8612. */
  8613. Node.prototype.inView = function() {
  8614. return (this.x >= this.canvasTopLeft.x &&
  8615. this.x < this.canvasBottomRight.x &&
  8616. this.y >= this.canvasTopLeft.y &&
  8617. this.y < this.canvasBottomRight.y);
  8618. };
  8619. /**
  8620. * This allows the zoom level of the graph to influence the rendering
  8621. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8622. *
  8623. * @param scale
  8624. * @param canvasTopLeft
  8625. * @param canvasBottomRight
  8626. */
  8627. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8628. this.graphScaleInv = 1.0/scale;
  8629. this.graphScale = scale;
  8630. this.canvasTopLeft = canvasTopLeft;
  8631. this.canvasBottomRight = canvasBottomRight;
  8632. };
  8633. /**
  8634. * This allows the zoom level of the graph to influence the rendering
  8635. *
  8636. * @param scale
  8637. */
  8638. Node.prototype.setScale = function(scale) {
  8639. this.graphScaleInv = 1.0/scale;
  8640. this.graphScale = scale;
  8641. };
  8642. /**
  8643. * set the velocity at 0. Is called when this node is contained in another during clustering
  8644. */
  8645. Node.prototype.clearVelocity = function() {
  8646. this.vx = 0;
  8647. this.vy = 0;
  8648. };
  8649. /**
  8650. * Basic preservation of (kinectic) energy
  8651. *
  8652. * @param massBeforeClustering
  8653. */
  8654. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8655. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8656. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8657. this.vx = Math.sqrt(energyBefore/this.mass);
  8658. energyBefore = this.vy * this.vy * massBeforeClustering;
  8659. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8660. this.vy = Math.sqrt(energyBefore/this.mass);
  8661. };
  8662. /**
  8663. * @class Edge
  8664. *
  8665. * A edge connects two nodes
  8666. * @param {Object} properties Object with properties. Must contain
  8667. * At least properties from and to.
  8668. * Available properties: from (number),
  8669. * to (number), label (string, color (string),
  8670. * width (number), style (string),
  8671. * length (number), title (string)
  8672. * @param {Graph} graph A graph object, used to find and edge to
  8673. * nodes.
  8674. * @param {Object} constants An object with default values for
  8675. * example for the color
  8676. */
  8677. function Edge (properties, graph, constants) {
  8678. if (!graph) {
  8679. throw "No graph provided";
  8680. }
  8681. this.graph = graph;
  8682. // initialize constants
  8683. this.widthMin = constants.edges.widthMin;
  8684. this.widthMax = constants.edges.widthMax;
  8685. // initialize variables
  8686. this.id = undefined;
  8687. this.fromId = undefined;
  8688. this.toId = undefined;
  8689. this.style = constants.edges.style;
  8690. this.title = undefined;
  8691. this.width = constants.edges.width;
  8692. this.value = undefined;
  8693. this.length = constants.physics.springLength;
  8694. this.customLength = false;
  8695. this.selected = false;
  8696. this.smooth = constants.smoothCurves;
  8697. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  8698. this.from = null; // a node
  8699. this.to = null; // a node
  8700. this.via = null; // a temp node
  8701. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8702. // by storing the original information we can revert to the original connection when the cluser is opened.
  8703. this.originalFromId = [];
  8704. this.originalToId = [];
  8705. this.connected = false;
  8706. // Added to support dashed lines
  8707. // David Jordan
  8708. // 2012-08-08
  8709. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8710. this.color = {color:constants.edges.color.color,
  8711. highlight:constants.edges.color.highlight};
  8712. this.widthFixed = false;
  8713. this.lengthFixed = false;
  8714. this.setProperties(properties, constants);
  8715. }
  8716. /**
  8717. * Set or overwrite properties for the edge
  8718. * @param {Object} properties an object with properties
  8719. * @param {Object} constants and object with default, global properties
  8720. */
  8721. Edge.prototype.setProperties = function(properties, constants) {
  8722. if (!properties) {
  8723. return;
  8724. }
  8725. if (properties.from !== undefined) {this.fromId = properties.from;}
  8726. if (properties.to !== undefined) {this.toId = properties.to;}
  8727. if (properties.id !== undefined) {this.id = properties.id;}
  8728. if (properties.style !== undefined) {this.style = properties.style;}
  8729. if (properties.label !== undefined) {this.label = properties.label;}
  8730. if (this.label) {
  8731. this.fontSize = constants.edges.fontSize;
  8732. this.fontFace = constants.edges.fontFace;
  8733. this.fontColor = constants.edges.fontColor;
  8734. this.fontFill = constants.edges.fontFill;
  8735. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8736. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8737. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8738. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8739. }
  8740. if (properties.title !== undefined) {this.title = properties.title;}
  8741. if (properties.width !== undefined) {this.width = properties.width;}
  8742. if (properties.value !== undefined) {this.value = properties.value;}
  8743. if (properties.length !== undefined) {this.length = properties.length;
  8744. this.customLength = true;}
  8745. // scale the arrow
  8746. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor};
  8747. // Added to support dashed lines
  8748. // David Jordan
  8749. // 2012-08-08
  8750. if (properties.dash) {
  8751. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8752. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8753. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8754. }
  8755. if (properties.color !== undefined) {
  8756. if (util.isString(properties.color)) {
  8757. this.color.color = properties.color;
  8758. this.color.highlight = properties.color;
  8759. }
  8760. else {
  8761. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8762. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8763. }
  8764. }
  8765. // A node is connected when it has a from and to node.
  8766. this.connect();
  8767. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8768. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8769. // set draw method based on style
  8770. switch (this.style) {
  8771. case 'line': this.draw = this._drawLine; break;
  8772. case 'arrow': this.draw = this._drawArrow; break;
  8773. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8774. case 'dash-line': this.draw = this._drawDashLine; break;
  8775. default: this.draw = this._drawLine; break;
  8776. }
  8777. };
  8778. /**
  8779. * Connect an edge to its nodes
  8780. */
  8781. Edge.prototype.connect = function () {
  8782. this.disconnect();
  8783. this.from = this.graph.nodes[this.fromId] || null;
  8784. this.to = this.graph.nodes[this.toId] || null;
  8785. this.connected = (this.from && this.to);
  8786. if (this.connected) {
  8787. this.from.attachEdge(this);
  8788. this.to.attachEdge(this);
  8789. }
  8790. else {
  8791. if (this.from) {
  8792. this.from.detachEdge(this);
  8793. }
  8794. if (this.to) {
  8795. this.to.detachEdge(this);
  8796. }
  8797. }
  8798. };
  8799. /**
  8800. * Disconnect an edge from its nodes
  8801. */
  8802. Edge.prototype.disconnect = function () {
  8803. if (this.from) {
  8804. this.from.detachEdge(this);
  8805. this.from = null;
  8806. }
  8807. if (this.to) {
  8808. this.to.detachEdge(this);
  8809. this.to = null;
  8810. }
  8811. this.connected = false;
  8812. };
  8813. /**
  8814. * get the title of this edge.
  8815. * @return {string} title The title of the edge, or undefined when no title
  8816. * has been set.
  8817. */
  8818. Edge.prototype.getTitle = function() {
  8819. return typeof this.title === "function" ? this.title() : this.title;
  8820. };
  8821. /**
  8822. * Retrieve the value of the edge. Can be undefined
  8823. * @return {Number} value
  8824. */
  8825. Edge.prototype.getValue = function() {
  8826. return this.value;
  8827. };
  8828. /**
  8829. * Adjust the value range of the edge. The edge will adjust it's width
  8830. * based on its value.
  8831. * @param {Number} min
  8832. * @param {Number} max
  8833. */
  8834. Edge.prototype.setValueRange = function(min, max) {
  8835. if (!this.widthFixed && this.value !== undefined) {
  8836. var scale = (this.widthMax - this.widthMin) / (max - min);
  8837. this.width = (this.value - min) * scale + this.widthMin;
  8838. }
  8839. };
  8840. /**
  8841. * Redraw a edge
  8842. * Draw this edge in the given canvas
  8843. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8844. * @param {CanvasRenderingContext2D} ctx
  8845. */
  8846. Edge.prototype.draw = function(ctx) {
  8847. throw "Method draw not initialized in edge";
  8848. };
  8849. /**
  8850. * Check if this object is overlapping with the provided object
  8851. * @param {Object} obj an object with parameters left, top
  8852. * @return {boolean} True if location is located on the edge
  8853. */
  8854. Edge.prototype.isOverlappingWith = function(obj) {
  8855. if (this.connected) {
  8856. var distMax = 10;
  8857. var xFrom = this.from.x;
  8858. var yFrom = this.from.y;
  8859. var xTo = this.to.x;
  8860. var yTo = this.to.y;
  8861. var xObj = obj.left;
  8862. var yObj = obj.top;
  8863. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8864. return (dist < distMax);
  8865. }
  8866. else {
  8867. return false
  8868. }
  8869. };
  8870. /**
  8871. * Redraw a edge as a line
  8872. * Draw this edge in the given canvas
  8873. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8874. * @param {CanvasRenderingContext2D} ctx
  8875. * @private
  8876. */
  8877. Edge.prototype._drawLine = function(ctx) {
  8878. // set style
  8879. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8880. else {ctx.strokeStyle = this.color.color;}
  8881. ctx.lineWidth = this._getLineWidth();
  8882. if (this.from != this.to) {
  8883. // draw line
  8884. this._line(ctx);
  8885. // draw label
  8886. var point;
  8887. if (this.label) {
  8888. if (this.smooth == true) {
  8889. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8890. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8891. point = {x:midpointX, y:midpointY};
  8892. }
  8893. else {
  8894. point = this._pointOnLine(0.5);
  8895. }
  8896. this._label(ctx, this.label, point.x, point.y);
  8897. }
  8898. }
  8899. else {
  8900. var x, y;
  8901. var radius = this.length / 4;
  8902. var node = this.from;
  8903. if (!node.width) {
  8904. node.resize(ctx);
  8905. }
  8906. if (node.width > node.height) {
  8907. x = node.x + node.width / 2;
  8908. y = node.y - radius;
  8909. }
  8910. else {
  8911. x = node.x + radius;
  8912. y = node.y - node.height / 2;
  8913. }
  8914. this._circle(ctx, x, y, radius);
  8915. point = this._pointOnCircle(x, y, radius, 0.5);
  8916. this._label(ctx, this.label, point.x, point.y);
  8917. }
  8918. };
  8919. /**
  8920. * Get the line width of the edge. Depends on width and whether one of the
  8921. * connected nodes is selected.
  8922. * @return {Number} width
  8923. * @private
  8924. */
  8925. Edge.prototype._getLineWidth = function() {
  8926. if (this.selected == true) {
  8927. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8928. }
  8929. else {
  8930. return this.width*this.graphScaleInv;
  8931. }
  8932. };
  8933. /**
  8934. * Draw a line between two nodes
  8935. * @param {CanvasRenderingContext2D} ctx
  8936. * @private
  8937. */
  8938. Edge.prototype._line = function (ctx) {
  8939. // draw a straight line
  8940. ctx.beginPath();
  8941. ctx.moveTo(this.from.x, this.from.y);
  8942. if (this.smooth == true) {
  8943. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8944. }
  8945. else {
  8946. ctx.lineTo(this.to.x, this.to.y);
  8947. }
  8948. ctx.stroke();
  8949. };
  8950. /**
  8951. * Draw a line from a node to itself, a circle
  8952. * @param {CanvasRenderingContext2D} ctx
  8953. * @param {Number} x
  8954. * @param {Number} y
  8955. * @param {Number} radius
  8956. * @private
  8957. */
  8958. Edge.prototype._circle = function (ctx, x, y, radius) {
  8959. // draw a circle
  8960. ctx.beginPath();
  8961. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8962. ctx.stroke();
  8963. };
  8964. /**
  8965. * Draw label with white background and with the middle at (x, y)
  8966. * @param {CanvasRenderingContext2D} ctx
  8967. * @param {String} text
  8968. * @param {Number} x
  8969. * @param {Number} y
  8970. * @private
  8971. */
  8972. Edge.prototype._label = function (ctx, text, x, y) {
  8973. if (text) {
  8974. // TODO: cache the calculated size
  8975. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8976. this.fontSize + "px " + this.fontFace;
  8977. ctx.fillStyle = this.fontFill;
  8978. var width = ctx.measureText(text).width;
  8979. var height = this.fontSize;
  8980. var left = x - width / 2;
  8981. var top = y - height / 2;
  8982. ctx.fillRect(left, top, width, height);
  8983. // draw text
  8984. ctx.fillStyle = this.fontColor || "black";
  8985. ctx.textAlign = "left";
  8986. ctx.textBaseline = "top";
  8987. ctx.fillText(text, left, top);
  8988. }
  8989. };
  8990. /**
  8991. * Redraw a edge as a dashed line
  8992. * Draw this edge in the given canvas
  8993. * @author David Jordan
  8994. * @date 2012-08-08
  8995. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8996. * @param {CanvasRenderingContext2D} ctx
  8997. * @private
  8998. */
  8999. Edge.prototype._drawDashLine = function(ctx) {
  9000. // set style
  9001. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9002. else {ctx.strokeStyle = this.color.color;}
  9003. ctx.lineWidth = this._getLineWidth();
  9004. // only firefox and chrome support this method, else we use the legacy one.
  9005. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9006. ctx.beginPath();
  9007. ctx.moveTo(this.from.x, this.from.y);
  9008. // configure the dash pattern
  9009. var pattern = [0];
  9010. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9011. pattern = [this.dash.length,this.dash.gap];
  9012. }
  9013. else {
  9014. pattern = [5,5];
  9015. }
  9016. // set dash settings for chrome or firefox
  9017. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9018. ctx.setLineDash(pattern);
  9019. ctx.lineDashOffset = 0;
  9020. } else { //Firefox
  9021. ctx.mozDash = pattern;
  9022. ctx.mozDashOffset = 0;
  9023. }
  9024. // draw the line
  9025. if (this.smooth == true) {
  9026. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9027. }
  9028. else {
  9029. ctx.lineTo(this.to.x, this.to.y);
  9030. }
  9031. ctx.stroke();
  9032. // restore the dash settings.
  9033. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9034. ctx.setLineDash([0]);
  9035. ctx.lineDashOffset = 0;
  9036. } else { //Firefox
  9037. ctx.mozDash = [0];
  9038. ctx.mozDashOffset = 0;
  9039. }
  9040. }
  9041. else { // unsupporting smooth lines
  9042. // draw dashed line
  9043. ctx.beginPath();
  9044. ctx.lineCap = 'round';
  9045. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9046. {
  9047. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9048. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9049. }
  9050. else if (this.dash.length !== undefined && this.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
  9051. {
  9052. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9053. [this.dash.length,this.dash.gap]);
  9054. }
  9055. else //If all else fails draw a line
  9056. {
  9057. ctx.moveTo(this.from.x, this.from.y);
  9058. ctx.lineTo(this.to.x, this.to.y);
  9059. }
  9060. ctx.stroke();
  9061. }
  9062. // draw label
  9063. if (this.label) {
  9064. var point;
  9065. if (this.smooth == true) {
  9066. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9067. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9068. point = {x:midpointX, y:midpointY};
  9069. }
  9070. else {
  9071. point = this._pointOnLine(0.5);
  9072. }
  9073. this._label(ctx, this.label, point.x, point.y);
  9074. }
  9075. };
  9076. /**
  9077. * Get a point on a line
  9078. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9079. * @return {Object} point
  9080. * @private
  9081. */
  9082. Edge.prototype._pointOnLine = function (percentage) {
  9083. return {
  9084. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9085. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9086. }
  9087. };
  9088. /**
  9089. * Get a point on a circle
  9090. * @param {Number} x
  9091. * @param {Number} y
  9092. * @param {Number} radius
  9093. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9094. * @return {Object} point
  9095. * @private
  9096. */
  9097. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9098. var angle = (percentage - 3/8) * 2 * Math.PI;
  9099. return {
  9100. x: x + radius * Math.cos(angle),
  9101. y: y - radius * Math.sin(angle)
  9102. }
  9103. };
  9104. /**
  9105. * Redraw a edge as a line with an arrow halfway the line
  9106. * Draw this edge in the given canvas
  9107. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9108. * @param {CanvasRenderingContext2D} ctx
  9109. * @private
  9110. */
  9111. Edge.prototype._drawArrowCenter = function(ctx) {
  9112. var point;
  9113. // set style
  9114. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9115. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9116. ctx.lineWidth = this._getLineWidth();
  9117. if (this.from != this.to) {
  9118. // draw line
  9119. this._line(ctx);
  9120. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9121. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9122. // draw an arrow halfway the line
  9123. if (this.smooth == true) {
  9124. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9125. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9126. point = {x:midpointX, y:midpointY};
  9127. }
  9128. else {
  9129. point = this._pointOnLine(0.5);
  9130. }
  9131. ctx.arrow(point.x, point.y, angle, length);
  9132. ctx.fill();
  9133. ctx.stroke();
  9134. // draw label
  9135. if (this.label) {
  9136. this._label(ctx, this.label, point.x, point.y);
  9137. }
  9138. }
  9139. else {
  9140. // draw circle
  9141. var x, y;
  9142. var radius = 0.25 * Math.max(100,this.length);
  9143. var node = this.from;
  9144. if (!node.width) {
  9145. node.resize(ctx);
  9146. }
  9147. if (node.width > node.height) {
  9148. x = node.x + node.width * 0.5;
  9149. y = node.y - radius;
  9150. }
  9151. else {
  9152. x = node.x + radius;
  9153. y = node.y - node.height * 0.5;
  9154. }
  9155. this._circle(ctx, x, y, radius);
  9156. // draw all arrows
  9157. var angle = 0.2 * Math.PI;
  9158. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9159. point = this._pointOnCircle(x, y, radius, 0.5);
  9160. ctx.arrow(point.x, point.y, angle, length);
  9161. ctx.fill();
  9162. ctx.stroke();
  9163. // draw label
  9164. if (this.label) {
  9165. point = this._pointOnCircle(x, y, radius, 0.5);
  9166. this._label(ctx, this.label, point.x, point.y);
  9167. }
  9168. }
  9169. };
  9170. /**
  9171. * Redraw a edge as a line with an arrow
  9172. * Draw this edge in the given canvas
  9173. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9174. * @param {CanvasRenderingContext2D} ctx
  9175. * @private
  9176. */
  9177. Edge.prototype._drawArrow = function(ctx) {
  9178. // set style
  9179. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9180. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9181. ctx.lineWidth = this._getLineWidth();
  9182. var angle, length;
  9183. //draw a line
  9184. if (this.from != this.to) {
  9185. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9186. var dx = (this.to.x - this.from.x);
  9187. var dy = (this.to.y - this.from.y);
  9188. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9189. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9190. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9191. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9192. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9193. if (this.smooth == true) {
  9194. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9195. dx = (this.to.x - this.via.x);
  9196. dy = (this.to.y - this.via.y);
  9197. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9198. }
  9199. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9200. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9201. var xTo,yTo;
  9202. if (this.smooth == true) {
  9203. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9204. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9205. }
  9206. else {
  9207. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9208. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9209. }
  9210. ctx.beginPath();
  9211. ctx.moveTo(xFrom,yFrom);
  9212. if (this.smooth == true) {
  9213. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9214. }
  9215. else {
  9216. ctx.lineTo(xTo, yTo);
  9217. }
  9218. ctx.stroke();
  9219. // draw arrow at the end of the line
  9220. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9221. ctx.arrow(xTo, yTo, angle, length);
  9222. ctx.fill();
  9223. ctx.stroke();
  9224. // draw label
  9225. if (this.label) {
  9226. var point;
  9227. if (this.smooth == true) {
  9228. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9229. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9230. point = {x:midpointX, y:midpointY};
  9231. }
  9232. else {
  9233. point = this._pointOnLine(0.5);
  9234. }
  9235. this._label(ctx, this.label, point.x, point.y);
  9236. }
  9237. }
  9238. else {
  9239. // draw circle
  9240. var node = this.from;
  9241. var x, y, arrow;
  9242. var radius = 0.25 * Math.max(100,this.length);
  9243. if (!node.width) {
  9244. node.resize(ctx);
  9245. }
  9246. if (node.width > node.height) {
  9247. x = node.x + node.width * 0.5;
  9248. y = node.y - radius;
  9249. arrow = {
  9250. x: x,
  9251. y: node.y,
  9252. angle: 0.9 * Math.PI
  9253. };
  9254. }
  9255. else {
  9256. x = node.x + radius;
  9257. y = node.y - node.height * 0.5;
  9258. arrow = {
  9259. x: node.x,
  9260. y: y,
  9261. angle: 0.6 * Math.PI
  9262. };
  9263. }
  9264. ctx.beginPath();
  9265. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9266. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9267. ctx.stroke();
  9268. // draw all arrows
  9269. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9270. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9271. ctx.fill();
  9272. ctx.stroke();
  9273. // draw label
  9274. if (this.label) {
  9275. point = this._pointOnCircle(x, y, radius, 0.5);
  9276. this._label(ctx, this.label, point.x, point.y);
  9277. }
  9278. }
  9279. };
  9280. /**
  9281. * Calculate the distance between a point (x3,y3) and a line segment from
  9282. * (x1,y1) to (x2,y2).
  9283. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9284. * @param {number} x1
  9285. * @param {number} y1
  9286. * @param {number} x2
  9287. * @param {number} y2
  9288. * @param {number} x3
  9289. * @param {number} y3
  9290. * @private
  9291. */
  9292. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9293. if (this.smooth == true) {
  9294. var minDistance = 1e9;
  9295. var i,t,x,y,dx,dy;
  9296. for (i = 0; i < 10; i++) {
  9297. t = 0.1*i;
  9298. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9299. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9300. dx = Math.abs(x3-x);
  9301. dy = Math.abs(y3-y);
  9302. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9303. }
  9304. return minDistance
  9305. }
  9306. else {
  9307. var px = x2-x1,
  9308. py = y2-y1,
  9309. something = px*px + py*py,
  9310. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9311. if (u > 1) {
  9312. u = 1;
  9313. }
  9314. else if (u < 0) {
  9315. u = 0;
  9316. }
  9317. var x = x1 + u * px,
  9318. y = y1 + u * py,
  9319. dx = x - x3,
  9320. dy = y - y3;
  9321. //# Note: If the actual distance does not matter,
  9322. //# if you only want to compare what this function
  9323. //# returns to other results of this function, you
  9324. //# can just return the squared distance instead
  9325. //# (i.e. remove the sqrt) to gain a little performance
  9326. return Math.sqrt(dx*dx + dy*dy);
  9327. }
  9328. };
  9329. /**
  9330. * This allows the zoom level of the graph to influence the rendering
  9331. *
  9332. * @param scale
  9333. */
  9334. Edge.prototype.setScale = function(scale) {
  9335. this.graphScaleInv = 1.0/scale;
  9336. };
  9337. Edge.prototype.select = function() {
  9338. this.selected = true;
  9339. };
  9340. Edge.prototype.unselect = function() {
  9341. this.selected = false;
  9342. };
  9343. Edge.prototype.positionBezierNode = function() {
  9344. if (this.via !== null) {
  9345. this.via.x = 0.5 * (this.from.x + this.to.x);
  9346. this.via.y = 0.5 * (this.from.y + this.to.y);
  9347. }
  9348. };
  9349. /**
  9350. * Popup is a class to create a popup window with some text
  9351. * @param {Element} container The container object.
  9352. * @param {Number} [x]
  9353. * @param {Number} [y]
  9354. * @param {String} [text]
  9355. * @param {Object} [style] An object containing borderColor,
  9356. * backgroundColor, etc.
  9357. */
  9358. function Popup(container, x, y, text, style) {
  9359. if (container) {
  9360. this.container = container;
  9361. }
  9362. else {
  9363. this.container = document.body;
  9364. }
  9365. // x, y and text are optional, see if a style object was passed in their place
  9366. if (style === undefined) {
  9367. if (typeof x === "object") {
  9368. style = x;
  9369. x = undefined;
  9370. } else if (typeof text === "object") {
  9371. style = text;
  9372. text = undefined;
  9373. } else {
  9374. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9375. style = {
  9376. fontColor: 'black',
  9377. fontSize: 14, // px
  9378. fontFace: 'verdana',
  9379. color: {
  9380. border: '#666',
  9381. background: '#FFFFC6'
  9382. }
  9383. }
  9384. }
  9385. }
  9386. this.x = 0;
  9387. this.y = 0;
  9388. this.padding = 5;
  9389. if (x !== undefined && y !== undefined ) {
  9390. this.setPosition(x, y);
  9391. }
  9392. if (text !== undefined) {
  9393. this.setText(text);
  9394. }
  9395. // create the frame
  9396. this.frame = document.createElement("div");
  9397. var styleAttr = this.frame.style;
  9398. styleAttr.position = "absolute";
  9399. styleAttr.visibility = "hidden";
  9400. styleAttr.border = "1px solid " + style.color.border;
  9401. styleAttr.color = style.fontColor;
  9402. styleAttr.fontSize = style.fontSize + "px";
  9403. styleAttr.fontFamily = style.fontFace;
  9404. styleAttr.padding = this.padding + "px";
  9405. styleAttr.backgroundColor = style.color.background;
  9406. styleAttr.borderRadius = "3px";
  9407. styleAttr.MozBorderRadius = "3px";
  9408. styleAttr.WebkitBorderRadius = "3px";
  9409. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9410. styleAttr.whiteSpace = "nowrap";
  9411. this.container.appendChild(this.frame);
  9412. }
  9413. /**
  9414. * @param {number} x Horizontal position of the popup window
  9415. * @param {number} y Vertical position of the popup window
  9416. */
  9417. Popup.prototype.setPosition = function(x, y) {
  9418. this.x = parseInt(x);
  9419. this.y = parseInt(y);
  9420. };
  9421. /**
  9422. * Set the text for the popup window. This can be HTML code
  9423. * @param {string} text
  9424. */
  9425. Popup.prototype.setText = function(text) {
  9426. this.frame.innerHTML = text;
  9427. };
  9428. /**
  9429. * Show the popup window
  9430. * @param {boolean} show Optional. Show or hide the window
  9431. */
  9432. Popup.prototype.show = function (show) {
  9433. if (show === undefined) {
  9434. show = true;
  9435. }
  9436. if (show) {
  9437. var height = this.frame.clientHeight;
  9438. var width = this.frame.clientWidth;
  9439. var maxHeight = this.frame.parentNode.clientHeight;
  9440. var maxWidth = this.frame.parentNode.clientWidth;
  9441. var top = (this.y - height);
  9442. if (top + height + this.padding > maxHeight) {
  9443. top = maxHeight - height - this.padding;
  9444. }
  9445. if (top < this.padding) {
  9446. top = this.padding;
  9447. }
  9448. var left = this.x;
  9449. if (left + width + this.padding > maxWidth) {
  9450. left = maxWidth - width - this.padding;
  9451. }
  9452. if (left < this.padding) {
  9453. left = this.padding;
  9454. }
  9455. this.frame.style.left = left + "px";
  9456. this.frame.style.top = top + "px";
  9457. this.frame.style.visibility = "visible";
  9458. }
  9459. else {
  9460. this.hide();
  9461. }
  9462. };
  9463. /**
  9464. * Hide the popup window
  9465. */
  9466. Popup.prototype.hide = function () {
  9467. this.frame.style.visibility = "hidden";
  9468. };
  9469. /**
  9470. * @class Groups
  9471. * This class can store groups and properties specific for groups.
  9472. */
  9473. Groups = function () {
  9474. this.clear();
  9475. this.defaultIndex = 0;
  9476. };
  9477. /**
  9478. * default constants for group colors
  9479. */
  9480. Groups.DEFAULT = [
  9481. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9482. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9483. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9484. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9485. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9486. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9487. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9488. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9489. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9490. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9491. ];
  9492. /**
  9493. * Clear all groups
  9494. */
  9495. Groups.prototype.clear = function () {
  9496. this.groups = {};
  9497. this.groups.length = function()
  9498. {
  9499. var i = 0;
  9500. for ( var p in this ) {
  9501. if (this.hasOwnProperty(p)) {
  9502. i++;
  9503. }
  9504. }
  9505. return i;
  9506. }
  9507. };
  9508. /**
  9509. * get group properties of a groupname. If groupname is not found, a new group
  9510. * is added.
  9511. * @param {*} groupname Can be a number, string, Date, etc.
  9512. * @return {Object} group The created group, containing all group properties
  9513. */
  9514. Groups.prototype.get = function (groupname) {
  9515. var group = this.groups[groupname];
  9516. if (group == undefined) {
  9517. // create new group
  9518. var index = this.defaultIndex % Groups.DEFAULT.length;
  9519. this.defaultIndex++;
  9520. group = {};
  9521. group.color = Groups.DEFAULT[index];
  9522. this.groups[groupname] = group;
  9523. }
  9524. return group;
  9525. };
  9526. /**
  9527. * Add a custom group style
  9528. * @param {String} groupname
  9529. * @param {Object} style An object containing borderColor,
  9530. * backgroundColor, etc.
  9531. * @return {Object} group The created group object
  9532. */
  9533. Groups.prototype.add = function (groupname, style) {
  9534. this.groups[groupname] = style;
  9535. if (style.color) {
  9536. style.color = util.parseColor(style.color);
  9537. }
  9538. return style;
  9539. };
  9540. /**
  9541. * @class Images
  9542. * This class loads images and keeps them stored.
  9543. */
  9544. Images = function () {
  9545. this.images = {};
  9546. this.callback = undefined;
  9547. };
  9548. /**
  9549. * Set an onload callback function. This will be called each time an image
  9550. * is loaded
  9551. * @param {function} callback
  9552. */
  9553. Images.prototype.setOnloadCallback = function(callback) {
  9554. this.callback = callback;
  9555. };
  9556. /**
  9557. *
  9558. * @param {string} url Url of the image
  9559. * @return {Image} img The image object
  9560. */
  9561. Images.prototype.load = function(url) {
  9562. var img = this.images[url];
  9563. if (img == undefined) {
  9564. // create the image
  9565. var images = this;
  9566. img = new Image();
  9567. this.images[url] = img;
  9568. img.onload = function() {
  9569. if (images.callback) {
  9570. images.callback(this);
  9571. }
  9572. };
  9573. img.src = url;
  9574. }
  9575. return img;
  9576. };
  9577. /**
  9578. * Created by Alex on 2/6/14.
  9579. */
  9580. var physicsMixin = {
  9581. /**
  9582. * Toggling barnes Hut calculation on and off.
  9583. *
  9584. * @private
  9585. */
  9586. _toggleBarnesHut: function () {
  9587. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9588. this._loadSelectedForceSolver();
  9589. this.moving = true;
  9590. this.start();
  9591. },
  9592. /**
  9593. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9594. *
  9595. * @private
  9596. */
  9597. _loadSelectedForceSolver: function () {
  9598. // this overloads the this._calculateNodeForces
  9599. if (this.constants.physics.barnesHut.enabled == true) {
  9600. this._clearMixin(repulsionMixin);
  9601. this._clearMixin(hierarchalRepulsionMixin);
  9602. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9603. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9604. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9605. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9606. this._loadMixin(barnesHutMixin);
  9607. }
  9608. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9609. this._clearMixin(barnesHutMixin);
  9610. this._clearMixin(repulsionMixin);
  9611. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9612. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9613. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9614. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9615. this._loadMixin(hierarchalRepulsionMixin);
  9616. }
  9617. else {
  9618. this._clearMixin(barnesHutMixin);
  9619. this._clearMixin(hierarchalRepulsionMixin);
  9620. this.barnesHutTree = undefined;
  9621. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9622. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9623. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9624. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9625. this._loadMixin(repulsionMixin);
  9626. }
  9627. },
  9628. /**
  9629. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9630. * if there is more than one node. If it is just one node, we dont calculate anything.
  9631. *
  9632. * @private
  9633. */
  9634. _initializeForceCalculation: function () {
  9635. // stop calculation if there is only one node
  9636. if (this.nodeIndices.length == 1) {
  9637. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9638. }
  9639. else {
  9640. // if there are too many nodes on screen, we cluster without repositioning
  9641. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9642. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9643. }
  9644. // we now start the force calculation
  9645. this._calculateForces();
  9646. }
  9647. },
  9648. /**
  9649. * Calculate the external forces acting on the nodes
  9650. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9651. * @private
  9652. */
  9653. _calculateForces: function () {
  9654. // Gravity is required to keep separated groups from floating off
  9655. // the forces are reset to zero in this loop by using _setForce instead
  9656. // of _addForce
  9657. this._calculateGravitationalForces();
  9658. this._calculateNodeForces();
  9659. if (this.constants.smoothCurves == true) {
  9660. this._calculateSpringForcesWithSupport();
  9661. }
  9662. else {
  9663. this._calculateSpringForces();
  9664. }
  9665. },
  9666. /**
  9667. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9668. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9669. * This function joins the datanodes and invisible (called support) nodes into one object.
  9670. * We do this so we do not contaminate this.nodes with the support nodes.
  9671. *
  9672. * @private
  9673. */
  9674. _updateCalculationNodes: function () {
  9675. if (this.constants.smoothCurves == true) {
  9676. this.calculationNodes = {};
  9677. this.calculationNodeIndices = [];
  9678. for (var nodeId in this.nodes) {
  9679. if (this.nodes.hasOwnProperty(nodeId)) {
  9680. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9681. }
  9682. }
  9683. var supportNodes = this.sectors['support']['nodes'];
  9684. for (var supportNodeId in supportNodes) {
  9685. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9686. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9687. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9688. }
  9689. else {
  9690. supportNodes[supportNodeId]._setForce(0, 0);
  9691. }
  9692. }
  9693. }
  9694. for (var idx in this.calculationNodes) {
  9695. if (this.calculationNodes.hasOwnProperty(idx)) {
  9696. this.calculationNodeIndices.push(idx);
  9697. }
  9698. }
  9699. }
  9700. else {
  9701. this.calculationNodes = this.nodes;
  9702. this.calculationNodeIndices = this.nodeIndices;
  9703. }
  9704. },
  9705. /**
  9706. * this function applies the central gravity effect to keep groups from floating off
  9707. *
  9708. * @private
  9709. */
  9710. _calculateGravitationalForces: function () {
  9711. var dx, dy, distance, node, i;
  9712. var nodes = this.calculationNodes;
  9713. var gravity = this.constants.physics.centralGravity;
  9714. var gravityForce = 0;
  9715. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9716. node = nodes[this.calculationNodeIndices[i]];
  9717. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9718. // gravity does not apply when we are in a pocket sector
  9719. if (this._sector() == "default" && gravity != 0) {
  9720. dx = -node.x;
  9721. dy = -node.y;
  9722. distance = Math.sqrt(dx * dx + dy * dy);
  9723. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9724. node.fx = dx * gravityForce;
  9725. node.fy = dy * gravityForce;
  9726. }
  9727. else {
  9728. node.fx = 0;
  9729. node.fy = 0;
  9730. }
  9731. }
  9732. },
  9733. /**
  9734. * this function calculates the effects of the springs in the case of unsmooth curves.
  9735. *
  9736. * @private
  9737. */
  9738. _calculateSpringForces: function () {
  9739. var edgeLength, edge, edgeId;
  9740. var dx, dy, fx, fy, springForce, length;
  9741. var edges = this.edges;
  9742. // forces caused by the edges, modelled as springs
  9743. for (edgeId in edges) {
  9744. if (edges.hasOwnProperty(edgeId)) {
  9745. edge = edges[edgeId];
  9746. if (edge.connected) {
  9747. // only calculate forces if nodes are in the same sector
  9748. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9749. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9750. // this implies that the edges between big clusters are longer
  9751. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9752. dx = (edge.from.x - edge.to.x);
  9753. dy = (edge.from.y - edge.to.y);
  9754. length = Math.sqrt(dx * dx + dy * dy);
  9755. if (length == 0) {
  9756. length = 0.01;
  9757. }
  9758. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9759. fx = dx * springForce;
  9760. fy = dy * springForce;
  9761. edge.from.fx += fx;
  9762. edge.from.fy += fy;
  9763. edge.to.fx -= fx;
  9764. edge.to.fy -= fy;
  9765. }
  9766. }
  9767. }
  9768. }
  9769. },
  9770. /**
  9771. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9772. *
  9773. * @private
  9774. */
  9775. _calculateSpringForcesWithSupport: function () {
  9776. var edgeLength, edge, edgeId, combinedClusterSize;
  9777. var edges = this.edges;
  9778. // forces caused by the edges, modelled as springs
  9779. for (edgeId in edges) {
  9780. if (edges.hasOwnProperty(edgeId)) {
  9781. edge = edges[edgeId];
  9782. if (edge.connected) {
  9783. // only calculate forces if nodes are in the same sector
  9784. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9785. if (edge.via != null) {
  9786. var node1 = edge.to;
  9787. var node2 = edge.via;
  9788. var node3 = edge.from;
  9789. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9790. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9791. // this implies that the edges between big clusters are longer
  9792. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9793. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9794. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9795. }
  9796. }
  9797. }
  9798. }
  9799. }
  9800. },
  9801. /**
  9802. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9803. *
  9804. * @param node1
  9805. * @param node2
  9806. * @param edgeLength
  9807. * @private
  9808. */
  9809. _calculateSpringForce: function (node1, node2, edgeLength) {
  9810. var dx, dy, fx, fy, springForce, length;
  9811. dx = (node1.x - node2.x);
  9812. dy = (node1.y - node2.y);
  9813. length = Math.sqrt(dx * dx + dy * dy);
  9814. if (length == 0) {
  9815. length = 0.01;
  9816. }
  9817. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9818. fx = dx * springForce;
  9819. fy = dy * springForce;
  9820. node1.fx += fx;
  9821. node1.fy += fy;
  9822. node2.fx -= fx;
  9823. node2.fy -= fy;
  9824. },
  9825. /**
  9826. * Load the HTML for the physics config and bind it
  9827. * @private
  9828. */
  9829. _loadPhysicsConfiguration: function () {
  9830. if (this.physicsConfiguration === undefined) {
  9831. this.backupConstants = {};
  9832. util.copyObject(this.constants, this.backupConstants);
  9833. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  9834. this.physicsConfiguration = document.createElement('div');
  9835. this.physicsConfiguration.className = "PhysicsConfiguration";
  9836. this.physicsConfiguration.innerHTML = '' +
  9837. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9838. '<tr>' +
  9839. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9840. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  9841. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9842. '</tr>' +
  9843. '</table>' +
  9844. '<table id="graph_BH_table" style="display:none">' +
  9845. '<tr><td><b>Barnes Hut</b></td></tr>' +
  9846. '<tr>' +
  9847. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="500" 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>' +
  9848. '</tr>' +
  9849. '<tr>' +
  9850. '<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>' +
  9851. '</tr>' +
  9852. '<tr>' +
  9853. '<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>' +
  9854. '</tr>' +
  9855. '<tr>' +
  9856. '<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>' +
  9857. '</tr>' +
  9858. '<tr>' +
  9859. '<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>' +
  9860. '</tr>' +
  9861. '</table>' +
  9862. '<table id="graph_R_table" style="display:none">' +
  9863. '<tr><td><b>Repulsion</b></td></tr>' +
  9864. '<tr>' +
  9865. '<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>' +
  9866. '</tr>' +
  9867. '<tr>' +
  9868. '<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>' +
  9869. '</tr>' +
  9870. '<tr>' +
  9871. '<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>' +
  9872. '</tr>' +
  9873. '<tr>' +
  9874. '<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>' +
  9875. '</tr>' +
  9876. '<tr>' +
  9877. '<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>' +
  9878. '</tr>' +
  9879. '</table>' +
  9880. '<table id="graph_H_table" style="display:none">' +
  9881. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  9882. '<tr>' +
  9883. '<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>' +
  9884. '</tr>' +
  9885. '<tr>' +
  9886. '<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>' +
  9887. '</tr>' +
  9888. '<tr>' +
  9889. '<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>' +
  9890. '</tr>' +
  9891. '<tr>' +
  9892. '<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>' +
  9893. '</tr>' +
  9894. '<tr>' +
  9895. '<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>' +
  9896. '</tr>' +
  9897. '<tr>' +
  9898. '<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>' +
  9899. '</tr>' +
  9900. '<tr>' +
  9901. '<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>' +
  9902. '</tr>' +
  9903. '<tr>' +
  9904. '<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>' +
  9905. '</tr>' +
  9906. '</table>' +
  9907. '<table><tr><td><b>Options:</b></td></tr>' +
  9908. '<tr>' +
  9909. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9910. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  9911. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  9912. '</tr>' +
  9913. '</table>'
  9914. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  9915. this.optionsDiv = document.createElement("div");
  9916. this.optionsDiv.style.fontSize = "14px";
  9917. this.optionsDiv.style.fontFamily = "verdana";
  9918. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  9919. var rangeElement;
  9920. rangeElement = document.getElementById('graph_BH_gc');
  9921. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  9922. rangeElement = document.getElementById('graph_BH_cg');
  9923. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  9924. rangeElement = document.getElementById('graph_BH_sc');
  9925. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  9926. rangeElement = document.getElementById('graph_BH_sl');
  9927. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  9928. rangeElement = document.getElementById('graph_BH_damp');
  9929. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  9930. rangeElement = document.getElementById('graph_R_nd');
  9931. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  9932. rangeElement = document.getElementById('graph_R_cg');
  9933. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  9934. rangeElement = document.getElementById('graph_R_sc');
  9935. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  9936. rangeElement = document.getElementById('graph_R_sl');
  9937. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  9938. rangeElement = document.getElementById('graph_R_damp');
  9939. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  9940. rangeElement = document.getElementById('graph_H_nd');
  9941. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  9942. rangeElement = document.getElementById('graph_H_cg');
  9943. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  9944. rangeElement = document.getElementById('graph_H_sc');
  9945. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  9946. rangeElement = document.getElementById('graph_H_sl');
  9947. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  9948. rangeElement = document.getElementById('graph_H_damp');
  9949. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  9950. rangeElement = document.getElementById('graph_H_direction');
  9951. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  9952. rangeElement = document.getElementById('graph_H_levsep');
  9953. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  9954. rangeElement = document.getElementById('graph_H_nspac');
  9955. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  9956. var radioButton1 = document.getElementById("graph_physicsMethod1");
  9957. var radioButton2 = document.getElementById("graph_physicsMethod2");
  9958. var radioButton3 = document.getElementById("graph_physicsMethod3");
  9959. radioButton2.checked = true;
  9960. if (this.constants.physics.barnesHut.enabled) {
  9961. radioButton1.checked = true;
  9962. }
  9963. if (this.constants.hierarchicalLayout.enabled) {
  9964. radioButton3.checked = true;
  9965. }
  9966. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9967. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  9968. var graph_generateOptions = document.getElementById("graph_generateOptions");
  9969. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  9970. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  9971. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  9972. if (this.constants.smoothCurves == true) {
  9973. graph_toggleSmooth.style.background = "#A4FF56";
  9974. }
  9975. else {
  9976. graph_toggleSmooth.style.background = "#FF8532";
  9977. }
  9978. switchConfigurations.apply(this);
  9979. radioButton1.onchange = switchConfigurations.bind(this);
  9980. radioButton2.onchange = switchConfigurations.bind(this);
  9981. radioButton3.onchange = switchConfigurations.bind(this);
  9982. }
  9983. },
  9984. _overWriteGraphConstants: function (constantsVariableName, value) {
  9985. var nameArray = constantsVariableName.split("_");
  9986. if (nameArray.length == 1) {
  9987. this.constants[nameArray[0]] = value;
  9988. }
  9989. else if (nameArray.length == 2) {
  9990. this.constants[nameArray[0]][nameArray[1]] = value;
  9991. }
  9992. else if (nameArray.length == 3) {
  9993. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  9994. }
  9995. }
  9996. };
  9997. function graphToggleSmoothCurves () {
  9998. this.constants.smoothCurves = !this.constants.smoothCurves;
  9999. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10000. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10001. else {graph_toggleSmooth.style.background = "#FF8532";}
  10002. this._configureSmoothCurves(false);
  10003. };
  10004. function graphRepositionNodes () {
  10005. for (var nodeId in this.calculationNodes) {
  10006. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10007. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10008. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10009. }
  10010. }
  10011. if (this.constants.hierarchicalLayout.enabled == true) {
  10012. this._setupHierarchicalLayout();
  10013. }
  10014. else {
  10015. this.repositionNodes();
  10016. }
  10017. this.moving = true;
  10018. this.start();
  10019. };
  10020. function graphGenerateOptions () {
  10021. var options = "No options are required, default values used.";
  10022. var optionsSpecific = [];
  10023. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10024. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10025. if (radioButton1.checked == true) {
  10026. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10027. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10028. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10029. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10030. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10031. if (optionsSpecific.length != 0) {
  10032. options = "var options = {";
  10033. options += "physics: {barnesHut: {";
  10034. for (var i = 0; i < optionsSpecific.length; i++) {
  10035. options += optionsSpecific[i];
  10036. if (i < optionsSpecific.length - 1) {
  10037. options += ", "
  10038. }
  10039. }
  10040. options += '}}'
  10041. }
  10042. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10043. if (optionsSpecific.length == 0) {options = "var options = {";}
  10044. else {options += ", "}
  10045. options += "smoothCurves: " + this.constants.smoothCurves;
  10046. }
  10047. if (options != "No options are required, default values used.") {
  10048. options += '};'
  10049. }
  10050. }
  10051. else if (radioButton2.checked == true) {
  10052. options = "var options = {";
  10053. options += "physics: {barnesHut: {enabled: false}";
  10054. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10055. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10056. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10057. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10058. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10059. if (optionsSpecific.length != 0) {
  10060. options += ", repulsion: {";
  10061. for (var i = 0; i < optionsSpecific.length; i++) {
  10062. options += optionsSpecific[i];
  10063. if (i < optionsSpecific.length - 1) {
  10064. options += ", "
  10065. }
  10066. }
  10067. options += '}}'
  10068. }
  10069. if (optionsSpecific.length == 0) {options += "}"}
  10070. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10071. options += ", smoothCurves: " + this.constants.smoothCurves;
  10072. }
  10073. options += '};'
  10074. }
  10075. else {
  10076. options = "var options = {";
  10077. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10078. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10079. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10080. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10081. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10082. if (optionsSpecific.length != 0) {
  10083. options += "physics: {hierarchicalRepulsion: {";
  10084. for (var i = 0; i < optionsSpecific.length; i++) {
  10085. options += optionsSpecific[i];
  10086. if (i < optionsSpecific.length - 1) {
  10087. options += ", ";
  10088. }
  10089. }
  10090. options += '}},';
  10091. }
  10092. options += 'hierarchicalLayout: {';
  10093. optionsSpecific = [];
  10094. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10095. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10096. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10097. if (optionsSpecific.length != 0) {
  10098. for (var i = 0; i < optionsSpecific.length; i++) {
  10099. options += optionsSpecific[i];
  10100. if (i < optionsSpecific.length - 1) {
  10101. options += ", "
  10102. }
  10103. }
  10104. options += '}'
  10105. }
  10106. else {
  10107. options += "enabled:true}";
  10108. }
  10109. options += '};'
  10110. }
  10111. this.optionsDiv.innerHTML = options;
  10112. };
  10113. function switchConfigurations () {
  10114. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10115. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10116. var tableId = "graph_" + radioButton + "_table";
  10117. var table = document.getElementById(tableId);
  10118. table.style.display = "block";
  10119. for (var i = 0; i < ids.length; i++) {
  10120. if (ids[i] != tableId) {
  10121. table = document.getElementById(ids[i]);
  10122. table.style.display = "none";
  10123. }
  10124. }
  10125. this._restoreNodes();
  10126. if (radioButton == "R") {
  10127. this.constants.hierarchicalLayout.enabled = false;
  10128. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10129. this.constants.physics.barnesHut.enabled = false;
  10130. }
  10131. else if (radioButton == "H") {
  10132. this.constants.hierarchicalLayout.enabled = true;
  10133. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10134. this.constants.physics.barnesHut.enabled = false;
  10135. this._setupHierarchicalLayout();
  10136. }
  10137. else {
  10138. this.constants.hierarchicalLayout.enabled = false;
  10139. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10140. this.constants.physics.barnesHut.enabled = true;
  10141. }
  10142. this._loadSelectedForceSolver();
  10143. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10144. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10145. else {graph_toggleSmooth.style.background = "#FF8532";}
  10146. this.moving = true;
  10147. this.start();
  10148. }
  10149. function showValueOfRange (id,map,constantsVariableName) {
  10150. var valueId = id + "_value";
  10151. var rangeValue = document.getElementById(id).value;
  10152. if (map instanceof Array) {
  10153. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10154. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10155. }
  10156. else {
  10157. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10158. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10159. }
  10160. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10161. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10162. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10163. this._setupHierarchicalLayout();
  10164. }
  10165. this.moving = true;
  10166. this.start();
  10167. };
  10168. /**
  10169. * Created by Alex on 2/10/14.
  10170. */
  10171. var hierarchalRepulsionMixin = {
  10172. /**
  10173. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10174. * This field is linearly approximated.
  10175. *
  10176. * @private
  10177. */
  10178. _calculateNodeForces: function () {
  10179. var dx, dy, distance, fx, fy, combinedClusterSize,
  10180. repulsingForce, node1, node2, i, j;
  10181. var nodes = this.calculationNodes;
  10182. var nodeIndices = this.calculationNodeIndices;
  10183. // approximation constants
  10184. var b = 5;
  10185. var a_base = 0.5 * -b;
  10186. // repulsing forces between nodes
  10187. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10188. var minimumDistance = nodeDistance;
  10189. // we loop from i over all but the last entree in the array
  10190. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10191. for (i = 0; i < nodeIndices.length - 1; i++) {
  10192. node1 = nodes[nodeIndices[i]];
  10193. for (j = i + 1; j < nodeIndices.length; j++) {
  10194. node2 = nodes[nodeIndices[j]];
  10195. dx = node2.x - node1.x;
  10196. dy = node2.y - node1.y;
  10197. distance = Math.sqrt(dx * dx + dy * dy);
  10198. var a = a_base / minimumDistance;
  10199. if (distance < 2 * minimumDistance) {
  10200. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10201. // normalize force with
  10202. if (distance == 0) {
  10203. distance = 0.01;
  10204. }
  10205. else {
  10206. repulsingForce = repulsingForce / distance;
  10207. }
  10208. fx = dx * repulsingForce;
  10209. fy = dy * repulsingForce;
  10210. node1.fx -= fx;
  10211. node1.fy -= fy;
  10212. node2.fx += fx;
  10213. node2.fy += fy;
  10214. }
  10215. }
  10216. }
  10217. }
  10218. };
  10219. /**
  10220. * Created by Alex on 2/10/14.
  10221. */
  10222. var barnesHutMixin = {
  10223. /**
  10224. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10225. * The Barnes Hut method is used to speed up this N-body simulation.
  10226. *
  10227. * @private
  10228. */
  10229. _calculateNodeForces : function() {
  10230. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10231. var node;
  10232. var nodes = this.calculationNodes;
  10233. var nodeIndices = this.calculationNodeIndices;
  10234. var nodeCount = nodeIndices.length;
  10235. this._formBarnesHutTree(nodes,nodeIndices);
  10236. var barnesHutTree = this.barnesHutTree;
  10237. // place the nodes one by one recursively
  10238. for (var i = 0; i < nodeCount; i++) {
  10239. node = nodes[nodeIndices[i]];
  10240. // starting with root is irrelevant, it never passes the BarnesHut condition
  10241. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10242. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10243. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10244. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10245. }
  10246. }
  10247. },
  10248. /**
  10249. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10250. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10251. *
  10252. * @param parentBranch
  10253. * @param node
  10254. * @private
  10255. */
  10256. _getForceContribution : function(parentBranch,node) {
  10257. // we get no force contribution from an empty region
  10258. if (parentBranch.childrenCount > 0) {
  10259. var dx,dy,distance;
  10260. // get the distance from the center of mass to the node.
  10261. dx = parentBranch.centerOfMass.x - node.x;
  10262. dy = parentBranch.centerOfMass.y - node.y;
  10263. distance = Math.sqrt(dx * dx + dy * dy);
  10264. // BarnesHut condition
  10265. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10266. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10267. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10268. // duplicate code to reduce function calls to speed up program
  10269. if (distance == 0) {
  10270. distance = 0.1*Math.random();
  10271. dx = distance;
  10272. }
  10273. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10274. var fx = dx * gravityForce;
  10275. var fy = dy * gravityForce;
  10276. node.fx += fx;
  10277. node.fy += fy;
  10278. }
  10279. else {
  10280. // Did not pass the condition, go into children if available
  10281. if (parentBranch.childrenCount == 4) {
  10282. this._getForceContribution(parentBranch.children.NW,node);
  10283. this._getForceContribution(parentBranch.children.NE,node);
  10284. this._getForceContribution(parentBranch.children.SW,node);
  10285. this._getForceContribution(parentBranch.children.SE,node);
  10286. }
  10287. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10288. if (parentBranch.children.data.id != node.id) { // if it is not self
  10289. // duplicate code to reduce function calls to speed up program
  10290. if (distance == 0) {
  10291. distance = 0.5*Math.random();
  10292. dx = distance;
  10293. }
  10294. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10295. var fx = dx * gravityForce;
  10296. var fy = dy * gravityForce;
  10297. node.fx += fx;
  10298. node.fy += fy;
  10299. }
  10300. }
  10301. }
  10302. }
  10303. },
  10304. /**
  10305. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10306. *
  10307. * @param nodes
  10308. * @param nodeIndices
  10309. * @private
  10310. */
  10311. _formBarnesHutTree : function(nodes,nodeIndices) {
  10312. var node;
  10313. var nodeCount = nodeIndices.length;
  10314. var minX = Number.MAX_VALUE,
  10315. minY = Number.MAX_VALUE,
  10316. maxX =-Number.MAX_VALUE,
  10317. maxY =-Number.MAX_VALUE;
  10318. // get the range of the nodes
  10319. for (var i = 0; i < nodeCount; i++) {
  10320. var x = nodes[nodeIndices[i]].x;
  10321. var y = nodes[nodeIndices[i]].y;
  10322. if (x < minX) { minX = x; }
  10323. if (x > maxX) { maxX = x; }
  10324. if (y < minY) { minY = y; }
  10325. if (y > maxY) { maxY = y; }
  10326. }
  10327. // make the range a square
  10328. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10329. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10330. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10331. var minimumTreeSize = 1e-5;
  10332. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10333. var halfRootSize = 0.5 * rootSize;
  10334. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10335. // construct the barnesHutTree
  10336. var barnesHutTree = {root:{
  10337. centerOfMass:{x:0,y:0}, // Center of Mass
  10338. mass:0,
  10339. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10340. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10341. size: rootSize,
  10342. calcSize: 1 / rootSize,
  10343. children: {data:null},
  10344. maxWidth: 0,
  10345. level: 0,
  10346. childrenCount: 4
  10347. }};
  10348. this._splitBranch(barnesHutTree.root);
  10349. // place the nodes one by one recursively
  10350. for (i = 0; i < nodeCount; i++) {
  10351. node = nodes[nodeIndices[i]];
  10352. this._placeInTree(barnesHutTree.root,node);
  10353. }
  10354. // make global
  10355. this.barnesHutTree = barnesHutTree
  10356. },
  10357. _updateBranchMass : function(parentBranch, node) {
  10358. var totalMass = parentBranch.mass + node.mass;
  10359. var totalMassInv = 1/totalMass;
  10360. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10361. parentBranch.centerOfMass.x *= totalMassInv;
  10362. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10363. parentBranch.centerOfMass.y *= totalMassInv;
  10364. parentBranch.mass = totalMass;
  10365. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10366. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10367. },
  10368. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10369. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10370. // update the mass of the branch.
  10371. this._updateBranchMass(parentBranch,node);
  10372. }
  10373. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10374. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10375. this._placeInRegion(parentBranch,node,"NW");
  10376. }
  10377. else { // in SW
  10378. this._placeInRegion(parentBranch,node,"SW");
  10379. }
  10380. }
  10381. else { // in NE or SE
  10382. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10383. this._placeInRegion(parentBranch,node,"NE");
  10384. }
  10385. else { // in SE
  10386. this._placeInRegion(parentBranch,node,"SE");
  10387. }
  10388. }
  10389. },
  10390. _placeInRegion : function(parentBranch,node,region) {
  10391. switch (parentBranch.children[region].childrenCount) {
  10392. case 0: // place node here
  10393. parentBranch.children[region].children.data = node;
  10394. parentBranch.children[region].childrenCount = 1;
  10395. this._updateBranchMass(parentBranch.children[region],node);
  10396. break;
  10397. case 1: // convert into children
  10398. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10399. // we move one node a pixel and we do not put it in the tree.
  10400. if (parentBranch.children[region].children.data.x == node.x &&
  10401. parentBranch.children[region].children.data.y == node.y) {
  10402. node.x += Math.random();
  10403. node.y += Math.random();
  10404. }
  10405. else {
  10406. this._splitBranch(parentBranch.children[region]);
  10407. this._placeInTree(parentBranch.children[region],node);
  10408. }
  10409. break;
  10410. case 4: // place in branch
  10411. this._placeInTree(parentBranch.children[region],node);
  10412. break;
  10413. }
  10414. },
  10415. /**
  10416. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10417. * after the split is complete.
  10418. *
  10419. * @param parentBranch
  10420. * @private
  10421. */
  10422. _splitBranch : function(parentBranch) {
  10423. // if the branch is filled with a node, replace the node in the new subset.
  10424. var containedNode = null;
  10425. if (parentBranch.childrenCount == 1) {
  10426. containedNode = parentBranch.children.data;
  10427. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10428. }
  10429. parentBranch.childrenCount = 4;
  10430. parentBranch.children.data = null;
  10431. this._insertRegion(parentBranch,"NW");
  10432. this._insertRegion(parentBranch,"NE");
  10433. this._insertRegion(parentBranch,"SW");
  10434. this._insertRegion(parentBranch,"SE");
  10435. if (containedNode != null) {
  10436. this._placeInTree(parentBranch,containedNode);
  10437. }
  10438. },
  10439. /**
  10440. * This function subdivides the region into four new segments.
  10441. * Specifically, this inserts a single new segment.
  10442. * It fills the children section of the parentBranch
  10443. *
  10444. * @param parentBranch
  10445. * @param region
  10446. * @param parentRange
  10447. * @private
  10448. */
  10449. _insertRegion : function(parentBranch, region) {
  10450. var minX,maxX,minY,maxY;
  10451. var childSize = 0.5 * parentBranch.size;
  10452. switch (region) {
  10453. case "NW":
  10454. minX = parentBranch.range.minX;
  10455. maxX = parentBranch.range.minX + childSize;
  10456. minY = parentBranch.range.minY;
  10457. maxY = parentBranch.range.minY + childSize;
  10458. break;
  10459. case "NE":
  10460. minX = parentBranch.range.minX + childSize;
  10461. maxX = parentBranch.range.maxX;
  10462. minY = parentBranch.range.minY;
  10463. maxY = parentBranch.range.minY + childSize;
  10464. break;
  10465. case "SW":
  10466. minX = parentBranch.range.minX;
  10467. maxX = parentBranch.range.minX + childSize;
  10468. minY = parentBranch.range.minY + childSize;
  10469. maxY = parentBranch.range.maxY;
  10470. break;
  10471. case "SE":
  10472. minX = parentBranch.range.minX + childSize;
  10473. maxX = parentBranch.range.maxX;
  10474. minY = parentBranch.range.minY + childSize;
  10475. maxY = parentBranch.range.maxY;
  10476. break;
  10477. }
  10478. parentBranch.children[region] = {
  10479. centerOfMass:{x:0,y:0},
  10480. mass:0,
  10481. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10482. size: 0.5 * parentBranch.size,
  10483. calcSize: 2 * parentBranch.calcSize,
  10484. children: {data:null},
  10485. maxWidth: 0,
  10486. level: parentBranch.level+1,
  10487. childrenCount: 0
  10488. };
  10489. },
  10490. /**
  10491. * This function is for debugging purposed, it draws the tree.
  10492. *
  10493. * @param ctx
  10494. * @param color
  10495. * @private
  10496. */
  10497. _drawTree : function(ctx,color) {
  10498. if (this.barnesHutTree !== undefined) {
  10499. ctx.lineWidth = 1;
  10500. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10501. }
  10502. },
  10503. /**
  10504. * This function is for debugging purposes. It draws the branches recursively.
  10505. *
  10506. * @param branch
  10507. * @param ctx
  10508. * @param color
  10509. * @private
  10510. */
  10511. _drawBranch : function(branch,ctx,color) {
  10512. if (color === undefined) {
  10513. color = "#FF0000";
  10514. }
  10515. if (branch.childrenCount == 4) {
  10516. this._drawBranch(branch.children.NW,ctx);
  10517. this._drawBranch(branch.children.NE,ctx);
  10518. this._drawBranch(branch.children.SE,ctx);
  10519. this._drawBranch(branch.children.SW,ctx);
  10520. }
  10521. ctx.strokeStyle = color;
  10522. ctx.beginPath();
  10523. ctx.moveTo(branch.range.minX,branch.range.minY);
  10524. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10525. ctx.stroke();
  10526. ctx.beginPath();
  10527. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10528. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10529. ctx.stroke();
  10530. ctx.beginPath();
  10531. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10532. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10533. ctx.stroke();
  10534. ctx.beginPath();
  10535. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10536. ctx.lineTo(branch.range.minX,branch.range.minY);
  10537. ctx.stroke();
  10538. /*
  10539. if (branch.mass > 0) {
  10540. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10541. ctx.stroke();
  10542. }
  10543. */
  10544. }
  10545. };
  10546. /**
  10547. * Created by Alex on 2/10/14.
  10548. */
  10549. var repulsionMixin = {
  10550. /**
  10551. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10552. * This field is linearly approximated.
  10553. *
  10554. * @private
  10555. */
  10556. _calculateNodeForces: function () {
  10557. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10558. repulsingForce, node1, node2, i, j;
  10559. var nodes = this.calculationNodes;
  10560. var nodeIndices = this.calculationNodeIndices;
  10561. // approximation constants
  10562. var a_base = -2 / 3;
  10563. var b = 4 / 3;
  10564. // repulsing forces between nodes
  10565. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10566. var minimumDistance = nodeDistance;
  10567. // we loop from i over all but the last entree in the array
  10568. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10569. for (i = 0; i < nodeIndices.length - 1; i++) {
  10570. node1 = nodes[nodeIndices[i]];
  10571. for (j = i + 1; j < nodeIndices.length; j++) {
  10572. node2 = nodes[nodeIndices[j]];
  10573. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10574. dx = node2.x - node1.x;
  10575. dy = node2.y - node1.y;
  10576. distance = Math.sqrt(dx * dx + dy * dy);
  10577. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10578. var a = a_base / minimumDistance;
  10579. if (distance < 2 * minimumDistance) {
  10580. if (distance < 0.5 * minimumDistance) {
  10581. repulsingForce = 1.0;
  10582. }
  10583. else {
  10584. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10585. }
  10586. // amplify the repulsion for clusters.
  10587. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10588. repulsingForce = repulsingForce / distance;
  10589. fx = dx * repulsingForce;
  10590. fy = dy * repulsingForce;
  10591. node1.fx -= fx;
  10592. node1.fy -= fy;
  10593. node2.fx += fx;
  10594. node2.fy += fy;
  10595. }
  10596. }
  10597. }
  10598. }
  10599. };
  10600. var HierarchicalLayoutMixin = {
  10601. _resetLevels : function() {
  10602. for (var nodeId in this.nodes) {
  10603. if (this.nodes.hasOwnProperty(nodeId)) {
  10604. var node = this.nodes[nodeId];
  10605. if (node.preassignedLevel == false) {
  10606. node.level = -1;
  10607. }
  10608. }
  10609. }
  10610. },
  10611. /**
  10612. * This is the main function to layout the nodes in a hierarchical way.
  10613. * It checks if the node details are supplied correctly
  10614. *
  10615. * @private
  10616. */
  10617. _setupHierarchicalLayout : function() {
  10618. if (this.constants.hierarchicalLayout.enabled == true) {
  10619. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10620. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10621. }
  10622. else {
  10623. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10624. }
  10625. // get the size of the largest hubs and check if the user has defined a level for a node.
  10626. var hubsize = 0;
  10627. var node, nodeId;
  10628. var definedLevel = false;
  10629. var undefinedLevel = false;
  10630. for (nodeId in this.nodes) {
  10631. if (this.nodes.hasOwnProperty(nodeId)) {
  10632. node = this.nodes[nodeId];
  10633. if (node.level != -1) {
  10634. definedLevel = true;
  10635. }
  10636. else {
  10637. undefinedLevel = true;
  10638. }
  10639. if (hubsize < node.edges.length) {
  10640. hubsize = node.edges.length;
  10641. }
  10642. }
  10643. }
  10644. // if the user defined some levels but not all, alert and run without hierarchical layout
  10645. if (undefinedLevel == true && definedLevel == true) {
  10646. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10647. this.zoomExtent(true,this.constants.clustering.enabled);
  10648. if (!this.constants.clustering.enabled) {
  10649. this.start();
  10650. }
  10651. }
  10652. else {
  10653. // setup the system to use hierarchical method.
  10654. this._changeConstants();
  10655. // define levels if undefined by the users. Based on hubsize
  10656. if (undefinedLevel == true) {
  10657. this._determineLevels(hubsize);
  10658. }
  10659. // check the distribution of the nodes per level.
  10660. var distribution = this._getDistribution();
  10661. // place the nodes on the canvas. This also stablilizes the system.
  10662. this._placeNodesByHierarchy(distribution);
  10663. // start the simulation.
  10664. this.start();
  10665. }
  10666. }
  10667. },
  10668. /**
  10669. * This function places the nodes on the canvas based on the hierarchial distribution.
  10670. *
  10671. * @param {Object} distribution | obtained by the function this._getDistribution()
  10672. * @private
  10673. */
  10674. _placeNodesByHierarchy : function(distribution) {
  10675. var nodeId, node;
  10676. // start placing all the level 0 nodes first. Then recursively position their branches.
  10677. for (nodeId in distribution[0].nodes) {
  10678. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10679. node = distribution[0].nodes[nodeId];
  10680. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10681. if (node.xFixed) {
  10682. node.x = distribution[0].minPos;
  10683. node.xFixed = false;
  10684. distribution[0].minPos += distribution[0].nodeSpacing;
  10685. }
  10686. }
  10687. else {
  10688. if (node.yFixed) {
  10689. node.y = distribution[0].minPos;
  10690. node.yFixed = false;
  10691. distribution[0].minPos += distribution[0].nodeSpacing;
  10692. }
  10693. }
  10694. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10695. }
  10696. }
  10697. // stabilize the system after positioning. This function calls zoomExtent.
  10698. this._stabilize();
  10699. },
  10700. /**
  10701. * This function get the distribution of levels based on hubsize
  10702. *
  10703. * @returns {Object}
  10704. * @private
  10705. */
  10706. _getDistribution : function() {
  10707. var distribution = {};
  10708. var nodeId, node;
  10709. // 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.
  10710. // the fix of X is removed after the x value has been set.
  10711. for (nodeId in this.nodes) {
  10712. if (this.nodes.hasOwnProperty(nodeId)) {
  10713. node = this.nodes[nodeId];
  10714. node.xFixed = true;
  10715. node.yFixed = true;
  10716. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10717. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10718. }
  10719. else {
  10720. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10721. }
  10722. if (!distribution.hasOwnProperty(node.level)) {
  10723. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10724. }
  10725. distribution[node.level].amount += 1;
  10726. distribution[node.level].nodes[node.id] = node;
  10727. }
  10728. }
  10729. // determine the largest amount of nodes of all levels
  10730. var maxCount = 0;
  10731. for (var level in distribution) {
  10732. if (distribution.hasOwnProperty(level)) {
  10733. if (maxCount < distribution[level].amount) {
  10734. maxCount = distribution[level].amount;
  10735. }
  10736. }
  10737. }
  10738. // set the initial position and spacing of each nodes accordingly
  10739. for (var level in distribution) {
  10740. if (distribution.hasOwnProperty(level)) {
  10741. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10742. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10743. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10744. }
  10745. }
  10746. return distribution;
  10747. },
  10748. /**
  10749. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10750. *
  10751. * @param hubsize
  10752. * @private
  10753. */
  10754. _determineLevels : function(hubsize) {
  10755. var nodeId, node;
  10756. // determine hubs
  10757. for (nodeId in this.nodes) {
  10758. if (this.nodes.hasOwnProperty(nodeId)) {
  10759. node = this.nodes[nodeId];
  10760. if (node.edges.length == hubsize) {
  10761. node.level = 0;
  10762. }
  10763. }
  10764. }
  10765. // branch from hubs
  10766. for (nodeId in this.nodes) {
  10767. if (this.nodes.hasOwnProperty(nodeId)) {
  10768. node = this.nodes[nodeId];
  10769. if (node.level == 0) {
  10770. this._setLevel(1,node.edges,node.id);
  10771. }
  10772. }
  10773. }
  10774. },
  10775. /**
  10776. * Since hierarchical layout does not support:
  10777. * - smooth curves (based on the physics),
  10778. * - clustering (based on dynamic node counts)
  10779. *
  10780. * We disable both features so there will be no problems.
  10781. *
  10782. * @private
  10783. */
  10784. _changeConstants : function() {
  10785. this.constants.clustering.enabled = false;
  10786. this.constants.physics.barnesHut.enabled = false;
  10787. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10788. this._loadSelectedForceSolver();
  10789. this.constants.smoothCurves = false;
  10790. this._configureSmoothCurves();
  10791. },
  10792. /**
  10793. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10794. * on a X position that ensures there will be no overlap.
  10795. *
  10796. * @param edges
  10797. * @param parentId
  10798. * @param distribution
  10799. * @param parentLevel
  10800. * @private
  10801. */
  10802. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10803. for (var i = 0; i < edges.length; i++) {
  10804. var childNode = null;
  10805. if (edges[i].toId == parentId) {
  10806. childNode = edges[i].from;
  10807. }
  10808. else {
  10809. childNode = edges[i].to;
  10810. }
  10811. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10812. var nodeMoved = false;
  10813. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10814. if (childNode.xFixed && childNode.level > parentLevel) {
  10815. childNode.xFixed = false;
  10816. childNode.x = distribution[childNode.level].minPos;
  10817. nodeMoved = true;
  10818. }
  10819. }
  10820. else {
  10821. if (childNode.yFixed && childNode.level > parentLevel) {
  10822. childNode.yFixed = false;
  10823. childNode.y = distribution[childNode.level].minPos;
  10824. nodeMoved = true;
  10825. }
  10826. }
  10827. if (nodeMoved == true) {
  10828. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10829. if (childNode.edges.length > 1) {
  10830. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10831. }
  10832. }
  10833. }
  10834. },
  10835. /**
  10836. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10837. *
  10838. * @param level
  10839. * @param edges
  10840. * @param parentId
  10841. * @private
  10842. */
  10843. _setLevel : function(level, edges, parentId) {
  10844. for (var i = 0; i < edges.length; i++) {
  10845. var childNode = null;
  10846. if (edges[i].toId == parentId) {
  10847. childNode = edges[i].from;
  10848. }
  10849. else {
  10850. childNode = edges[i].to;
  10851. }
  10852. if (childNode.level == -1 || childNode.level > level) {
  10853. childNode.level = level;
  10854. if (edges.length > 1) {
  10855. this._setLevel(level+1, childNode.edges, childNode.id);
  10856. }
  10857. }
  10858. }
  10859. },
  10860. /**
  10861. * Unfix nodes
  10862. *
  10863. * @private
  10864. */
  10865. _restoreNodes : function() {
  10866. for (nodeId in this.nodes) {
  10867. if (this.nodes.hasOwnProperty(nodeId)) {
  10868. this.nodes[nodeId].xFixed = false;
  10869. this.nodes[nodeId].yFixed = false;
  10870. }
  10871. }
  10872. }
  10873. };
  10874. /**
  10875. * Created by Alex on 2/4/14.
  10876. */
  10877. var manipulationMixin = {
  10878. /**
  10879. * clears the toolbar div element of children
  10880. *
  10881. * @private
  10882. */
  10883. _clearManipulatorBar : function() {
  10884. while (this.manipulationDiv.hasChildNodes()) {
  10885. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10886. }
  10887. },
  10888. /**
  10889. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  10890. * these functions to their original functionality, we saved them in this.cachedFunctions.
  10891. * This function restores these functions to their original function.
  10892. *
  10893. * @private
  10894. */
  10895. _restoreOverloadedFunctions : function() {
  10896. for (var functionName in this.cachedFunctions) {
  10897. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  10898. this[functionName] = this.cachedFunctions[functionName];
  10899. }
  10900. }
  10901. },
  10902. /**
  10903. * Enable or disable edit-mode.
  10904. *
  10905. * @private
  10906. */
  10907. _toggleEditMode : function() {
  10908. this.editMode = !this.editMode;
  10909. var toolbar = document.getElementById("graph-manipulationDiv");
  10910. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10911. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  10912. if (this.editMode == true) {
  10913. toolbar.style.display="block";
  10914. closeDiv.style.display="block";
  10915. editModeDiv.style.display="none";
  10916. closeDiv.onclick = this._toggleEditMode.bind(this);
  10917. }
  10918. else {
  10919. toolbar.style.display="none";
  10920. closeDiv.style.display="none";
  10921. editModeDiv.style.display="block";
  10922. closeDiv.onclick = null;
  10923. }
  10924. this._createManipulatorBar()
  10925. },
  10926. /**
  10927. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  10928. *
  10929. * @private
  10930. */
  10931. _createManipulatorBar : function() {
  10932. // remove bound functions
  10933. if (this.boundFunction) {
  10934. this.off('select', this.boundFunction);
  10935. }
  10936. // restore overloaded functions
  10937. this._restoreOverloadedFunctions();
  10938. // resume calculation
  10939. this.freezeSimulation = false;
  10940. // reset global variables
  10941. this.blockConnectingEdgeSelection = false;
  10942. this.forceAppendSelection = false;
  10943. if (this.editMode == true) {
  10944. while (this.manipulationDiv.hasChildNodes()) {
  10945. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10946. }
  10947. // add the icons to the manipulator div
  10948. this.manipulationDiv.innerHTML = "" +
  10949. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  10950. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  10951. "<div class='graph-seperatorLine'></div>" +
  10952. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  10953. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  10954. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10955. this.manipulationDiv.innerHTML += "" +
  10956. "<div class='graph-seperatorLine'></div>" +
  10957. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  10958. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  10959. }
  10960. if (this._selectionIsEmpty() == false) {
  10961. this.manipulationDiv.innerHTML += "" +
  10962. "<div class='graph-seperatorLine'></div>" +
  10963. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  10964. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  10965. }
  10966. // bind the icons
  10967. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  10968. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  10969. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  10970. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  10971. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10972. var editButton = document.getElementById("graph-manipulate-editNode");
  10973. editButton.onclick = this._editNode.bind(this);
  10974. }
  10975. if (this._selectionIsEmpty() == false) {
  10976. var deleteButton = document.getElementById("graph-manipulate-delete");
  10977. deleteButton.onclick = this._deleteSelected.bind(this);
  10978. }
  10979. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10980. closeDiv.onclick = this._toggleEditMode.bind(this);
  10981. this.boundFunction = this._createManipulatorBar.bind(this);
  10982. this.on('select', this.boundFunction);
  10983. }
  10984. else {
  10985. this.editModeDiv.innerHTML = "" +
  10986. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  10987. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  10988. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  10989. editModeButton.onclick = this._toggleEditMode.bind(this);
  10990. }
  10991. },
  10992. /**
  10993. * Create the toolbar for adding Nodes
  10994. *
  10995. * @private
  10996. */
  10997. _createAddNodeToolbar : function() {
  10998. // clear the toolbar
  10999. this._clearManipulatorBar();
  11000. if (this.boundFunction) {
  11001. this.off('select', this.boundFunction);
  11002. }
  11003. // create the toolbar contents
  11004. this.manipulationDiv.innerHTML = "" +
  11005. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11006. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11007. "<div class='graph-seperatorLine'></div>" +
  11008. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11009. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11010. // bind the icon
  11011. var backButton = document.getElementById("graph-manipulate-back");
  11012. backButton.onclick = this._createManipulatorBar.bind(this);
  11013. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11014. this.boundFunction = this._addNode.bind(this);
  11015. this.on('select', this.boundFunction);
  11016. },
  11017. /**
  11018. * create the toolbar to connect nodes
  11019. *
  11020. * @private
  11021. */
  11022. _createAddEdgeToolbar : function() {
  11023. // clear the toolbar
  11024. this._clearManipulatorBar();
  11025. this._unselectAll(true);
  11026. this.freezeSimulation = true;
  11027. if (this.boundFunction) {
  11028. this.off('select', this.boundFunction);
  11029. }
  11030. this._unselectAll();
  11031. this.forceAppendSelection = false;
  11032. this.blockConnectingEdgeSelection = true;
  11033. this.manipulationDiv.innerHTML = "" +
  11034. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11035. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11036. "<div class='graph-seperatorLine'></div>" +
  11037. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11038. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11039. // bind the icon
  11040. var backButton = document.getElementById("graph-manipulate-back");
  11041. backButton.onclick = this._createManipulatorBar.bind(this);
  11042. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11043. this.boundFunction = this._handleConnect.bind(this);
  11044. this.on('select', this.boundFunction);
  11045. // temporarily overload functions
  11046. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11047. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11048. this._handleTouch = this._handleConnect;
  11049. this._handleOnRelease = this._finishConnect;
  11050. // redraw to show the unselect
  11051. this._redraw();
  11052. },
  11053. /**
  11054. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11055. * to walk the user through the process.
  11056. *
  11057. * @private
  11058. */
  11059. _handleConnect : function(pointer) {
  11060. if (this._getSelectedNodeCount() == 0) {
  11061. var node = this._getNodeAt(pointer);
  11062. if (node != null) {
  11063. if (node.clusterSize > 1) {
  11064. alert("Cannot create edges to a cluster.")
  11065. }
  11066. else {
  11067. this._selectObject(node,false);
  11068. // create a node the temporary line can look at
  11069. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11070. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11071. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11072. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11073. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11074. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11075. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11076. // create a temporary edge
  11077. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11078. this.edges['connectionEdge'].from = node;
  11079. this.edges['connectionEdge'].connected = true;
  11080. this.edges['connectionEdge'].smooth = true;
  11081. this.edges['connectionEdge'].selected = true;
  11082. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11083. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11084. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11085. this._handleOnDrag = function(event) {
  11086. var pointer = this._getPointer(event.gesture.center);
  11087. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11088. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11089. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11090. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11091. };
  11092. this.moving = true;
  11093. this.start();
  11094. }
  11095. }
  11096. }
  11097. },
  11098. _finishConnect : function(pointer) {
  11099. if (this._getSelectedNodeCount() == 1) {
  11100. // restore the drag function
  11101. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11102. delete this.cachedFunctions["_handleOnDrag"];
  11103. // remember the edge id
  11104. var connectFromId = this.edges['connectionEdge'].fromId;
  11105. // remove the temporary nodes and edge
  11106. delete this.edges['connectionEdge'];
  11107. delete this.sectors['support']['nodes']['targetNode'];
  11108. delete this.sectors['support']['nodes']['targetViaNode'];
  11109. var node = this._getNodeAt(pointer);
  11110. if (node != null) {
  11111. if (node.clusterSize > 1) {
  11112. alert("Cannot create edges to a cluster.")
  11113. }
  11114. else {
  11115. this._createEdge(connectFromId,node.id);
  11116. this._createManipulatorBar();
  11117. }
  11118. }
  11119. this._unselectAll();
  11120. }
  11121. },
  11122. /**
  11123. * Adds a node on the specified location
  11124. *
  11125. * @param {Object} pointer
  11126. */
  11127. _addNode : function() {
  11128. if (this._selectionIsEmpty() && this.editMode == true) {
  11129. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11130. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11131. if (this.triggerFunctions.add) {
  11132. if (this.triggerFunctions.add.length == 2) {
  11133. var me = this;
  11134. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11135. me.nodesData.add(finalizedData);
  11136. me._createManipulatorBar();
  11137. me.moving = true;
  11138. me.start();
  11139. });
  11140. }
  11141. else {
  11142. alert(this.constants.labels['addError']);
  11143. this._createManipulatorBar();
  11144. this.moving = true;
  11145. this.start();
  11146. }
  11147. }
  11148. else {
  11149. this.nodesData.add(defaultData);
  11150. this._createManipulatorBar();
  11151. this.moving = true;
  11152. this.start();
  11153. }
  11154. }
  11155. },
  11156. /**
  11157. * connect two nodes with a new edge.
  11158. *
  11159. * @private
  11160. */
  11161. _createEdge : function(sourceNodeId,targetNodeId) {
  11162. if (this.editMode == true) {
  11163. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11164. if (this.triggerFunctions.connect) {
  11165. if (this.triggerFunctions.connect.length == 2) {
  11166. var me = this;
  11167. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11168. me.edgesData.add(finalizedData);
  11169. me.moving = true;
  11170. me.start();
  11171. });
  11172. }
  11173. else {
  11174. alert(this.constants.labels["linkError"]);
  11175. this.moving = true;
  11176. this.start();
  11177. }
  11178. }
  11179. else {
  11180. this.edgesData.add(defaultData);
  11181. this.moving = true;
  11182. this.start();
  11183. }
  11184. }
  11185. },
  11186. /**
  11187. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11188. *
  11189. * @private
  11190. */
  11191. _editNode : function() {
  11192. if (this.triggerFunctions.edit && this.editMode == true) {
  11193. var node = this._getSelectedNode();
  11194. var data = {id:node.id,
  11195. label: node.label,
  11196. group: node.group,
  11197. shape: node.shape,
  11198. color: {
  11199. background:node.color.background,
  11200. border:node.color.border,
  11201. highlight: {
  11202. background:node.color.highlight.background,
  11203. border:node.color.highlight.border
  11204. }
  11205. }};
  11206. if (this.triggerFunctions.edit.length == 2) {
  11207. var me = this;
  11208. this.triggerFunctions.edit(data, function (finalizedData) {
  11209. me.nodesData.update(finalizedData);
  11210. me._createManipulatorBar();
  11211. me.moving = true;
  11212. me.start();
  11213. });
  11214. }
  11215. else {
  11216. alert(this.constants.labels["editError"]);
  11217. }
  11218. }
  11219. else {
  11220. alert(this.constants.labels["editBoundError"]);
  11221. }
  11222. },
  11223. /**
  11224. * delete everything in the selection
  11225. *
  11226. * @private
  11227. */
  11228. _deleteSelected : function() {
  11229. if (!this._selectionIsEmpty() && this.editMode == true) {
  11230. if (!this._clusterInSelection()) {
  11231. var selectedNodes = this.getSelectedNodes();
  11232. var selectedEdges = this.getSelectedEdges();
  11233. if (this.triggerFunctions.del) {
  11234. var me = this;
  11235. var data = {nodes: selectedNodes, edges: selectedEdges};
  11236. if (this.triggerFunctions.del.length = 2) {
  11237. this.triggerFunctions.del(data, function (finalizedData) {
  11238. me.edgesData.remove(finalizedData.edges);
  11239. me.nodesData.remove(finalizedData.nodes);
  11240. me._unselectAll();
  11241. me.moving = true;
  11242. me.start();
  11243. });
  11244. }
  11245. else {
  11246. alert(this.constants.labels["deleteError"])
  11247. }
  11248. }
  11249. else {
  11250. this.edgesData.remove(selectedEdges);
  11251. this.nodesData.remove(selectedNodes);
  11252. this._unselectAll();
  11253. this.moving = true;
  11254. this.start();
  11255. }
  11256. }
  11257. else {
  11258. alert(this.constants.labels["deleteClusterError"]);
  11259. }
  11260. }
  11261. }
  11262. };
  11263. /**
  11264. * Creation of the SectorMixin var.
  11265. *
  11266. * This contains all the functions the Graph object can use to employ the sector system.
  11267. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11268. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11269. *
  11270. * Alex de Mulder
  11271. * 21-01-2013
  11272. */
  11273. var SectorMixin = {
  11274. /**
  11275. * This function is only called by the setData function of the Graph object.
  11276. * This loads the global references into the active sector. This initializes the sector.
  11277. *
  11278. * @private
  11279. */
  11280. _putDataInSector : function() {
  11281. this.sectors["active"][this._sector()].nodes = this.nodes;
  11282. this.sectors["active"][this._sector()].edges = this.edges;
  11283. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11284. },
  11285. /**
  11286. * /**
  11287. * This function sets the global references to nodes, edges and nodeIndices back to
  11288. * those of the supplied (active) sector. If a type is defined, do the specific type
  11289. *
  11290. * @param {String} sectorId
  11291. * @param {String} [sectorType] | "active" or "frozen"
  11292. * @private
  11293. */
  11294. _switchToSector : function(sectorId, sectorType) {
  11295. if (sectorType === undefined || sectorType == "active") {
  11296. this._switchToActiveSector(sectorId);
  11297. }
  11298. else {
  11299. this._switchToFrozenSector(sectorId);
  11300. }
  11301. },
  11302. /**
  11303. * This function sets the global references to nodes, edges and nodeIndices back to
  11304. * those of the supplied active sector.
  11305. *
  11306. * @param sectorId
  11307. * @private
  11308. */
  11309. _switchToActiveSector : function(sectorId) {
  11310. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11311. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11312. this.edges = this.sectors["active"][sectorId]["edges"];
  11313. },
  11314. /**
  11315. * This function sets the global references to nodes, edges and nodeIndices back to
  11316. * those of the supplied active sector.
  11317. *
  11318. * @param sectorId
  11319. * @private
  11320. */
  11321. _switchToSupportSector : function() {
  11322. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11323. this.nodes = this.sectors["support"]["nodes"];
  11324. this.edges = this.sectors["support"]["edges"];
  11325. },
  11326. /**
  11327. * This function sets the global references to nodes, edges and nodeIndices back to
  11328. * those of the supplied frozen sector.
  11329. *
  11330. * @param sectorId
  11331. * @private
  11332. */
  11333. _switchToFrozenSector : function(sectorId) {
  11334. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11335. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11336. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11337. },
  11338. /**
  11339. * This function sets the global references to nodes, edges and nodeIndices back to
  11340. * those of the currently active sector.
  11341. *
  11342. * @private
  11343. */
  11344. _loadLatestSector : function() {
  11345. this._switchToSector(this._sector());
  11346. },
  11347. /**
  11348. * This function returns the currently active sector Id
  11349. *
  11350. * @returns {String}
  11351. * @private
  11352. */
  11353. _sector : function() {
  11354. return this.activeSector[this.activeSector.length-1];
  11355. },
  11356. /**
  11357. * This function returns the previously active sector Id
  11358. *
  11359. * @returns {String}
  11360. * @private
  11361. */
  11362. _previousSector : function() {
  11363. if (this.activeSector.length > 1) {
  11364. return this.activeSector[this.activeSector.length-2];
  11365. }
  11366. else {
  11367. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11368. }
  11369. },
  11370. /**
  11371. * We add the active sector at the end of the this.activeSector array
  11372. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11373. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11374. *
  11375. * @param newId
  11376. * @private
  11377. */
  11378. _setActiveSector : function(newId) {
  11379. this.activeSector.push(newId);
  11380. },
  11381. /**
  11382. * We remove the currently active sector id from the active sector stack. This happens when
  11383. * we reactivate the previously active sector
  11384. *
  11385. * @private
  11386. */
  11387. _forgetLastSector : function() {
  11388. this.activeSector.pop();
  11389. },
  11390. /**
  11391. * This function creates a new active sector with the supplied newId. This newId
  11392. * is the expanding node id.
  11393. *
  11394. * @param {String} newId | Id of the new active sector
  11395. * @private
  11396. */
  11397. _createNewSector : function(newId) {
  11398. // create the new sector
  11399. this.sectors["active"][newId] = {"nodes":{},
  11400. "edges":{},
  11401. "nodeIndices":[],
  11402. "formationScale": this.scale,
  11403. "drawingNode": undefined};
  11404. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11405. this.sectors["active"][newId]['drawingNode'] = new Node(
  11406. {id:newId,
  11407. color: {
  11408. background: "#eaefef",
  11409. border: "495c5e"
  11410. }
  11411. },{},{},this.constants);
  11412. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11413. },
  11414. /**
  11415. * This function removes the currently active sector. This is called when we create a new
  11416. * active sector.
  11417. *
  11418. * @param {String} sectorId | Id of the active sector that will be removed
  11419. * @private
  11420. */
  11421. _deleteActiveSector : function(sectorId) {
  11422. delete this.sectors["active"][sectorId];
  11423. },
  11424. /**
  11425. * This function removes the currently active sector. This is called when we reactivate
  11426. * the previously active sector.
  11427. *
  11428. * @param {String} sectorId | Id of the active sector that will be removed
  11429. * @private
  11430. */
  11431. _deleteFrozenSector : function(sectorId) {
  11432. delete this.sectors["frozen"][sectorId];
  11433. },
  11434. /**
  11435. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11436. * We copy the references, then delete the active entree.
  11437. *
  11438. * @param sectorId
  11439. * @private
  11440. */
  11441. _freezeSector : function(sectorId) {
  11442. // we move the set references from the active to the frozen stack.
  11443. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11444. // we have moved the sector data into the frozen set, we now remove it from the active set
  11445. this._deleteActiveSector(sectorId);
  11446. },
  11447. /**
  11448. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11449. * object to the "active" object.
  11450. *
  11451. * @param sectorId
  11452. * @private
  11453. */
  11454. _activateSector : function(sectorId) {
  11455. // we move the set references from the frozen to the active stack.
  11456. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11457. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11458. this._deleteFrozenSector(sectorId);
  11459. },
  11460. /**
  11461. * This function merges the data from the currently active sector with a frozen sector. This is used
  11462. * in the process of reverting back to the previously active sector.
  11463. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11464. * upon the creation of a new active sector.
  11465. *
  11466. * @param sectorId
  11467. * @private
  11468. */
  11469. _mergeThisWithFrozen : function(sectorId) {
  11470. // copy all nodes
  11471. for (var nodeId in this.nodes) {
  11472. if (this.nodes.hasOwnProperty(nodeId)) {
  11473. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11474. }
  11475. }
  11476. // copy all edges (if not fully clustered, else there are no edges)
  11477. for (var edgeId in this.edges) {
  11478. if (this.edges.hasOwnProperty(edgeId)) {
  11479. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11480. }
  11481. }
  11482. // merge the nodeIndices
  11483. for (var i = 0; i < this.nodeIndices.length; i++) {
  11484. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11485. }
  11486. },
  11487. /**
  11488. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11489. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11490. *
  11491. * @private
  11492. */
  11493. _collapseThisToSingleCluster : function() {
  11494. this.clusterToFit(1,false);
  11495. },
  11496. /**
  11497. * We create a new active sector from the node that we want to open.
  11498. *
  11499. * @param node
  11500. * @private
  11501. */
  11502. _addSector : function(node) {
  11503. // this is the currently active sector
  11504. var sector = this._sector();
  11505. // // this should allow me to select nodes from a frozen set.
  11506. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11507. // console.log("the node is part of the active sector");
  11508. // }
  11509. // else {
  11510. // console.log("I dont know what the fuck happened!!");
  11511. // }
  11512. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11513. delete this.nodes[node.id];
  11514. var unqiueIdentifier = util.randomUUID();
  11515. // we fully freeze the currently active sector
  11516. this._freezeSector(sector);
  11517. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11518. this._createNewSector(unqiueIdentifier);
  11519. // we add the active sector to the sectors array to be able to revert these steps later on
  11520. this._setActiveSector(unqiueIdentifier);
  11521. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11522. this._switchToSector(this._sector());
  11523. // finally we add the node we removed from our previous active sector to the new active sector
  11524. this.nodes[node.id] = node;
  11525. },
  11526. /**
  11527. * We close the sector that is currently open and revert back to the one before.
  11528. * If the active sector is the "default" sector, nothing happens.
  11529. *
  11530. * @private
  11531. */
  11532. _collapseSector : function() {
  11533. // the currently active sector
  11534. var sector = this._sector();
  11535. // we cannot collapse the default sector
  11536. if (sector != "default") {
  11537. if ((this.nodeIndices.length == 1) ||
  11538. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11539. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11540. var previousSector = this._previousSector();
  11541. // we collapse the sector back to a single cluster
  11542. this._collapseThisToSingleCluster();
  11543. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11544. // This previous sector is the one we will reactivate
  11545. this._mergeThisWithFrozen(previousSector);
  11546. // the previously active (frozen) sector now has all the data from the currently active sector.
  11547. // we can now delete the active sector.
  11548. this._deleteActiveSector(sector);
  11549. // we activate the previously active (and currently frozen) sector.
  11550. this._activateSector(previousSector);
  11551. // we load the references from the newly active sector into the global references
  11552. this._switchToSector(previousSector);
  11553. // we forget the previously active sector because we reverted to the one before
  11554. this._forgetLastSector();
  11555. // finally, we update the node index list.
  11556. this._updateNodeIndexList();
  11557. // we refresh the list with calulation nodes and calculation node indices.
  11558. this._updateCalculationNodes();
  11559. }
  11560. }
  11561. },
  11562. /**
  11563. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11564. *
  11565. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11566. * | we dont pass the function itself because then the "this" is the window object
  11567. * | instead of the Graph object
  11568. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11569. * @private
  11570. */
  11571. _doInAllActiveSectors : function(runFunction,argument) {
  11572. if (argument === undefined) {
  11573. for (var sector in this.sectors["active"]) {
  11574. if (this.sectors["active"].hasOwnProperty(sector)) {
  11575. // switch the global references to those of this sector
  11576. this._switchToActiveSector(sector);
  11577. this[runFunction]();
  11578. }
  11579. }
  11580. }
  11581. else {
  11582. for (var sector in this.sectors["active"]) {
  11583. if (this.sectors["active"].hasOwnProperty(sector)) {
  11584. // switch the global references to those of this sector
  11585. this._switchToActiveSector(sector);
  11586. var args = Array.prototype.splice.call(arguments, 1);
  11587. if (args.length > 1) {
  11588. this[runFunction](args[0],args[1]);
  11589. }
  11590. else {
  11591. this[runFunction](argument);
  11592. }
  11593. }
  11594. }
  11595. }
  11596. // we revert the global references back to our active sector
  11597. this._loadLatestSector();
  11598. },
  11599. /**
  11600. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11601. *
  11602. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11603. * | we dont pass the function itself because then the "this" is the window object
  11604. * | instead of the Graph object
  11605. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11606. * @private
  11607. */
  11608. _doInSupportSector : function(runFunction,argument) {
  11609. if (argument === undefined) {
  11610. this._switchToSupportSector();
  11611. this[runFunction]();
  11612. }
  11613. else {
  11614. this._switchToSupportSector();
  11615. var args = Array.prototype.splice.call(arguments, 1);
  11616. if (args.length > 1) {
  11617. this[runFunction](args[0],args[1]);
  11618. }
  11619. else {
  11620. this[runFunction](argument);
  11621. }
  11622. }
  11623. // we revert the global references back to our active sector
  11624. this._loadLatestSector();
  11625. },
  11626. /**
  11627. * This runs a function in all frozen sectors. This is used in the _redraw().
  11628. *
  11629. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11630. * | we don't pass the function itself because then the "this" is the window object
  11631. * | instead of the Graph object
  11632. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11633. * @private
  11634. */
  11635. _doInAllFrozenSectors : function(runFunction,argument) {
  11636. if (argument === undefined) {
  11637. for (var sector in this.sectors["frozen"]) {
  11638. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11639. // switch the global references to those of this sector
  11640. this._switchToFrozenSector(sector);
  11641. this[runFunction]();
  11642. }
  11643. }
  11644. }
  11645. else {
  11646. for (var sector in this.sectors["frozen"]) {
  11647. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11648. // switch the global references to those of this sector
  11649. this._switchToFrozenSector(sector);
  11650. var args = Array.prototype.splice.call(arguments, 1);
  11651. if (args.length > 1) {
  11652. this[runFunction](args[0],args[1]);
  11653. }
  11654. else {
  11655. this[runFunction](argument);
  11656. }
  11657. }
  11658. }
  11659. }
  11660. this._loadLatestSector();
  11661. },
  11662. /**
  11663. * This runs a function in all sectors. This is used in the _redraw().
  11664. *
  11665. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11666. * | we don't pass the function itself because then the "this" is the window object
  11667. * | instead of the Graph object
  11668. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11669. * @private
  11670. */
  11671. _doInAllSectors : function(runFunction,argument) {
  11672. var args = Array.prototype.splice.call(arguments, 1);
  11673. if (argument === undefined) {
  11674. this._doInAllActiveSectors(runFunction);
  11675. this._doInAllFrozenSectors(runFunction);
  11676. }
  11677. else {
  11678. if (args.length > 1) {
  11679. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11680. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11681. }
  11682. else {
  11683. this._doInAllActiveSectors(runFunction,argument);
  11684. this._doInAllFrozenSectors(runFunction,argument);
  11685. }
  11686. }
  11687. },
  11688. /**
  11689. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11690. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11691. *
  11692. * @private
  11693. */
  11694. _clearNodeIndexList : function() {
  11695. var sector = this._sector();
  11696. this.sectors["active"][sector]["nodeIndices"] = [];
  11697. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11698. },
  11699. /**
  11700. * Draw the encompassing sector node
  11701. *
  11702. * @param ctx
  11703. * @param sectorType
  11704. * @private
  11705. */
  11706. _drawSectorNodes : function(ctx,sectorType) {
  11707. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11708. for (var sector in this.sectors[sectorType]) {
  11709. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11710. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11711. this._switchToSector(sector,sectorType);
  11712. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11713. for (var nodeId in this.nodes) {
  11714. if (this.nodes.hasOwnProperty(nodeId)) {
  11715. node = this.nodes[nodeId];
  11716. node.resize(ctx);
  11717. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11718. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11719. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11720. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11721. }
  11722. }
  11723. node = this.sectors[sectorType][sector]["drawingNode"];
  11724. node.x = 0.5 * (maxX + minX);
  11725. node.y = 0.5 * (maxY + minY);
  11726. node.width = 2 * (node.x - minX);
  11727. node.height = 2 * (node.y - minY);
  11728. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11729. node.setScale(this.scale);
  11730. node._drawCircle(ctx);
  11731. }
  11732. }
  11733. }
  11734. },
  11735. _drawAllSectorNodes : function(ctx) {
  11736. this._drawSectorNodes(ctx,"frozen");
  11737. this._drawSectorNodes(ctx,"active");
  11738. this._loadLatestSector();
  11739. }
  11740. };
  11741. /**
  11742. * Creation of the ClusterMixin var.
  11743. *
  11744. * This contains all the functions the Graph object can use to employ clustering
  11745. *
  11746. * Alex de Mulder
  11747. * 21-01-2013
  11748. */
  11749. var ClusterMixin = {
  11750. /**
  11751. * This is only called in the constructor of the graph object
  11752. *
  11753. */
  11754. startWithClustering : function() {
  11755. // cluster if the data set is big
  11756. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11757. // updates the lables after clustering
  11758. this.updateLabels();
  11759. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11760. // the setData function.
  11761. if (this.stabilize) {
  11762. this._stabilize();
  11763. }
  11764. this.start();
  11765. },
  11766. /**
  11767. * This function clusters until the initialMaxNodes has been reached
  11768. *
  11769. * @param {Number} maxNumberOfNodes
  11770. * @param {Boolean} reposition
  11771. */
  11772. clusterToFit : function(maxNumberOfNodes, reposition) {
  11773. var numberOfNodes = this.nodeIndices.length;
  11774. var maxLevels = 50;
  11775. var level = 0;
  11776. // we first cluster the hubs, then we pull in the outliers, repeat
  11777. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11778. if (level % 3 == 0) {
  11779. this.forceAggregateHubs(true);
  11780. this.normalizeClusterLevels();
  11781. }
  11782. else {
  11783. this.increaseClusterLevel(); // this also includes a cluster normalization
  11784. }
  11785. numberOfNodes = this.nodeIndices.length;
  11786. level += 1;
  11787. }
  11788. // after the clustering we reposition the nodes to reduce the initial chaos
  11789. if (level > 0 && reposition == true) {
  11790. this.repositionNodes();
  11791. }
  11792. this._updateCalculationNodes();
  11793. },
  11794. /**
  11795. * This function can be called to open up a specific cluster. It is only called by
  11796. * It will unpack the cluster back one level.
  11797. *
  11798. * @param node | Node object: cluster to open.
  11799. */
  11800. openCluster : function(node) {
  11801. var isMovingBeforeClustering = this.moving;
  11802. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11803. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11804. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11805. this._addSector(node);
  11806. var level = 0;
  11807. // we decluster until we reach a decent number of nodes
  11808. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11809. this.decreaseClusterLevel();
  11810. level += 1;
  11811. }
  11812. }
  11813. else {
  11814. this._expandClusterNode(node,false,true);
  11815. // update the index list, dynamic edges and labels
  11816. this._updateNodeIndexList();
  11817. this._updateDynamicEdges();
  11818. this._updateCalculationNodes();
  11819. this.updateLabels();
  11820. }
  11821. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11822. if (this.moving != isMovingBeforeClustering) {
  11823. this.start();
  11824. }
  11825. },
  11826. /**
  11827. * This calls the updateClustes with default arguments
  11828. */
  11829. updateClustersDefault : function() {
  11830. if (this.constants.clustering.enabled == true) {
  11831. this.updateClusters(0,false,false);
  11832. }
  11833. },
  11834. /**
  11835. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11836. * be clustered with their connected node. This can be repeated as many times as needed.
  11837. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11838. */
  11839. increaseClusterLevel : function() {
  11840. this.updateClusters(-1,false,true);
  11841. },
  11842. /**
  11843. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11844. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11845. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11846. */
  11847. decreaseClusterLevel : function() {
  11848. this.updateClusters(1,false,true);
  11849. },
  11850. /**
  11851. * This is the main clustering function. It clusters and declusters on zoom or forced
  11852. * This function clusters on zoom, it can be called with a predefined zoom direction
  11853. * If out, check if we can form clusters, if in, check if we can open clusters.
  11854. * This function is only called from _zoom()
  11855. *
  11856. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11857. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11858. * @param {Boolean} force | enabled or disable forcing
  11859. *
  11860. */
  11861. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11862. var isMovingBeforeClustering = this.moving;
  11863. var amountOfNodes = this.nodeIndices.length;
  11864. // on zoom out collapse the sector if the scale is at the level the sector was made
  11865. if (this.previousScale > this.scale && zoomDirection == 0) {
  11866. this._collapseSector();
  11867. }
  11868. // check if we zoom in or out
  11869. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11870. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11871. // outer nodes determines if it is being clustered
  11872. this._formClusters(force);
  11873. }
  11874. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11875. if (force == true) {
  11876. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11877. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11878. this._openClusters(recursive,force);
  11879. }
  11880. else {
  11881. // if a cluster takes up a set percentage of the active window
  11882. this._openClustersBySize();
  11883. }
  11884. }
  11885. this._updateNodeIndexList();
  11886. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11887. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11888. this._aggregateHubs(force);
  11889. this._updateNodeIndexList();
  11890. }
  11891. // we now reduce chains.
  11892. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11893. this.handleChains();
  11894. this._updateNodeIndexList();
  11895. }
  11896. this.previousScale = this.scale;
  11897. // rest of the update the index list, dynamic edges and labels
  11898. this._updateDynamicEdges();
  11899. this.updateLabels();
  11900. // if a cluster was formed, we increase the clusterSession
  11901. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  11902. this.clusterSession += 1;
  11903. // if clusters have been made, we normalize the cluster level
  11904. this.normalizeClusterLevels();
  11905. }
  11906. if (doNotStart == false || doNotStart === undefined) {
  11907. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11908. if (this.moving != isMovingBeforeClustering) {
  11909. this.start();
  11910. }
  11911. }
  11912. this._updateCalculationNodes();
  11913. },
  11914. /**
  11915. * This function handles the chains. It is called on every updateClusters().
  11916. */
  11917. handleChains : function() {
  11918. // after clustering we check how many chains there are
  11919. var chainPercentage = this._getChainFraction();
  11920. if (chainPercentage > this.constants.clustering.chainThreshold) {
  11921. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  11922. }
  11923. },
  11924. /**
  11925. * this functions starts clustering by hubs
  11926. * The minimum hub threshold is set globally
  11927. *
  11928. * @private
  11929. */
  11930. _aggregateHubs : function(force) {
  11931. this._getHubSize();
  11932. this._formClustersByHub(force,false);
  11933. },
  11934. /**
  11935. * This function is fired by keypress. It forces hubs to form.
  11936. *
  11937. */
  11938. forceAggregateHubs : function(doNotStart) {
  11939. var isMovingBeforeClustering = this.moving;
  11940. var amountOfNodes = this.nodeIndices.length;
  11941. this._aggregateHubs(true);
  11942. // update the index list, dynamic edges and labels
  11943. this._updateNodeIndexList();
  11944. this._updateDynamicEdges();
  11945. this.updateLabels();
  11946. // if a cluster was formed, we increase the clusterSession
  11947. if (this.nodeIndices.length != amountOfNodes) {
  11948. this.clusterSession += 1;
  11949. }
  11950. if (doNotStart == false || doNotStart === undefined) {
  11951. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11952. if (this.moving != isMovingBeforeClustering) {
  11953. this.start();
  11954. }
  11955. }
  11956. },
  11957. /**
  11958. * If a cluster takes up more than a set percentage of the screen, open the cluster
  11959. *
  11960. * @private
  11961. */
  11962. _openClustersBySize : function() {
  11963. for (var nodeId in this.nodes) {
  11964. if (this.nodes.hasOwnProperty(nodeId)) {
  11965. var node = this.nodes[nodeId];
  11966. if (node.inView() == true) {
  11967. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11968. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11969. this.openCluster(node);
  11970. }
  11971. }
  11972. }
  11973. }
  11974. },
  11975. /**
  11976. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  11977. * has to be opened based on the current zoom level.
  11978. *
  11979. * @private
  11980. */
  11981. _openClusters : function(recursive,force) {
  11982. for (var i = 0; i < this.nodeIndices.length; i++) {
  11983. var node = this.nodes[this.nodeIndices[i]];
  11984. this._expandClusterNode(node,recursive,force);
  11985. this._updateCalculationNodes();
  11986. }
  11987. },
  11988. /**
  11989. * This function checks if a node has to be opened. This is done by checking the zoom level.
  11990. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  11991. * This recursive behaviour is optional and can be set by the recursive argument.
  11992. *
  11993. * @param {Node} parentNode | to check for cluster and expand
  11994. * @param {Boolean} recursive | enabled or disable recursive calling
  11995. * @param {Boolean} force | enabled or disable forcing
  11996. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  11997. * @private
  11998. */
  11999. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12000. // first check if node is a cluster
  12001. if (parentNode.clusterSize > 1) {
  12002. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12003. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12004. openAll = true;
  12005. }
  12006. recursive = openAll ? true : recursive;
  12007. // if the last child has been added on a smaller scale than current scale decluster
  12008. if (parentNode.formationScale < this.scale || force == true) {
  12009. // we will check if any of the contained child nodes should be removed from the cluster
  12010. for (var containedNodeId in parentNode.containedNodes) {
  12011. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12012. var childNode = parentNode.containedNodes[containedNodeId];
  12013. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12014. // the largest cluster is the one that comes from outside
  12015. if (force == true) {
  12016. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12017. || openAll) {
  12018. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12019. }
  12020. }
  12021. else {
  12022. if (this._nodeInActiveArea(parentNode)) {
  12023. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12024. }
  12025. }
  12026. }
  12027. }
  12028. }
  12029. }
  12030. },
  12031. /**
  12032. * ONLY CALLED FROM _expandClusterNode
  12033. *
  12034. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12035. * the child node from the parent contained_node object and put it back into the global nodes object.
  12036. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12037. *
  12038. * @param {Node} parentNode | the parent node
  12039. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12040. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12041. * With force and recursive both true, the entire cluster is unpacked
  12042. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12043. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12044. * @private
  12045. */
  12046. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12047. var childNode = parentNode.containedNodes[containedNodeId];
  12048. // if child node has been added on smaller scale than current, kick out
  12049. if (childNode.formationScale < this.scale || force == true) {
  12050. // unselect all selected items
  12051. this._unselectAll();
  12052. // put the child node back in the global nodes object
  12053. this.nodes[containedNodeId] = childNode;
  12054. // release the contained edges from this childNode back into the global edges
  12055. this._releaseContainedEdges(parentNode,childNode);
  12056. // reconnect rerouted edges to the childNode
  12057. this._connectEdgeBackToChild(parentNode,childNode);
  12058. // validate all edges in dynamicEdges
  12059. this._validateEdges(parentNode);
  12060. // undo the changes from the clustering operation on the parent node
  12061. parentNode.mass -= childNode.mass;
  12062. parentNode.clusterSize -= childNode.clusterSize;
  12063. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12064. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12065. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12066. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12067. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12068. // remove node from the list
  12069. delete parentNode.containedNodes[containedNodeId];
  12070. // check if there are other childs with this clusterSession in the parent.
  12071. var othersPresent = false;
  12072. for (var childNodeId in parentNode.containedNodes) {
  12073. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12074. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12075. othersPresent = true;
  12076. break;
  12077. }
  12078. }
  12079. }
  12080. // if there are no others, remove the cluster session from the list
  12081. if (othersPresent == false) {
  12082. parentNode.clusterSessions.pop();
  12083. }
  12084. this._repositionBezierNodes(childNode);
  12085. // this._repositionBezierNodes(parentNode);
  12086. // remove the clusterSession from the child node
  12087. childNode.clusterSession = 0;
  12088. // recalculate the size of the node on the next time the node is rendered
  12089. parentNode.clearSizeCache();
  12090. // restart the simulation to reorganise all nodes
  12091. this.moving = true;
  12092. }
  12093. // check if a further expansion step is possible if recursivity is enabled
  12094. if (recursive == true) {
  12095. this._expandClusterNode(childNode,recursive,force,openAll);
  12096. }
  12097. },
  12098. /**
  12099. * position the bezier nodes at the center of the edges
  12100. *
  12101. * @param node
  12102. * @private
  12103. */
  12104. _repositionBezierNodes : function(node) {
  12105. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12106. node.dynamicEdges[i].positionBezierNode();
  12107. }
  12108. },
  12109. /**
  12110. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12111. * This function is called only from updateClusters()
  12112. * forceLevelCollapse ignores the length of the edge and collapses one level
  12113. * This means that a node with only one edge will be clustered with its connected node
  12114. *
  12115. * @private
  12116. * @param {Boolean} force
  12117. */
  12118. _formClusters : function(force) {
  12119. if (force == false) {
  12120. this._formClustersByZoom();
  12121. }
  12122. else {
  12123. this._forceClustersByZoom();
  12124. }
  12125. },
  12126. /**
  12127. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12128. *
  12129. * @private
  12130. */
  12131. _formClustersByZoom : function() {
  12132. var dx,dy,length,
  12133. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12134. // check if any edges are shorter than minLength and start the clustering
  12135. // the clustering favours the node with the larger mass
  12136. for (var edgeId in this.edges) {
  12137. if (this.edges.hasOwnProperty(edgeId)) {
  12138. var edge = this.edges[edgeId];
  12139. if (edge.connected) {
  12140. if (edge.toId != edge.fromId) {
  12141. dx = (edge.to.x - edge.from.x);
  12142. dy = (edge.to.y - edge.from.y);
  12143. length = Math.sqrt(dx * dx + dy * dy);
  12144. if (length < minLength) {
  12145. // first check which node is larger
  12146. var parentNode = edge.from;
  12147. var childNode = edge.to;
  12148. if (edge.to.mass > edge.from.mass) {
  12149. parentNode = edge.to;
  12150. childNode = edge.from;
  12151. }
  12152. if (childNode.dynamicEdgesLength == 1) {
  12153. this._addToCluster(parentNode,childNode,false);
  12154. }
  12155. else if (parentNode.dynamicEdgesLength == 1) {
  12156. this._addToCluster(childNode,parentNode,false);
  12157. }
  12158. }
  12159. }
  12160. }
  12161. }
  12162. }
  12163. },
  12164. /**
  12165. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12166. * connected node.
  12167. *
  12168. * @private
  12169. */
  12170. _forceClustersByZoom : function() {
  12171. for (var nodeId in this.nodes) {
  12172. // another node could have absorbed this child.
  12173. if (this.nodes.hasOwnProperty(nodeId)) {
  12174. var childNode = this.nodes[nodeId];
  12175. // the edges can be swallowed by another decrease
  12176. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12177. var edge = childNode.dynamicEdges[0];
  12178. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12179. // group to the largest node
  12180. if (childNode.id != parentNode.id) {
  12181. if (parentNode.mass > childNode.mass) {
  12182. this._addToCluster(parentNode,childNode,true);
  12183. }
  12184. else {
  12185. this._addToCluster(childNode,parentNode,true);
  12186. }
  12187. }
  12188. }
  12189. }
  12190. }
  12191. },
  12192. /**
  12193. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12194. * This function clusters a node to its smallest connected neighbour.
  12195. *
  12196. * @param node
  12197. * @private
  12198. */
  12199. _clusterToSmallestNeighbour : function(node) {
  12200. var smallestNeighbour = -1;
  12201. var smallestNeighbourNode = null;
  12202. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12203. if (node.dynamicEdges[i] !== undefined) {
  12204. var neighbour = null;
  12205. if (node.dynamicEdges[i].fromId != node.id) {
  12206. neighbour = node.dynamicEdges[i].from;
  12207. }
  12208. else if (node.dynamicEdges[i].toId != node.id) {
  12209. neighbour = node.dynamicEdges[i].to;
  12210. }
  12211. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12212. smallestNeighbour = neighbour.clusterSessions.length;
  12213. smallestNeighbourNode = neighbour;
  12214. }
  12215. }
  12216. }
  12217. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12218. this._addToCluster(neighbour, node, true);
  12219. }
  12220. },
  12221. /**
  12222. * This function forms clusters from hubs, it loops over all nodes
  12223. *
  12224. * @param {Boolean} force | Disregard zoom level
  12225. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12226. * @private
  12227. */
  12228. _formClustersByHub : function(force, onlyEqual) {
  12229. // we loop over all nodes in the list
  12230. for (var nodeId in this.nodes) {
  12231. // we check if it is still available since it can be used by the clustering in this loop
  12232. if (this.nodes.hasOwnProperty(nodeId)) {
  12233. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12234. }
  12235. }
  12236. },
  12237. /**
  12238. * This function forms a cluster from a specific preselected hub node
  12239. *
  12240. * @param {Node} hubNode | the node we will cluster as a hub
  12241. * @param {Boolean} force | Disregard zoom level
  12242. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12243. * @param {Number} [absorptionSizeOffset] |
  12244. * @private
  12245. */
  12246. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12247. if (absorptionSizeOffset === undefined) {
  12248. absorptionSizeOffset = 0;
  12249. }
  12250. // we decide if the node is a hub
  12251. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12252. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12253. // initialize variables
  12254. var dx,dy,length;
  12255. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12256. var allowCluster = false;
  12257. // we create a list of edges because the dynamicEdges change over the course of this loop
  12258. var edgesIdarray = [];
  12259. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12260. for (var j = 0; j < amountOfInitialEdges; j++) {
  12261. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12262. }
  12263. // if the hub clustering is not forces, we check if one of the edges connected
  12264. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12265. if (force == false) {
  12266. allowCluster = false;
  12267. for (j = 0; j < amountOfInitialEdges; j++) {
  12268. var edge = this.edges[edgesIdarray[j]];
  12269. if (edge !== undefined) {
  12270. if (edge.connected) {
  12271. if (edge.toId != edge.fromId) {
  12272. dx = (edge.to.x - edge.from.x);
  12273. dy = (edge.to.y - edge.from.y);
  12274. length = Math.sqrt(dx * dx + dy * dy);
  12275. if (length < minLength) {
  12276. allowCluster = true;
  12277. break;
  12278. }
  12279. }
  12280. }
  12281. }
  12282. }
  12283. }
  12284. // start the clustering if allowed
  12285. if ((!force && allowCluster) || force) {
  12286. // we loop over all edges INITIALLY connected to this hub
  12287. for (j = 0; j < amountOfInitialEdges; j++) {
  12288. edge = this.edges[edgesIdarray[j]];
  12289. // the edge can be clustered by this function in a previous loop
  12290. if (edge !== undefined) {
  12291. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12292. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12293. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12294. (childNode.id != hubNode.id)) {
  12295. this._addToCluster(hubNode,childNode,force);
  12296. }
  12297. }
  12298. }
  12299. }
  12300. }
  12301. },
  12302. /**
  12303. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12304. *
  12305. * @param {Node} parentNode | this is the node that will house the child node
  12306. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12307. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12308. * @private
  12309. */
  12310. _addToCluster : function(parentNode, childNode, force) {
  12311. // join child node in the parent node
  12312. parentNode.containedNodes[childNode.id] = childNode;
  12313. // manage all the edges connected to the child and parent nodes
  12314. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12315. var edge = childNode.dynamicEdges[i];
  12316. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12317. this._addToContainedEdges(parentNode,childNode,edge);
  12318. }
  12319. else {
  12320. this._connectEdgeToCluster(parentNode,childNode,edge);
  12321. }
  12322. }
  12323. // a contained node has no dynamic edges.
  12324. childNode.dynamicEdges = [];
  12325. // remove circular edges from clusters
  12326. this._containCircularEdgesFromNode(parentNode,childNode);
  12327. // remove the childNode from the global nodes object
  12328. delete this.nodes[childNode.id];
  12329. // update the properties of the child and parent
  12330. var massBefore = parentNode.mass;
  12331. childNode.clusterSession = this.clusterSession;
  12332. parentNode.mass += childNode.mass;
  12333. parentNode.clusterSize += childNode.clusterSize;
  12334. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12335. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12336. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12337. parentNode.clusterSessions.push(this.clusterSession);
  12338. }
  12339. // forced clusters only open from screen size and double tap
  12340. if (force == true) {
  12341. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12342. parentNode.formationScale = 0;
  12343. }
  12344. else {
  12345. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12346. }
  12347. // recalculate the size of the node on the next time the node is rendered
  12348. parentNode.clearSizeCache();
  12349. // set the pop-out scale for the childnode
  12350. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12351. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12352. childNode.clearVelocity();
  12353. // the mass has altered, preservation of energy dictates the velocity to be updated
  12354. parentNode.updateVelocity(massBefore);
  12355. // restart the simulation to reorganise all nodes
  12356. this.moving = true;
  12357. },
  12358. /**
  12359. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12360. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12361. * It has to be called if a level is collapsed. It is called by _formClusters().
  12362. * @private
  12363. */
  12364. _updateDynamicEdges : function() {
  12365. for (var i = 0; i < this.nodeIndices.length; i++) {
  12366. var node = this.nodes[this.nodeIndices[i]];
  12367. node.dynamicEdgesLength = node.dynamicEdges.length;
  12368. // this corrects for multiple edges pointing at the same other node
  12369. var correction = 0;
  12370. if (node.dynamicEdgesLength > 1) {
  12371. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12372. var edgeToId = node.dynamicEdges[j].toId;
  12373. var edgeFromId = node.dynamicEdges[j].fromId;
  12374. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12375. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12376. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12377. correction += 1;
  12378. }
  12379. }
  12380. }
  12381. }
  12382. node.dynamicEdgesLength -= correction;
  12383. }
  12384. },
  12385. /**
  12386. * This adds an edge from the childNode to the contained edges of the parent node
  12387. *
  12388. * @param parentNode | Node object
  12389. * @param childNode | Node object
  12390. * @param edge | Edge object
  12391. * @private
  12392. */
  12393. _addToContainedEdges : function(parentNode, childNode, edge) {
  12394. // create an array object if it does not yet exist for this childNode
  12395. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12396. parentNode.containedEdges[childNode.id] = []
  12397. }
  12398. // add this edge to the list
  12399. parentNode.containedEdges[childNode.id].push(edge);
  12400. // remove the edge from the global edges object
  12401. delete this.edges[edge.id];
  12402. // remove the edge from the parent object
  12403. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12404. if (parentNode.dynamicEdges[i].id == edge.id) {
  12405. parentNode.dynamicEdges.splice(i,1);
  12406. break;
  12407. }
  12408. }
  12409. },
  12410. /**
  12411. * This function connects an edge that was connected to a child node to the parent node.
  12412. * It keeps track of which nodes it has been connected to with the originalId array.
  12413. *
  12414. * @param {Node} parentNode | Node object
  12415. * @param {Node} childNode | Node object
  12416. * @param {Edge} edge | Edge object
  12417. * @private
  12418. */
  12419. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12420. // handle circular edges
  12421. if (edge.toId == edge.fromId) {
  12422. this._addToContainedEdges(parentNode, childNode, edge);
  12423. }
  12424. else {
  12425. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12426. edge.originalToId.push(childNode.id);
  12427. edge.to = parentNode;
  12428. edge.toId = parentNode.id;
  12429. }
  12430. else { // edge connected to other node with the "from" side
  12431. edge.originalFromId.push(childNode.id);
  12432. edge.from = parentNode;
  12433. edge.fromId = parentNode.id;
  12434. }
  12435. this._addToReroutedEdges(parentNode,childNode,edge);
  12436. }
  12437. },
  12438. /**
  12439. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12440. * these edges inside of the cluster.
  12441. *
  12442. * @param parentNode
  12443. * @param childNode
  12444. * @private
  12445. */
  12446. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12447. // manage all the edges connected to the child and parent nodes
  12448. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12449. var edge = parentNode.dynamicEdges[i];
  12450. // handle circular edges
  12451. if (edge.toId == edge.fromId) {
  12452. this._addToContainedEdges(parentNode, childNode, edge);
  12453. }
  12454. }
  12455. },
  12456. /**
  12457. * This adds an edge from the childNode to the rerouted edges of the parent node
  12458. *
  12459. * @param parentNode | Node object
  12460. * @param childNode | Node object
  12461. * @param edge | Edge object
  12462. * @private
  12463. */
  12464. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12465. // create an array object if it does not yet exist for this childNode
  12466. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12467. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12468. parentNode.reroutedEdges[childNode.id] = [];
  12469. }
  12470. parentNode.reroutedEdges[childNode.id].push(edge);
  12471. // this edge becomes part of the dynamicEdges of the cluster node
  12472. parentNode.dynamicEdges.push(edge);
  12473. },
  12474. /**
  12475. * This function connects an edge that was connected to a cluster node back to the child node.
  12476. *
  12477. * @param parentNode | Node object
  12478. * @param childNode | Node object
  12479. * @private
  12480. */
  12481. _connectEdgeBackToChild : function(parentNode, childNode) {
  12482. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12483. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12484. var edge = parentNode.reroutedEdges[childNode.id][i];
  12485. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12486. edge.originalFromId.pop();
  12487. edge.fromId = childNode.id;
  12488. edge.from = childNode;
  12489. }
  12490. else {
  12491. edge.originalToId.pop();
  12492. edge.toId = childNode.id;
  12493. edge.to = childNode;
  12494. }
  12495. // append this edge to the list of edges connecting to the childnode
  12496. childNode.dynamicEdges.push(edge);
  12497. // remove the edge from the parent object
  12498. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12499. if (parentNode.dynamicEdges[j].id == edge.id) {
  12500. parentNode.dynamicEdges.splice(j,1);
  12501. break;
  12502. }
  12503. }
  12504. }
  12505. // remove the entry from the rerouted edges
  12506. delete parentNode.reroutedEdges[childNode.id];
  12507. }
  12508. },
  12509. /**
  12510. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12511. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12512. * parentNode
  12513. *
  12514. * @param parentNode | Node object
  12515. * @private
  12516. */
  12517. _validateEdges : function(parentNode) {
  12518. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12519. var edge = parentNode.dynamicEdges[i];
  12520. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12521. parentNode.dynamicEdges.splice(i,1);
  12522. }
  12523. }
  12524. },
  12525. /**
  12526. * This function released the contained edges back into the global domain and puts them back into the
  12527. * dynamic edges of both parent and child.
  12528. *
  12529. * @param {Node} parentNode |
  12530. * @param {Node} childNode |
  12531. * @private
  12532. */
  12533. _releaseContainedEdges : function(parentNode, childNode) {
  12534. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12535. var edge = parentNode.containedEdges[childNode.id][i];
  12536. // put the edge back in the global edges object
  12537. this.edges[edge.id] = edge;
  12538. // put the edge back in the dynamic edges of the child and parent
  12539. childNode.dynamicEdges.push(edge);
  12540. parentNode.dynamicEdges.push(edge);
  12541. }
  12542. // remove the entry from the contained edges
  12543. delete parentNode.containedEdges[childNode.id];
  12544. },
  12545. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12546. /**
  12547. * This updates the node labels for all nodes (for debugging purposes)
  12548. */
  12549. updateLabels : function() {
  12550. var nodeId;
  12551. // update node labels
  12552. for (nodeId in this.nodes) {
  12553. if (this.nodes.hasOwnProperty(nodeId)) {
  12554. var node = this.nodes[nodeId];
  12555. if (node.clusterSize > 1) {
  12556. node.label = "[".concat(String(node.clusterSize),"]");
  12557. }
  12558. }
  12559. }
  12560. // update node labels
  12561. for (nodeId in this.nodes) {
  12562. if (this.nodes.hasOwnProperty(nodeId)) {
  12563. node = this.nodes[nodeId];
  12564. if (node.clusterSize == 1) {
  12565. if (node.originalLabel !== undefined) {
  12566. node.label = node.originalLabel;
  12567. }
  12568. else {
  12569. node.label = String(node.id);
  12570. }
  12571. }
  12572. }
  12573. }
  12574. // /* Debug Override */
  12575. // for (nodeId in this.nodes) {
  12576. // if (this.nodes.hasOwnProperty(nodeId)) {
  12577. // node = this.nodes[nodeId];
  12578. // node.label = String(node.level);
  12579. // }
  12580. // }
  12581. },
  12582. /**
  12583. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12584. * if the rest of the nodes are already a few cluster levels in.
  12585. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12586. * clustered enough to the clusterToSmallestNeighbours function.
  12587. */
  12588. normalizeClusterLevels : function() {
  12589. var maxLevel = 0;
  12590. var minLevel = 1e9;
  12591. var clusterLevel = 0;
  12592. // we loop over all nodes in the list
  12593. for (var nodeId in this.nodes) {
  12594. if (this.nodes.hasOwnProperty(nodeId)) {
  12595. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12596. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12597. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12598. }
  12599. }
  12600. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12601. var amountOfNodes = this.nodeIndices.length;
  12602. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12603. // we loop over all nodes in the list
  12604. for (var nodeId in this.nodes) {
  12605. if (this.nodes.hasOwnProperty(nodeId)) {
  12606. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12607. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12608. }
  12609. }
  12610. }
  12611. this._updateNodeIndexList();
  12612. this._updateDynamicEdges();
  12613. // if a cluster was formed, we increase the clusterSession
  12614. if (this.nodeIndices.length != amountOfNodes) {
  12615. this.clusterSession += 1;
  12616. }
  12617. }
  12618. },
  12619. /**
  12620. * This function determines if the cluster we want to decluster is in the active area
  12621. * this means around the zoom center
  12622. *
  12623. * @param {Node} node
  12624. * @returns {boolean}
  12625. * @private
  12626. */
  12627. _nodeInActiveArea : function(node) {
  12628. return (
  12629. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12630. &&
  12631. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12632. )
  12633. },
  12634. /**
  12635. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12636. * It puts large clusters away from the center and randomizes the order.
  12637. *
  12638. */
  12639. repositionNodes : function() {
  12640. for (var i = 0; i < this.nodeIndices.length; i++) {
  12641. var node = this.nodes[this.nodeIndices[i]];
  12642. if ((node.xFixed == false || node.yFixed == false)) {
  12643. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12644. var angle = 2 * Math.PI * Math.random();
  12645. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12646. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12647. this._repositionBezierNodes(node);
  12648. }
  12649. }
  12650. },
  12651. /**
  12652. * We determine how many connections denote an important hub.
  12653. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12654. *
  12655. * @private
  12656. */
  12657. _getHubSize : function() {
  12658. var average = 0;
  12659. var averageSquared = 0;
  12660. var hubCounter = 0;
  12661. var largestHub = 0;
  12662. for (var i = 0; i < this.nodeIndices.length; i++) {
  12663. var node = this.nodes[this.nodeIndices[i]];
  12664. if (node.dynamicEdgesLength > largestHub) {
  12665. largestHub = node.dynamicEdgesLength;
  12666. }
  12667. average += node.dynamicEdgesLength;
  12668. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12669. hubCounter += 1;
  12670. }
  12671. average = average / hubCounter;
  12672. averageSquared = averageSquared / hubCounter;
  12673. var variance = averageSquared - Math.pow(average,2);
  12674. var standardDeviation = Math.sqrt(variance);
  12675. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12676. // always have at least one to cluster
  12677. if (this.hubThreshold > largestHub) {
  12678. this.hubThreshold = largestHub;
  12679. }
  12680. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12681. // console.log("hubThreshold:",this.hubThreshold);
  12682. },
  12683. /**
  12684. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12685. * with this amount we can cluster specifically on these chains.
  12686. *
  12687. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12688. * @private
  12689. */
  12690. _reduceAmountOfChains : function(fraction) {
  12691. this.hubThreshold = 2;
  12692. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12693. for (var nodeId in this.nodes) {
  12694. if (this.nodes.hasOwnProperty(nodeId)) {
  12695. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12696. if (reduceAmount > 0) {
  12697. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12698. reduceAmount -= 1;
  12699. }
  12700. }
  12701. }
  12702. }
  12703. },
  12704. /**
  12705. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12706. * with this amount we can cluster specifically on these chains.
  12707. *
  12708. * @private
  12709. */
  12710. _getChainFraction : function() {
  12711. var chains = 0;
  12712. var total = 0;
  12713. for (var nodeId in this.nodes) {
  12714. if (this.nodes.hasOwnProperty(nodeId)) {
  12715. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12716. chains += 1;
  12717. }
  12718. total += 1;
  12719. }
  12720. }
  12721. return chains/total;
  12722. }
  12723. };
  12724. var SelectionMixin = {
  12725. /**
  12726. * This function can be called from the _doInAllSectors function
  12727. *
  12728. * @param object
  12729. * @param overlappingNodes
  12730. * @private
  12731. */
  12732. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12733. var nodes = this.nodes;
  12734. for (var nodeId in nodes) {
  12735. if (nodes.hasOwnProperty(nodeId)) {
  12736. if (nodes[nodeId].isOverlappingWith(object)) {
  12737. overlappingNodes.push(nodeId);
  12738. }
  12739. }
  12740. }
  12741. },
  12742. /**
  12743. * retrieve all nodes overlapping with given object
  12744. * @param {Object} object An object with parameters left, top, right, bottom
  12745. * @return {Number[]} An array with id's of the overlapping nodes
  12746. * @private
  12747. */
  12748. _getAllNodesOverlappingWith : function (object) {
  12749. var overlappingNodes = [];
  12750. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12751. return overlappingNodes;
  12752. },
  12753. /**
  12754. * Return a position object in canvasspace from a single point in screenspace
  12755. *
  12756. * @param pointer
  12757. * @returns {{left: number, top: number, right: number, bottom: number}}
  12758. * @private
  12759. */
  12760. _pointerToPositionObject : function(pointer) {
  12761. var x = this._canvasToX(pointer.x);
  12762. var y = this._canvasToY(pointer.y);
  12763. return {left: x,
  12764. top: y,
  12765. right: x,
  12766. bottom: y};
  12767. },
  12768. /**
  12769. * Get the top node at the a specific point (like a click)
  12770. *
  12771. * @param {{x: Number, y: Number}} pointer
  12772. * @return {Node | null} node
  12773. * @private
  12774. */
  12775. _getNodeAt : function (pointer) {
  12776. // we first check if this is an navigation controls element
  12777. var positionObject = this._pointerToPositionObject(pointer);
  12778. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12779. // if there are overlapping nodes, select the last one, this is the
  12780. // one which is drawn on top of the others
  12781. if (overlappingNodes.length > 0) {
  12782. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12783. }
  12784. else {
  12785. return null;
  12786. }
  12787. },
  12788. /**
  12789. * retrieve all edges overlapping with given object, selector is around center
  12790. * @param {Object} object An object with parameters left, top, right, bottom
  12791. * @return {Number[]} An array with id's of the overlapping nodes
  12792. * @private
  12793. */
  12794. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12795. var edges = this.edges;
  12796. for (var edgeId in edges) {
  12797. if (edges.hasOwnProperty(edgeId)) {
  12798. if (edges[edgeId].isOverlappingWith(object)) {
  12799. overlappingEdges.push(edgeId);
  12800. }
  12801. }
  12802. }
  12803. },
  12804. /**
  12805. * retrieve all nodes overlapping with given object
  12806. * @param {Object} object An object with parameters left, top, right, bottom
  12807. * @return {Number[]} An array with id's of the overlapping nodes
  12808. * @private
  12809. */
  12810. _getAllEdgesOverlappingWith : function (object) {
  12811. var overlappingEdges = [];
  12812. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12813. return overlappingEdges;
  12814. },
  12815. /**
  12816. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12817. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12818. *
  12819. * @param pointer
  12820. * @returns {null}
  12821. * @private
  12822. */
  12823. _getEdgeAt : function(pointer) {
  12824. var positionObject = this._pointerToPositionObject(pointer);
  12825. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12826. if (overlappingEdges.length > 0) {
  12827. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12828. }
  12829. else {
  12830. return null;
  12831. }
  12832. },
  12833. /**
  12834. * Add object to the selection array.
  12835. *
  12836. * @param obj
  12837. * @private
  12838. */
  12839. _addToSelection : function(obj) {
  12840. if (obj instanceof Node) {
  12841. this.selectionObj.nodes[obj.id] = obj;
  12842. }
  12843. else {
  12844. this.selectionObj.edges[obj.id] = obj;
  12845. }
  12846. },
  12847. /**
  12848. * Remove a single option from selection.
  12849. *
  12850. * @param {Object} obj
  12851. * @private
  12852. */
  12853. _removeFromSelection : function(obj) {
  12854. if (obj instanceof Node) {
  12855. delete this.selectionObj.nodes[obj.id];
  12856. }
  12857. else {
  12858. delete this.selectionObj.edges[obj.id];
  12859. }
  12860. },
  12861. /**
  12862. * Unselect all. The selectionObj is useful for this.
  12863. *
  12864. * @param {Boolean} [doNotTrigger] | ignore trigger
  12865. * @private
  12866. */
  12867. _unselectAll : function(doNotTrigger) {
  12868. if (doNotTrigger === undefined) {
  12869. doNotTrigger = false;
  12870. }
  12871. for(var nodeId in this.selectionObj.nodes) {
  12872. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12873. this.selectionObj.nodes[nodeId].unselect();
  12874. }
  12875. }
  12876. for(var edgeId in this.selectionObj.edges) {
  12877. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12878. this.selectionObj.edges[edgeId].unselect();;
  12879. }
  12880. }
  12881. this.selectionObj = {nodes:{},edges:{}};
  12882. if (doNotTrigger == false) {
  12883. this.emit('select', this.getSelection());
  12884. }
  12885. },
  12886. /**
  12887. * Unselect all clusters. The selectionObj is useful for this.
  12888. *
  12889. * @param {Boolean} [doNotTrigger] | ignore trigger
  12890. * @private
  12891. */
  12892. _unselectClusters : function(doNotTrigger) {
  12893. if (doNotTrigger === undefined) {
  12894. doNotTrigger = false;
  12895. }
  12896. for (var nodeId in this.selectionObj.nodes) {
  12897. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12898. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12899. this.selectionObj.nodes[nodeId].unselect();
  12900. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  12901. }
  12902. }
  12903. }
  12904. if (doNotTrigger == false) {
  12905. this.emit('select', this.getSelection());
  12906. }
  12907. },
  12908. /**
  12909. * return the number of selected nodes
  12910. *
  12911. * @returns {number}
  12912. * @private
  12913. */
  12914. _getSelectedNodeCount : function() {
  12915. var count = 0;
  12916. for (var nodeId in this.selectionObj.nodes) {
  12917. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12918. count += 1;
  12919. }
  12920. }
  12921. return count;
  12922. },
  12923. /**
  12924. * return the number of selected nodes
  12925. *
  12926. * @returns {number}
  12927. * @private
  12928. */
  12929. _getSelectedNode : function() {
  12930. for (var nodeId in this.selectionObj.nodes) {
  12931. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12932. return this.selectionObj.nodes[nodeId];
  12933. }
  12934. }
  12935. return null;
  12936. },
  12937. /**
  12938. * return the number of selected edges
  12939. *
  12940. * @returns {number}
  12941. * @private
  12942. */
  12943. _getSelectedEdgeCount : function() {
  12944. var count = 0;
  12945. for (var edgeId in this.selectionObj.edges) {
  12946. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12947. count += 1;
  12948. }
  12949. }
  12950. return count;
  12951. },
  12952. /**
  12953. * return the number of selected objects.
  12954. *
  12955. * @returns {number}
  12956. * @private
  12957. */
  12958. _getSelectedObjectCount : function() {
  12959. var count = 0;
  12960. for(var nodeId in this.selectionObj.nodes) {
  12961. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12962. count += 1;
  12963. }
  12964. }
  12965. for(var edgeId in this.selectionObj.edges) {
  12966. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12967. count += 1;
  12968. }
  12969. }
  12970. return count;
  12971. },
  12972. /**
  12973. * Check if anything is selected
  12974. *
  12975. * @returns {boolean}
  12976. * @private
  12977. */
  12978. _selectionIsEmpty : function() {
  12979. for(var nodeId in this.selectionObj.nodes) {
  12980. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12981. return false;
  12982. }
  12983. }
  12984. for(var edgeId in this.selectionObj.edges) {
  12985. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12986. return false;
  12987. }
  12988. }
  12989. return true;
  12990. },
  12991. /**
  12992. * check if one of the selected nodes is a cluster.
  12993. *
  12994. * @returns {boolean}
  12995. * @private
  12996. */
  12997. _clusterInSelection : function() {
  12998. for(var nodeId in this.selectionObj.nodes) {
  12999. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13000. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13001. return true;
  13002. }
  13003. }
  13004. }
  13005. return false;
  13006. },
  13007. /**
  13008. * select the edges connected to the node that is being selected
  13009. *
  13010. * @param {Node} node
  13011. * @private
  13012. */
  13013. _selectConnectedEdges : function(node) {
  13014. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13015. var edge = node.dynamicEdges[i];
  13016. edge.select();
  13017. this._addToSelection(edge);
  13018. }
  13019. },
  13020. /**
  13021. * unselect the edges connected to the node that is being selected
  13022. *
  13023. * @param {Node} node
  13024. * @private
  13025. */
  13026. _unselectConnectedEdges : function(node) {
  13027. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13028. var edge = node.dynamicEdges[i];
  13029. edge.unselect();
  13030. this._removeFromSelection(edge);
  13031. }
  13032. },
  13033. /**
  13034. * This is called when someone clicks on a node. either select or deselect it.
  13035. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13036. *
  13037. * @param {Node || Edge} object
  13038. * @param {Boolean} append
  13039. * @param {Boolean} [doNotTrigger] | ignore trigger
  13040. * @private
  13041. */
  13042. _selectObject : function(object, append, doNotTrigger) {
  13043. if (doNotTrigger === undefined) {
  13044. doNotTrigger = false;
  13045. }
  13046. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13047. this._unselectAll(true);
  13048. }
  13049. if (object.selected == false) {
  13050. object.select();
  13051. this._addToSelection(object);
  13052. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13053. this._selectConnectedEdges(object);
  13054. }
  13055. }
  13056. else {
  13057. object.unselect();
  13058. this._removeFromSelection(object);
  13059. }
  13060. if (doNotTrigger == false) {
  13061. this.emit('select', this.getSelection());
  13062. }
  13063. },
  13064. /**
  13065. * handles the selection part of the touch, only for navigation controls elements;
  13066. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13067. * This is the most responsive solution
  13068. *
  13069. * @param {Object} pointer
  13070. * @private
  13071. */
  13072. _handleTouch : function(pointer) {
  13073. },
  13074. /**
  13075. * handles the selection part of the tap;
  13076. *
  13077. * @param {Object} pointer
  13078. * @private
  13079. */
  13080. _handleTap : function(pointer) {
  13081. var node = this._getNodeAt(pointer);
  13082. if (node != null) {
  13083. this._selectObject(node,false);
  13084. }
  13085. else {
  13086. var edge = this._getEdgeAt(pointer);
  13087. if (edge != null) {
  13088. this._selectObject(edge,false);
  13089. }
  13090. else {
  13091. this._unselectAll();
  13092. }
  13093. }
  13094. this.emit("click", this.getSelection());
  13095. this._redraw();
  13096. },
  13097. /**
  13098. * handles the selection part of the double tap and opens a cluster if needed
  13099. *
  13100. * @param {Object} pointer
  13101. * @private
  13102. */
  13103. _handleDoubleTap : function(pointer) {
  13104. var node = this._getNodeAt(pointer);
  13105. if (node != null && node !== undefined) {
  13106. // we reset the areaCenter here so the opening of the node will occur
  13107. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13108. "y" : this._canvasToY(pointer.y)};
  13109. this.openCluster(node);
  13110. }
  13111. this.emit("doubleClick", this.getSelection());
  13112. },
  13113. /**
  13114. * Handle the onHold selection part
  13115. *
  13116. * @param pointer
  13117. * @private
  13118. */
  13119. _handleOnHold : function(pointer) {
  13120. var node = this._getNodeAt(pointer);
  13121. if (node != null) {
  13122. this._selectObject(node,true);
  13123. }
  13124. else {
  13125. var edge = this._getEdgeAt(pointer);
  13126. if (edge != null) {
  13127. this._selectObject(edge,true);
  13128. }
  13129. }
  13130. this._redraw();
  13131. },
  13132. /**
  13133. * handle the onRelease event. These functions are here for the navigation controls module.
  13134. *
  13135. * @private
  13136. */
  13137. _handleOnRelease : function(pointer) {
  13138. },
  13139. /**
  13140. *
  13141. * retrieve the currently selected objects
  13142. * @return {Number[] | String[]} selection An array with the ids of the
  13143. * selected nodes.
  13144. */
  13145. getSelection : function() {
  13146. var nodeIds = this.getSelectedNodes();
  13147. var edgeIds = this.getSelectedEdges();
  13148. return {nodes:nodeIds, edges:edgeIds};
  13149. },
  13150. /**
  13151. *
  13152. * retrieve the currently selected nodes
  13153. * @return {String} selection An array with the ids of the
  13154. * selected nodes.
  13155. */
  13156. getSelectedNodes : function() {
  13157. var idArray = [];
  13158. for(var nodeId in this.selectionObj.nodes) {
  13159. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13160. idArray.push(nodeId);
  13161. }
  13162. }
  13163. return idArray
  13164. },
  13165. /**
  13166. *
  13167. * retrieve the currently selected edges
  13168. * @return {Array} selection An array with the ids of the
  13169. * selected nodes.
  13170. */
  13171. getSelectedEdges : function() {
  13172. var idArray = [];
  13173. for(var edgeId in this.selectionObj.edges) {
  13174. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13175. idArray.push(edgeId);
  13176. }
  13177. }
  13178. return idArray;
  13179. },
  13180. /**
  13181. * select zero or more nodes
  13182. * @param {Number[] | String[]} selection An array with the ids of the
  13183. * selected nodes.
  13184. */
  13185. setSelection : function(selection) {
  13186. var i, iMax, id;
  13187. if (!selection || (selection.length == undefined))
  13188. throw 'Selection must be an array with ids';
  13189. // first unselect any selected node
  13190. this._unselectAll(true);
  13191. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13192. id = selection[i];
  13193. var node = this.nodes[id];
  13194. if (!node) {
  13195. throw new RangeError('Node with id "' + id + '" not found');
  13196. }
  13197. this._selectObject(node,true,true);
  13198. }
  13199. this.redraw();
  13200. },
  13201. /**
  13202. * Validate the selection: remove ids of nodes which no longer exist
  13203. * @private
  13204. */
  13205. _updateSelection : function () {
  13206. for(var nodeId in this.selectionObj.nodes) {
  13207. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13208. if (!this.nodes.hasOwnProperty(nodeId)) {
  13209. delete this.selectionObj.nodes[nodeId];
  13210. }
  13211. }
  13212. }
  13213. for(var edgeId in this.selectionObj.edges) {
  13214. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13215. if (!this.edges.hasOwnProperty(edgeId)) {
  13216. delete this.selectionObj.edges[edgeId];
  13217. }
  13218. }
  13219. }
  13220. }
  13221. };
  13222. /**
  13223. * Created by Alex on 1/22/14.
  13224. */
  13225. var NavigationMixin = {
  13226. _cleanNavigation : function() {
  13227. // clean up previosu navigation items
  13228. var wrapper = document.getElementById('graph-navigation_wrapper');
  13229. if (wrapper != null) {
  13230. this.containerElement.removeChild(wrapper);
  13231. }
  13232. document.onmouseup = null;
  13233. },
  13234. /**
  13235. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13236. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13237. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13238. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13239. *
  13240. * @private
  13241. */
  13242. _loadNavigationElements : function() {
  13243. this._cleanNavigation();
  13244. this.navigationDivs = {};
  13245. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13246. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13247. this.navigationDivs['wrapper'] = document.createElement('div');
  13248. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13249. this.navigationDivs['wrapper'].style.position = "absolute";
  13250. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13251. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13252. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13253. for (var i = 0; i < navigationDivs.length; i++) {
  13254. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13255. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13256. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13257. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13258. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13259. }
  13260. document.onmouseup = this._stopMovement.bind(this);
  13261. },
  13262. /**
  13263. * this stops all movement induced by the navigation buttons
  13264. *
  13265. * @private
  13266. */
  13267. _stopMovement : function() {
  13268. this._xStopMoving();
  13269. this._yStopMoving();
  13270. this._stopZoom();
  13271. },
  13272. /**
  13273. * stops the actions performed by page up and down etc.
  13274. *
  13275. * @param event
  13276. * @private
  13277. */
  13278. _preventDefault : function(event) {
  13279. if (event !== undefined) {
  13280. if (event.preventDefault) {
  13281. event.preventDefault();
  13282. } else {
  13283. event.returnValue = false;
  13284. }
  13285. }
  13286. },
  13287. /**
  13288. * move the screen up
  13289. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13290. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13291. * To avoid this behaviour, we do the translation in the start loop.
  13292. *
  13293. * @private
  13294. */
  13295. _moveUp : function(event) {
  13296. this.yIncrement = this.constants.keyboard.speed.y;
  13297. this.start(); // if there is no node movement, the calculation wont be done
  13298. this._preventDefault(event);
  13299. if (this.navigationDivs) {
  13300. this.navigationDivs['up'].className += " active";
  13301. }
  13302. },
  13303. /**
  13304. * move the screen down
  13305. * @private
  13306. */
  13307. _moveDown : function(event) {
  13308. this.yIncrement = -this.constants.keyboard.speed.y;
  13309. this.start(); // if there is no node movement, the calculation wont be done
  13310. this._preventDefault(event);
  13311. if (this.navigationDivs) {
  13312. this.navigationDivs['down'].className += " active";
  13313. }
  13314. },
  13315. /**
  13316. * move the screen left
  13317. * @private
  13318. */
  13319. _moveLeft : function(event) {
  13320. this.xIncrement = this.constants.keyboard.speed.x;
  13321. this.start(); // if there is no node movement, the calculation wont be done
  13322. this._preventDefault(event);
  13323. if (this.navigationDivs) {
  13324. this.navigationDivs['left'].className += " active";
  13325. }
  13326. },
  13327. /**
  13328. * move the screen right
  13329. * @private
  13330. */
  13331. _moveRight : function(event) {
  13332. this.xIncrement = -this.constants.keyboard.speed.y;
  13333. this.start(); // if there is no node movement, the calculation wont be done
  13334. this._preventDefault(event);
  13335. if (this.navigationDivs) {
  13336. this.navigationDivs['right'].className += " active";
  13337. }
  13338. },
  13339. /**
  13340. * Zoom in, using the same method as the movement.
  13341. * @private
  13342. */
  13343. _zoomIn : function(event) {
  13344. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13345. this.start(); // if there is no node movement, the calculation wont be done
  13346. this._preventDefault(event);
  13347. if (this.navigationDivs) {
  13348. this.navigationDivs['zoomIn'].className += " active";
  13349. }
  13350. },
  13351. /**
  13352. * Zoom out
  13353. * @private
  13354. */
  13355. _zoomOut : function() {
  13356. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13357. this.start(); // if there is no node movement, the calculation wont be done
  13358. this._preventDefault(event);
  13359. if (this.navigationDivs) {
  13360. this.navigationDivs['zoomOut'].className += " active";
  13361. }
  13362. },
  13363. /**
  13364. * Stop zooming and unhighlight the zoom controls
  13365. * @private
  13366. */
  13367. _stopZoom : function() {
  13368. this.zoomIncrement = 0;
  13369. if (this.navigationDivs) {
  13370. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13371. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13372. }
  13373. },
  13374. /**
  13375. * Stop moving in the Y direction and unHighlight the up and down
  13376. * @private
  13377. */
  13378. _yStopMoving : function() {
  13379. this.yIncrement = 0;
  13380. if (this.navigationDivs) {
  13381. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13382. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13383. }
  13384. },
  13385. /**
  13386. * Stop moving in the X direction and unHighlight left and right.
  13387. * @private
  13388. */
  13389. _xStopMoving : function() {
  13390. this.xIncrement = 0;
  13391. if (this.navigationDivs) {
  13392. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13393. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13394. }
  13395. }
  13396. };
  13397. /**
  13398. * Created by Alex on 2/10/14.
  13399. */
  13400. var graphMixinLoaders = {
  13401. /**
  13402. * Load a mixin into the graph object
  13403. *
  13404. * @param {Object} sourceVariable | this object has to contain functions.
  13405. * @private
  13406. */
  13407. _loadMixin: function (sourceVariable) {
  13408. for (var mixinFunction in sourceVariable) {
  13409. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13410. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13411. }
  13412. }
  13413. },
  13414. /**
  13415. * removes a mixin from the graph object.
  13416. *
  13417. * @param {Object} sourceVariable | this object has to contain functions.
  13418. * @private
  13419. */
  13420. _clearMixin: function (sourceVariable) {
  13421. for (var mixinFunction in sourceVariable) {
  13422. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13423. Graph.prototype[mixinFunction] = undefined;
  13424. }
  13425. }
  13426. },
  13427. /**
  13428. * Mixin the physics system and initialize the parameters required.
  13429. *
  13430. * @private
  13431. */
  13432. _loadPhysicsSystem: function () {
  13433. this._loadMixin(physicsMixin);
  13434. this._loadSelectedForceSolver();
  13435. if (this.constants.configurePhysics == true) {
  13436. this._loadPhysicsConfiguration();
  13437. }
  13438. },
  13439. /**
  13440. * Mixin the cluster system and initialize the parameters required.
  13441. *
  13442. * @private
  13443. */
  13444. _loadClusterSystem: function () {
  13445. this.clusterSession = 0;
  13446. this.hubThreshold = 5;
  13447. this._loadMixin(ClusterMixin);
  13448. },
  13449. /**
  13450. * Mixin the sector system and initialize the parameters required
  13451. *
  13452. * @private
  13453. */
  13454. _loadSectorSystem: function () {
  13455. this.sectors = { },
  13456. this.activeSector = ["default"];
  13457. this.sectors["active"] = { },
  13458. this.sectors["active"]["default"] = {"nodes": {},
  13459. "edges": {},
  13460. "nodeIndices": [],
  13461. "formationScale": 1.0,
  13462. "drawingNode": undefined };
  13463. this.sectors["frozen"] = {},
  13464. this.sectors["support"] = {"nodes": {},
  13465. "edges": {},
  13466. "nodeIndices": [],
  13467. "formationScale": 1.0,
  13468. "drawingNode": undefined };
  13469. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13470. this._loadMixin(SectorMixin);
  13471. },
  13472. /**
  13473. * Mixin the selection system and initialize the parameters required
  13474. *
  13475. * @private
  13476. */
  13477. _loadSelectionSystem: function () {
  13478. this.selectionObj = {nodes: {}, edges: {}};
  13479. this._loadMixin(SelectionMixin);
  13480. },
  13481. /**
  13482. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13483. *
  13484. * @private
  13485. */
  13486. _loadManipulationSystem: function () {
  13487. // reset global variables -- these are used by the selection of nodes and edges.
  13488. this.blockConnectingEdgeSelection = false;
  13489. this.forceAppendSelection = false
  13490. if (this.constants.dataManipulation.enabled == true) {
  13491. // load the manipulator HTML elements. All styling done in css.
  13492. if (this.manipulationDiv === undefined) {
  13493. this.manipulationDiv = document.createElement('div');
  13494. this.manipulationDiv.className = 'graph-manipulationDiv';
  13495. this.manipulationDiv.id = 'graph-manipulationDiv';
  13496. if (this.editMode == true) {
  13497. this.manipulationDiv.style.display = "block";
  13498. }
  13499. else {
  13500. this.manipulationDiv.style.display = "none";
  13501. }
  13502. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13503. }
  13504. if (this.editModeDiv === undefined) {
  13505. this.editModeDiv = document.createElement('div');
  13506. this.editModeDiv.className = 'graph-manipulation-editMode';
  13507. this.editModeDiv.id = 'graph-manipulation-editMode';
  13508. if (this.editMode == true) {
  13509. this.editModeDiv.style.display = "none";
  13510. }
  13511. else {
  13512. this.editModeDiv.style.display = "block";
  13513. }
  13514. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13515. }
  13516. if (this.closeDiv === undefined) {
  13517. this.closeDiv = document.createElement('div');
  13518. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13519. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13520. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13521. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13522. }
  13523. // load the manipulation functions
  13524. this._loadMixin(manipulationMixin);
  13525. // create the manipulator toolbar
  13526. this._createManipulatorBar();
  13527. }
  13528. else {
  13529. if (this.manipulationDiv !== undefined) {
  13530. // removes all the bindings and overloads
  13531. this._createManipulatorBar();
  13532. // remove the manipulation divs
  13533. this.containerElement.removeChild(this.manipulationDiv);
  13534. this.containerElement.removeChild(this.editModeDiv);
  13535. this.containerElement.removeChild(this.closeDiv);
  13536. this.manipulationDiv = undefined;
  13537. this.editModeDiv = undefined;
  13538. this.closeDiv = undefined;
  13539. // remove the mixin functions
  13540. this._clearMixin(manipulationMixin);
  13541. }
  13542. }
  13543. },
  13544. /**
  13545. * Mixin the navigation (User Interface) system and initialize the parameters required
  13546. *
  13547. * @private
  13548. */
  13549. _loadNavigationControls: function () {
  13550. this._loadMixin(NavigationMixin);
  13551. // the clean function removes the button divs, this is done to remove the bindings.
  13552. this._cleanNavigation();
  13553. if (this.constants.navigation.enabled == true) {
  13554. this._loadNavigationElements();
  13555. }
  13556. },
  13557. /**
  13558. * Mixin the hierarchical layout system.
  13559. *
  13560. * @private
  13561. */
  13562. _loadHierarchySystem: function () {
  13563. this._loadMixin(HierarchicalLayoutMixin);
  13564. }
  13565. };
  13566. /**
  13567. * @constructor Graph
  13568. * Create a graph visualization, displaying nodes and edges.
  13569. *
  13570. * @param {Element} container The DOM element in which the Graph will
  13571. * be created. Normally a div element.
  13572. * @param {Object} data An object containing parameters
  13573. * {Array} nodes
  13574. * {Array} edges
  13575. * @param {Object} options Options
  13576. */
  13577. function Graph (container, data, options) {
  13578. this._initializeMixinLoaders();
  13579. // create variables and set default values
  13580. this.containerElement = container;
  13581. this.width = '100%';
  13582. this.height = '100%';
  13583. // render and calculation settings
  13584. this.renderRefreshRate = 60; // hz (fps)
  13585. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13586. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13587. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13588. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13589. this.stabilize = true; // stabilize before displaying the graph
  13590. this.selectable = true;
  13591. this.initializing = true;
  13592. // these functions are triggered when the dataset is edited
  13593. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13594. // set constant values
  13595. this.constants = {
  13596. nodes: {
  13597. radiusMin: 5,
  13598. radiusMax: 20,
  13599. radius: 5,
  13600. shape: 'ellipse',
  13601. image: undefined,
  13602. widthMin: 16, // px
  13603. widthMax: 64, // px
  13604. fixed: false,
  13605. fontColor: 'black',
  13606. fontSize: 14, // px
  13607. fontFace: 'verdana',
  13608. level: -1,
  13609. color: {
  13610. border: '#2B7CE9',
  13611. background: '#97C2FC',
  13612. highlight: {
  13613. border: '#2B7CE9',
  13614. background: '#D2E5FF'
  13615. }
  13616. },
  13617. borderColor: '#2B7CE9',
  13618. backgroundColor: '#97C2FC',
  13619. highlightColor: '#D2E5FF',
  13620. group: undefined
  13621. },
  13622. edges: {
  13623. widthMin: 1,
  13624. widthMax: 15,
  13625. width: 1,
  13626. style: 'line',
  13627. color: {
  13628. color:'#848484',
  13629. highlight:'#848484'
  13630. },
  13631. fontColor: '#343434',
  13632. fontSize: 14, // px
  13633. fontFace: 'arial',
  13634. fontFill: 'white',
  13635. arrowScaleFactor: 1,
  13636. dash: {
  13637. length: 10,
  13638. gap: 5,
  13639. altLength: undefined
  13640. }
  13641. },
  13642. configurePhysics:false,
  13643. physics: {
  13644. barnesHut: {
  13645. enabled: true,
  13646. theta: 1 / 0.6, // inverted to save time during calculation
  13647. gravitationalConstant: -2000,
  13648. centralGravity: 0.3,
  13649. springLength: 95,
  13650. springConstant: 0.04,
  13651. damping: 0.09
  13652. },
  13653. repulsion: {
  13654. centralGravity: 0.1,
  13655. springLength: 200,
  13656. springConstant: 0.05,
  13657. nodeDistance: 100,
  13658. damping: 0.09
  13659. },
  13660. hierarchicalRepulsion: {
  13661. enabled: false,
  13662. centralGravity: 0.0,
  13663. springLength: 100,
  13664. springConstant: 0.01,
  13665. nodeDistance: 60,
  13666. damping: 0.09
  13667. },
  13668. damping: null,
  13669. centralGravity: null,
  13670. springLength: null,
  13671. springConstant: null
  13672. },
  13673. clustering: { // Per Node in Cluster = PNiC
  13674. enabled: false, // (Boolean) | global on/off switch for clustering.
  13675. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13676. 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
  13677. 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
  13678. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13679. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13680. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13681. 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.
  13682. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13683. maxFontSize: 1000,
  13684. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13685. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13686. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13687. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13688. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13689. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13690. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13691. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13692. clusterLevelDifference: 2
  13693. },
  13694. navigation: {
  13695. enabled: false
  13696. },
  13697. keyboard: {
  13698. enabled: false,
  13699. speed: {x: 10, y: 10, zoom: 0.02}
  13700. },
  13701. dataManipulation: {
  13702. enabled: false,
  13703. initiallyVisible: false
  13704. },
  13705. hierarchicalLayout: {
  13706. enabled:false,
  13707. levelSeparation: 150,
  13708. nodeSpacing: 100,
  13709. direction: "UD" // UD, DU, LR, RL
  13710. },
  13711. freezeForStabilization: false,
  13712. smoothCurves: true,
  13713. maxVelocity: 10,
  13714. minVelocity: 0.1, // px/s
  13715. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13716. labels:{
  13717. add:"Add Node",
  13718. edit:"Edit",
  13719. link:"Add Link",
  13720. del:"Delete selected",
  13721. editNode:"Edit Node",
  13722. back:"Back",
  13723. addDescription:"Click in an empty space to place a new node.",
  13724. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13725. addError:"The function for add does not support two arguments (data,callback).",
  13726. linkError:"The function for connect does not support two arguments (data,callback).",
  13727. editError:"The function for edit does not support two arguments (data, callback).",
  13728. editBoundError:"No edit function has been bound to this button.",
  13729. deleteError:"The function for delete does not support two arguments (data, callback).",
  13730. deleteClusterError:"Clusters cannot be deleted."
  13731. },
  13732. tooltip: {
  13733. delay: 300,
  13734. fontColor: 'black',
  13735. fontSize: 14, // px
  13736. fontFace: 'verdana',
  13737. color: {
  13738. border: '#666',
  13739. background: '#FFFFC6'
  13740. }
  13741. }
  13742. };
  13743. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13744. // Node variables
  13745. var graph = this;
  13746. this.groups = new Groups(); // object with groups
  13747. this.images = new Images(); // object with images
  13748. this.images.setOnloadCallback(function () {
  13749. graph._redraw();
  13750. });
  13751. // keyboard navigation variables
  13752. this.xIncrement = 0;
  13753. this.yIncrement = 0;
  13754. this.zoomIncrement = 0;
  13755. // loading all the mixins:
  13756. // load the force calculation functions, grouped under the physics system.
  13757. this._loadPhysicsSystem();
  13758. // create a frame and canvas
  13759. this._create();
  13760. // load the sector system. (mandatory, fully integrated with Graph)
  13761. this._loadSectorSystem();
  13762. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13763. this._loadClusterSystem();
  13764. // load the selection system. (mandatory, required by Graph)
  13765. this._loadSelectionSystem();
  13766. // load the selection system. (mandatory, required by Graph)
  13767. this._loadHierarchySystem();
  13768. // apply options
  13769. this.setOptions(options);
  13770. // other vars
  13771. this.freezeSimulation = false;// freeze the simulation
  13772. this.cachedFunctions = {};
  13773. // containers for nodes and edges
  13774. this.calculationNodes = {};
  13775. this.calculationNodeIndices = [];
  13776. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13777. this.nodes = {}; // object with Node objects
  13778. this.edges = {}; // object with Edge objects
  13779. // position and scale variables and objects
  13780. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13781. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13782. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13783. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13784. this.scale = 1; // defining the global scale variable in the constructor
  13785. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13786. // datasets or dataviews
  13787. this.nodesData = null; // A DataSet or DataView
  13788. this.edgesData = null; // A DataSet or DataView
  13789. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13790. this.nodesListeners = {
  13791. 'add': function (event, params) {
  13792. graph._addNodes(params.items);
  13793. graph.start();
  13794. },
  13795. 'update': function (event, params) {
  13796. graph._updateNodes(params.items);
  13797. graph.start();
  13798. },
  13799. 'remove': function (event, params) {
  13800. graph._removeNodes(params.items);
  13801. graph.start();
  13802. }
  13803. };
  13804. this.edgesListeners = {
  13805. 'add': function (event, params) {
  13806. graph._addEdges(params.items);
  13807. graph.start();
  13808. },
  13809. 'update': function (event, params) {
  13810. graph._updateEdges(params.items);
  13811. graph.start();
  13812. },
  13813. 'remove': function (event, params) {
  13814. graph._removeEdges(params.items);
  13815. graph.start();
  13816. }
  13817. };
  13818. // properties for the animation
  13819. this.moving = true;
  13820. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13821. // load data (the disable start variable will be the same as the enabled clustering)
  13822. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13823. // hierarchical layout
  13824. this.initializing = false;
  13825. if (this.constants.hierarchicalLayout.enabled == true) {
  13826. this._setupHierarchicalLayout();
  13827. }
  13828. else {
  13829. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13830. if (this.stabilize == false) {
  13831. this.zoomExtent(true,this.constants.clustering.enabled);
  13832. }
  13833. }
  13834. // if clustering is disabled, the simulation will have started in the setData function
  13835. if (this.constants.clustering.enabled) {
  13836. this.startWithClustering();
  13837. }
  13838. }
  13839. // Extend Graph with an Emitter mixin
  13840. Emitter(Graph.prototype);
  13841. /**
  13842. * Get the script path where the vis.js library is located
  13843. *
  13844. * @returns {string | null} path Path or null when not found. Path does not
  13845. * end with a slash.
  13846. * @private
  13847. */
  13848. Graph.prototype._getScriptPath = function() {
  13849. var scripts = document.getElementsByTagName( 'script' );
  13850. // find script named vis.js or vis.min.js
  13851. for (var i = 0; i < scripts.length; i++) {
  13852. var src = scripts[i].src;
  13853. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13854. if (match) {
  13855. // return path without the script name
  13856. return src.substring(0, src.length - match[0].length);
  13857. }
  13858. }
  13859. return null;
  13860. };
  13861. /**
  13862. * Find the center position of the graph
  13863. * @private
  13864. */
  13865. Graph.prototype._getRange = function() {
  13866. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13867. for (var nodeId in this.nodes) {
  13868. if (this.nodes.hasOwnProperty(nodeId)) {
  13869. node = this.nodes[nodeId];
  13870. if (minX > (node.x)) {minX = node.x;}
  13871. if (maxX < (node.x)) {maxX = node.x;}
  13872. if (minY > (node.y)) {minY = node.y;}
  13873. if (maxY < (node.y)) {maxY = node.y;}
  13874. }
  13875. }
  13876. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13877. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13878. }
  13879. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13880. };
  13881. /**
  13882. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13883. * @returns {{x: number, y: number}}
  13884. * @private
  13885. */
  13886. Graph.prototype._findCenter = function(range) {
  13887. return {x: (0.5 * (range.maxX + range.minX)),
  13888. y: (0.5 * (range.maxY + range.minY))};
  13889. };
  13890. /**
  13891. * center the graph
  13892. *
  13893. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13894. */
  13895. Graph.prototype._centerGraph = function(range) {
  13896. var center = this._findCenter(range);
  13897. center.x *= this.scale;
  13898. center.y *= this.scale;
  13899. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13900. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13901. this._setTranslation(-center.x,-center.y); // set at 0,0
  13902. };
  13903. /**
  13904. * This function zooms out to fit all data on screen based on amount of nodes
  13905. *
  13906. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13907. */
  13908. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  13909. if (initialZoom === undefined) {
  13910. initialZoom = false;
  13911. }
  13912. if (disableStart === undefined) {
  13913. disableStart = false;
  13914. }
  13915. var range = this._getRange();
  13916. var zoomLevel;
  13917. if (initialZoom == true) {
  13918. var numberOfNodes = this.nodeIndices.length;
  13919. if (this.constants.smoothCurves == true) {
  13920. if (this.constants.clustering.enabled == true &&
  13921. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13922. 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.
  13923. }
  13924. else {
  13925. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13926. }
  13927. }
  13928. else {
  13929. if (this.constants.clustering.enabled == true &&
  13930. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13931. 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.
  13932. }
  13933. else {
  13934. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13935. }
  13936. }
  13937. // correct for larger canvasses.
  13938. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  13939. zoomLevel *= factor;
  13940. }
  13941. else {
  13942. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  13943. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  13944. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13945. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13946. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13947. }
  13948. if (zoomLevel > 1.0) {
  13949. zoomLevel = 1.0;
  13950. }
  13951. this._setScale(zoomLevel);
  13952. this._centerGraph(range);
  13953. if (disableStart == false) {
  13954. this.moving = true;
  13955. this.start();
  13956. }
  13957. };
  13958. /**
  13959. * Update the this.nodeIndices with the most recent node index list
  13960. * @private
  13961. */
  13962. Graph.prototype._updateNodeIndexList = function() {
  13963. this._clearNodeIndexList();
  13964. for (var idx in this.nodes) {
  13965. if (this.nodes.hasOwnProperty(idx)) {
  13966. this.nodeIndices.push(idx);
  13967. }
  13968. }
  13969. };
  13970. /**
  13971. * Set nodes and edges, and optionally options as well.
  13972. *
  13973. * @param {Object} data Object containing parameters:
  13974. * {Array | DataSet | DataView} [nodes] Array with nodes
  13975. * {Array | DataSet | DataView} [edges] Array with edges
  13976. * {String} [dot] String containing data in DOT format
  13977. * {Options} [options] Object with options
  13978. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  13979. */
  13980. Graph.prototype.setData = function(data, disableStart) {
  13981. if (disableStart === undefined) {
  13982. disableStart = false;
  13983. }
  13984. if (data && data.dot && (data.nodes || data.edges)) {
  13985. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13986. ' parameter pair "nodes" and "edges", but not both.');
  13987. }
  13988. // set options
  13989. this.setOptions(data && data.options);
  13990. // set all data
  13991. if (data && data.dot) {
  13992. // parse DOT file
  13993. if(data && data.dot) {
  13994. var dotData = vis.util.DOTToGraph(data.dot);
  13995. this.setData(dotData);
  13996. return;
  13997. }
  13998. }
  13999. else {
  14000. this._setNodes(data && data.nodes);
  14001. this._setEdges(data && data.edges);
  14002. }
  14003. this._putDataInSector();
  14004. if (!disableStart) {
  14005. // find a stable position or start animating to a stable position
  14006. if (this.stabilize) {
  14007. this._stabilize();
  14008. }
  14009. this.start();
  14010. }
  14011. };
  14012. /**
  14013. * Set options
  14014. * @param {Object} options
  14015. */
  14016. Graph.prototype.setOptions = function (options) {
  14017. if (options) {
  14018. var prop;
  14019. // retrieve parameter values
  14020. if (options.width !== undefined) {this.width = options.width;}
  14021. if (options.height !== undefined) {this.height = options.height;}
  14022. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14023. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14024. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14025. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14026. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14027. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14028. if (options.labels !== undefined) {
  14029. for (prop in options.labels) {
  14030. if (options.labels.hasOwnProperty(prop)) {
  14031. this.constants.labels[prop] = options.labels[prop];
  14032. }
  14033. }
  14034. }
  14035. if (options.onAdd) {
  14036. this.triggerFunctions.add = options.onAdd;
  14037. }
  14038. if (options.onEdit) {
  14039. this.triggerFunctions.edit = options.onEdit;
  14040. }
  14041. if (options.onConnect) {
  14042. this.triggerFunctions.connect = options.onConnect;
  14043. }
  14044. if (options.onDelete) {
  14045. this.triggerFunctions.del = options.onDelete;
  14046. }
  14047. if (options.physics) {
  14048. if (options.physics.barnesHut) {
  14049. this.constants.physics.barnesHut.enabled = true;
  14050. for (prop in options.physics.barnesHut) {
  14051. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14052. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14053. }
  14054. }
  14055. }
  14056. if (options.physics.repulsion) {
  14057. this.constants.physics.barnesHut.enabled = false;
  14058. for (prop in options.physics.repulsion) {
  14059. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14060. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14061. }
  14062. }
  14063. }
  14064. }
  14065. if (options.hierarchicalLayout) {
  14066. this.constants.hierarchicalLayout.enabled = true;
  14067. for (prop in options.hierarchicalLayout) {
  14068. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14069. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14070. }
  14071. }
  14072. }
  14073. else if (options.hierarchicalLayout !== undefined) {
  14074. this.constants.hierarchicalLayout.enabled = false;
  14075. }
  14076. if (options.clustering) {
  14077. this.constants.clustering.enabled = true;
  14078. for (prop in options.clustering) {
  14079. if (options.clustering.hasOwnProperty(prop)) {
  14080. this.constants.clustering[prop] = options.clustering[prop];
  14081. }
  14082. }
  14083. }
  14084. else if (options.clustering !== undefined) {
  14085. this.constants.clustering.enabled = false;
  14086. }
  14087. if (options.navigation) {
  14088. this.constants.navigation.enabled = true;
  14089. for (prop in options.navigation) {
  14090. if (options.navigation.hasOwnProperty(prop)) {
  14091. this.constants.navigation[prop] = options.navigation[prop];
  14092. }
  14093. }
  14094. }
  14095. else if (options.navigation !== undefined) {
  14096. this.constants.navigation.enabled = false;
  14097. }
  14098. if (options.keyboard) {
  14099. this.constants.keyboard.enabled = true;
  14100. for (prop in options.keyboard) {
  14101. if (options.keyboard.hasOwnProperty(prop)) {
  14102. this.constants.keyboard[prop] = options.keyboard[prop];
  14103. }
  14104. }
  14105. }
  14106. else if (options.keyboard !== undefined) {
  14107. this.constants.keyboard.enabled = false;
  14108. }
  14109. if (options.dataManipulation) {
  14110. this.constants.dataManipulation.enabled = true;
  14111. for (prop in options.dataManipulation) {
  14112. if (options.dataManipulation.hasOwnProperty(prop)) {
  14113. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14114. }
  14115. }
  14116. }
  14117. else if (options.dataManipulation !== undefined) {
  14118. this.constants.dataManipulation.enabled = false;
  14119. }
  14120. // TODO: work out these options and document them
  14121. if (options.edges) {
  14122. for (prop in options.edges) {
  14123. if (options.edges.hasOwnProperty(prop)) {
  14124. if (typeof options.edges[prop] != "object") {
  14125. this.constants.edges[prop] = options.edges[prop];
  14126. }
  14127. }
  14128. }
  14129. if (options.edges.color !== undefined) {
  14130. if (util.isString(options.edges.color)) {
  14131. this.constants.edges.color = {};
  14132. this.constants.edges.color.color = options.edges.color;
  14133. this.constants.edges.color.highlight = options.edges.color;
  14134. }
  14135. else {
  14136. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14137. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14138. }
  14139. }
  14140. if (!options.edges.fontColor) {
  14141. if (options.edges.color !== undefined) {
  14142. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14143. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14144. }
  14145. }
  14146. // Added to support dashed lines
  14147. // David Jordan
  14148. // 2012-08-08
  14149. if (options.edges.dash) {
  14150. if (options.edges.dash.length !== undefined) {
  14151. this.constants.edges.dash.length = options.edges.dash.length;
  14152. }
  14153. if (options.edges.dash.gap !== undefined) {
  14154. this.constants.edges.dash.gap = options.edges.dash.gap;
  14155. }
  14156. if (options.edges.dash.altLength !== undefined) {
  14157. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14158. }
  14159. }
  14160. }
  14161. if (options.nodes) {
  14162. for (prop in options.nodes) {
  14163. if (options.nodes.hasOwnProperty(prop)) {
  14164. this.constants.nodes[prop] = options.nodes[prop];
  14165. }
  14166. }
  14167. if (options.nodes.color) {
  14168. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14169. }
  14170. /*
  14171. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14172. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14173. */
  14174. }
  14175. if (options.groups) {
  14176. for (var groupname in options.groups) {
  14177. if (options.groups.hasOwnProperty(groupname)) {
  14178. var group = options.groups[groupname];
  14179. this.groups.add(groupname, group);
  14180. }
  14181. }
  14182. }
  14183. if (options.tooltip) {
  14184. for (prop in options.tooltip) {
  14185. if (options.tooltip.hasOwnProperty(prop)) {
  14186. this.constants.tooltip[prop] = options.tooltip[prop];
  14187. }
  14188. }
  14189. if (options.tooltip.color) {
  14190. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14191. }
  14192. }
  14193. }
  14194. // (Re)loading the mixins that can be enabled or disabled in the options.
  14195. // load the force calculation functions, grouped under the physics system.
  14196. this._loadPhysicsSystem();
  14197. // load the navigation system.
  14198. this._loadNavigationControls();
  14199. // load the data manipulation system
  14200. this._loadManipulationSystem();
  14201. // configure the smooth curves
  14202. this._configureSmoothCurves();
  14203. // bind keys. If disabled, this will not do anything;
  14204. this._createKeyBinds();
  14205. this.setSize(this.width, this.height);
  14206. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14207. this._setScale(1);
  14208. this._redraw();
  14209. };
  14210. /**
  14211. * Create the main frame for the Graph.
  14212. * This function is executed once when a Graph object is created. The frame
  14213. * contains a canvas, and this canvas contains all objects like the axis and
  14214. * nodes.
  14215. * @private
  14216. */
  14217. Graph.prototype._create = function () {
  14218. // remove all elements from the container element.
  14219. while (this.containerElement.hasChildNodes()) {
  14220. this.containerElement.removeChild(this.containerElement.firstChild);
  14221. }
  14222. this.frame = document.createElement('div');
  14223. this.frame.className = 'graph-frame';
  14224. this.frame.style.position = 'relative';
  14225. this.frame.style.overflow = 'hidden';
  14226. // create the graph canvas (HTML canvas element)
  14227. this.frame.canvas = document.createElement( 'canvas' );
  14228. this.frame.canvas.style.position = 'relative';
  14229. this.frame.appendChild(this.frame.canvas);
  14230. if (!this.frame.canvas.getContext) {
  14231. var noCanvas = document.createElement( 'DIV' );
  14232. noCanvas.style.color = 'red';
  14233. noCanvas.style.fontWeight = 'bold' ;
  14234. noCanvas.style.padding = '10px';
  14235. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14236. this.frame.canvas.appendChild(noCanvas);
  14237. }
  14238. var me = this;
  14239. this.drag = {};
  14240. this.pinch = {};
  14241. this.hammer = Hammer(this.frame.canvas, {
  14242. prevent_default: true
  14243. });
  14244. this.hammer.on('tap', me._onTap.bind(me) );
  14245. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14246. this.hammer.on('hold', me._onHold.bind(me) );
  14247. this.hammer.on('pinch', me._onPinch.bind(me) );
  14248. this.hammer.on('touch', me._onTouch.bind(me) );
  14249. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14250. this.hammer.on('drag', me._onDrag.bind(me) );
  14251. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14252. this.hammer.on('release', me._onRelease.bind(me) );
  14253. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14254. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14255. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14256. // add the frame to the container element
  14257. this.containerElement.appendChild(this.frame);
  14258. };
  14259. /**
  14260. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14261. * @private
  14262. */
  14263. Graph.prototype._createKeyBinds = function() {
  14264. var me = this;
  14265. this.mousetrap = mousetrap;
  14266. this.mousetrap.reset();
  14267. if (this.constants.keyboard.enabled == true) {
  14268. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14269. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14270. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14271. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14272. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14273. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14274. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14275. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14276. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14277. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14278. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14279. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14280. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14281. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14282. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14283. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14284. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14285. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14286. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14287. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14288. }
  14289. if (this.constants.dataManipulation.enabled == true) {
  14290. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14291. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14292. }
  14293. };
  14294. /**
  14295. * Get the pointer location from a touch location
  14296. * @param {{pageX: Number, pageY: Number}} touch
  14297. * @return {{x: Number, y: Number}} pointer
  14298. * @private
  14299. */
  14300. Graph.prototype._getPointer = function (touch) {
  14301. return {
  14302. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14303. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14304. };
  14305. };
  14306. /**
  14307. * On start of a touch gesture, store the pointer
  14308. * @param event
  14309. * @private
  14310. */
  14311. Graph.prototype._onTouch = function (event) {
  14312. this.drag.pointer = this._getPointer(event.gesture.center);
  14313. this.drag.pinched = false;
  14314. this.pinch.scale = this._getScale();
  14315. this._handleTouch(this.drag.pointer);
  14316. };
  14317. /**
  14318. * handle drag start event
  14319. * @private
  14320. */
  14321. Graph.prototype._onDragStart = function () {
  14322. this._handleDragStart();
  14323. };
  14324. /**
  14325. * This function is called by _onDragStart.
  14326. * It is separated out because we can then overload it for the datamanipulation system.
  14327. *
  14328. * @private
  14329. */
  14330. Graph.prototype._handleDragStart = function() {
  14331. var drag = this.drag;
  14332. var node = this._getNodeAt(drag.pointer);
  14333. // note: drag.pointer is set in _onTouch to get the initial touch location
  14334. drag.dragging = true;
  14335. drag.selection = [];
  14336. drag.translation = this._getTranslation();
  14337. drag.nodeId = null;
  14338. if (node != null) {
  14339. drag.nodeId = node.id;
  14340. // select the clicked node if not yet selected
  14341. if (!node.isSelected()) {
  14342. this._selectObject(node,false);
  14343. }
  14344. // create an array with the selected nodes and their original location and status
  14345. for (var objectId in this.selectionObj.nodes) {
  14346. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14347. var object = this.selectionObj.nodes[objectId];
  14348. var s = {
  14349. id: object.id,
  14350. node: object,
  14351. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14352. x: object.x,
  14353. y: object.y,
  14354. xFixed: object.xFixed,
  14355. yFixed: object.yFixed
  14356. };
  14357. object.xFixed = true;
  14358. object.yFixed = true;
  14359. drag.selection.push(s);
  14360. }
  14361. }
  14362. }
  14363. };
  14364. /**
  14365. * handle drag event
  14366. * @private
  14367. */
  14368. Graph.prototype._onDrag = function (event) {
  14369. this._handleOnDrag(event)
  14370. };
  14371. /**
  14372. * This function is called by _onDrag.
  14373. * It is separated out because we can then overload it for the datamanipulation system.
  14374. *
  14375. * @private
  14376. */
  14377. Graph.prototype._handleOnDrag = function(event) {
  14378. if (this.drag.pinched) {
  14379. return;
  14380. }
  14381. var pointer = this._getPointer(event.gesture.center);
  14382. var me = this,
  14383. drag = this.drag,
  14384. selection = drag.selection;
  14385. if (selection && selection.length) {
  14386. // calculate delta's and new location
  14387. var deltaX = pointer.x - drag.pointer.x,
  14388. deltaY = pointer.y - drag.pointer.y;
  14389. // update position of all selected nodes
  14390. selection.forEach(function (s) {
  14391. var node = s.node;
  14392. if (!s.xFixed) {
  14393. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14394. }
  14395. if (!s.yFixed) {
  14396. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14397. }
  14398. });
  14399. // start _animationStep if not yet running
  14400. if (!this.moving) {
  14401. this.moving = true;
  14402. this.start();
  14403. }
  14404. }
  14405. else {
  14406. // move the graph
  14407. var diffX = pointer.x - this.drag.pointer.x;
  14408. var diffY = pointer.y - this.drag.pointer.y;
  14409. this._setTranslation(
  14410. this.drag.translation.x + diffX,
  14411. this.drag.translation.y + diffY);
  14412. this._redraw();
  14413. this.moved = true;
  14414. }
  14415. };
  14416. /**
  14417. * handle drag start event
  14418. * @private
  14419. */
  14420. Graph.prototype._onDragEnd = function () {
  14421. this.drag.dragging = false;
  14422. var selection = this.drag.selection;
  14423. if (selection) {
  14424. selection.forEach(function (s) {
  14425. // restore original xFixed and yFixed
  14426. s.node.xFixed = s.xFixed;
  14427. s.node.yFixed = s.yFixed;
  14428. });
  14429. }
  14430. };
  14431. /**
  14432. * handle tap/click event: select/unselect a node
  14433. * @private
  14434. */
  14435. Graph.prototype._onTap = function (event) {
  14436. var pointer = this._getPointer(event.gesture.center);
  14437. this.pointerPosition = pointer;
  14438. this._handleTap(pointer);
  14439. };
  14440. /**
  14441. * handle doubletap event
  14442. * @private
  14443. */
  14444. Graph.prototype._onDoubleTap = function (event) {
  14445. var pointer = this._getPointer(event.gesture.center);
  14446. this._handleDoubleTap(pointer);
  14447. };
  14448. /**
  14449. * handle long tap event: multi select nodes
  14450. * @private
  14451. */
  14452. Graph.prototype._onHold = function (event) {
  14453. var pointer = this._getPointer(event.gesture.center);
  14454. this.pointerPosition = pointer;
  14455. this._handleOnHold(pointer);
  14456. };
  14457. /**
  14458. * handle the release of the screen
  14459. *
  14460. * @private
  14461. */
  14462. Graph.prototype._onRelease = function (event) {
  14463. var pointer = this._getPointer(event.gesture.center);
  14464. this._handleOnRelease(pointer);
  14465. };
  14466. /**
  14467. * Handle pinch event
  14468. * @param event
  14469. * @private
  14470. */
  14471. Graph.prototype._onPinch = function (event) {
  14472. var pointer = this._getPointer(event.gesture.center);
  14473. this.drag.pinched = true;
  14474. if (!('scale' in this.pinch)) {
  14475. this.pinch.scale = 1;
  14476. }
  14477. // TODO: enabled moving while pinching?
  14478. var scale = this.pinch.scale * event.gesture.scale;
  14479. this._zoom(scale, pointer)
  14480. };
  14481. /**
  14482. * Zoom the graph in or out
  14483. * @param {Number} scale a number around 1, and between 0.01 and 10
  14484. * @param {{x: Number, y: Number}} pointer Position on screen
  14485. * @return {Number} appliedScale scale is limited within the boundaries
  14486. * @private
  14487. */
  14488. Graph.prototype._zoom = function(scale, pointer) {
  14489. var scaleOld = this._getScale();
  14490. if (scale < 0.00001) {
  14491. scale = 0.00001;
  14492. }
  14493. if (scale > 10) {
  14494. scale = 10;
  14495. }
  14496. // + this.frame.canvas.clientHeight / 2
  14497. var translation = this._getTranslation();
  14498. var scaleFrac = scale / scaleOld;
  14499. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14500. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14501. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14502. "y" : this._canvasToY(pointer.y)};
  14503. this._setScale(scale);
  14504. this._setTranslation(tx, ty);
  14505. this.updateClustersDefault();
  14506. this._redraw();
  14507. return scale;
  14508. };
  14509. /**
  14510. * Event handler for mouse wheel event, used to zoom the timeline
  14511. * See http://adomas.org/javascript-mouse-wheel/
  14512. * https://github.com/EightMedia/hammer.js/issues/256
  14513. * @param {MouseEvent} event
  14514. * @private
  14515. */
  14516. Graph.prototype._onMouseWheel = function(event) {
  14517. // retrieve delta
  14518. var delta = 0;
  14519. if (event.wheelDelta) { /* IE/Opera. */
  14520. delta = event.wheelDelta/120;
  14521. } else if (event.detail) { /* Mozilla case. */
  14522. // In Mozilla, sign of delta is different than in IE.
  14523. // Also, delta is multiple of 3.
  14524. delta = -event.detail/3;
  14525. }
  14526. // If delta is nonzero, handle it.
  14527. // Basically, delta is now positive if wheel was scrolled up,
  14528. // and negative, if wheel was scrolled down.
  14529. if (delta) {
  14530. // calculate the new scale
  14531. var scale = this._getScale();
  14532. var zoom = delta / 10;
  14533. if (delta < 0) {
  14534. zoom = zoom / (1 - zoom);
  14535. }
  14536. scale *= (1 + zoom);
  14537. // calculate the pointer location
  14538. var gesture = util.fakeGesture(this, event);
  14539. var pointer = this._getPointer(gesture.center);
  14540. // apply the new scale
  14541. this._zoom(scale, pointer);
  14542. }
  14543. // Prevent default actions caused by mouse wheel.
  14544. event.preventDefault();
  14545. };
  14546. /**
  14547. * Mouse move handler for checking whether the title moves over a node with a title.
  14548. * @param {Event} event
  14549. * @private
  14550. */
  14551. Graph.prototype._onMouseMoveTitle = function (event) {
  14552. var gesture = util.fakeGesture(this, event);
  14553. var pointer = this._getPointer(gesture.center);
  14554. // check if the previously selected node is still selected
  14555. if (this.popupNode) {
  14556. this._checkHidePopup(pointer);
  14557. }
  14558. // start a timeout that will check if the mouse is positioned above
  14559. // an element
  14560. var me = this;
  14561. var checkShow = function() {
  14562. me._checkShowPopup(pointer);
  14563. };
  14564. if (this.popupTimer) {
  14565. clearInterval(this.popupTimer); // stop any running calculationTimer
  14566. }
  14567. if (!this.drag.dragging) {
  14568. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14569. }
  14570. };
  14571. /**
  14572. * Check if there is an element on the given position in the graph
  14573. * (a node or edge). If so, and if this element has a title,
  14574. * show a popup window with its title.
  14575. *
  14576. * @param {{x:Number, y:Number}} pointer
  14577. * @private
  14578. */
  14579. Graph.prototype._checkShowPopup = function (pointer) {
  14580. var obj = {
  14581. left: this._canvasToX(pointer.x),
  14582. top: this._canvasToY(pointer.y),
  14583. right: this._canvasToX(pointer.x),
  14584. bottom: this._canvasToY(pointer.y)
  14585. };
  14586. var id;
  14587. var lastPopupNode = this.popupNode;
  14588. if (this.popupNode == undefined) {
  14589. // search the nodes for overlap, select the top one in case of multiple nodes
  14590. var nodes = this.nodes;
  14591. for (id in nodes) {
  14592. if (nodes.hasOwnProperty(id)) {
  14593. var node = nodes[id];
  14594. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14595. this.popupNode = node;
  14596. break;
  14597. }
  14598. }
  14599. }
  14600. }
  14601. if (this.popupNode === undefined) {
  14602. // search the edges for overlap
  14603. var edges = this.edges;
  14604. for (id in edges) {
  14605. if (edges.hasOwnProperty(id)) {
  14606. var edge = edges[id];
  14607. if (edge.connected && (edge.getTitle() !== undefined) &&
  14608. edge.isOverlappingWith(obj)) {
  14609. this.popupNode = edge;
  14610. break;
  14611. }
  14612. }
  14613. }
  14614. }
  14615. if (this.popupNode) {
  14616. // show popup message window
  14617. if (this.popupNode != lastPopupNode) {
  14618. var me = this;
  14619. if (!me.popup) {
  14620. me.popup = new Popup(me.frame, me.constants.tooltip);
  14621. }
  14622. // adjust a small offset such that the mouse cursor is located in the
  14623. // bottom left location of the popup, and you can easily move over the
  14624. // popup area
  14625. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14626. me.popup.setText(me.popupNode.getTitle());
  14627. me.popup.show();
  14628. }
  14629. }
  14630. else {
  14631. if (this.popup) {
  14632. this.popup.hide();
  14633. }
  14634. }
  14635. };
  14636. /**
  14637. * Check if the popup must be hided, which is the case when the mouse is no
  14638. * longer hovering on the object
  14639. * @param {{x:Number, y:Number}} pointer
  14640. * @private
  14641. */
  14642. Graph.prototype._checkHidePopup = function (pointer) {
  14643. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14644. this.popupNode = undefined;
  14645. if (this.popup) {
  14646. this.popup.hide();
  14647. }
  14648. }
  14649. };
  14650. /**
  14651. * Set a new size for the graph
  14652. * @param {string} width Width in pixels or percentage (for example '800px'
  14653. * or '50%')
  14654. * @param {string} height Height in pixels or percentage (for example '400px'
  14655. * or '30%')
  14656. */
  14657. Graph.prototype.setSize = function(width, height) {
  14658. this.frame.style.width = width;
  14659. this.frame.style.height = height;
  14660. this.frame.canvas.style.width = '100%';
  14661. this.frame.canvas.style.height = '100%';
  14662. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14663. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14664. if (this.manipulationDiv !== undefined) {
  14665. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14666. }
  14667. if (this.navigationDivs !== undefined) {
  14668. if (this.navigationDivs['wrapper'] !== undefined) {
  14669. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14670. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14671. }
  14672. }
  14673. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14674. };
  14675. /**
  14676. * Set a data set with nodes for the graph
  14677. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14678. * @private
  14679. */
  14680. Graph.prototype._setNodes = function(nodes) {
  14681. var oldNodesData = this.nodesData;
  14682. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14683. this.nodesData = nodes;
  14684. }
  14685. else if (nodes instanceof Array) {
  14686. this.nodesData = new DataSet();
  14687. this.nodesData.add(nodes);
  14688. }
  14689. else if (!nodes) {
  14690. this.nodesData = new DataSet();
  14691. }
  14692. else {
  14693. throw new TypeError('Array or DataSet expected');
  14694. }
  14695. if (oldNodesData) {
  14696. // unsubscribe from old dataset
  14697. util.forEach(this.nodesListeners, function (callback, event) {
  14698. oldNodesData.off(event, callback);
  14699. });
  14700. }
  14701. // remove drawn nodes
  14702. this.nodes = {};
  14703. if (this.nodesData) {
  14704. // subscribe to new dataset
  14705. var me = this;
  14706. util.forEach(this.nodesListeners, function (callback, event) {
  14707. me.nodesData.on(event, callback);
  14708. });
  14709. // draw all new nodes
  14710. var ids = this.nodesData.getIds();
  14711. this._addNodes(ids);
  14712. }
  14713. this._updateSelection();
  14714. };
  14715. /**
  14716. * Add nodes
  14717. * @param {Number[] | String[]} ids
  14718. * @private
  14719. */
  14720. Graph.prototype._addNodes = function(ids) {
  14721. var id;
  14722. for (var i = 0, len = ids.length; i < len; i++) {
  14723. id = ids[i];
  14724. var data = this.nodesData.get(id);
  14725. var node = new Node(data, this.images, this.groups, this.constants);
  14726. this.nodes[id] = node; // note: this may replace an existing node
  14727. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14728. var radius = 10 * 0.1*ids.length;
  14729. var angle = 2 * Math.PI * Math.random();
  14730. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14731. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14732. }
  14733. this.moving = true;
  14734. }
  14735. this._updateNodeIndexList();
  14736. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14737. this._resetLevels();
  14738. this._setupHierarchicalLayout();
  14739. }
  14740. this._updateCalculationNodes();
  14741. this._reconnectEdges();
  14742. this._updateValueRange(this.nodes);
  14743. this.updateLabels();
  14744. };
  14745. /**
  14746. * Update existing nodes, or create them when not yet existing
  14747. * @param {Number[] | String[]} ids
  14748. * @private
  14749. */
  14750. Graph.prototype._updateNodes = function(ids) {
  14751. var nodes = this.nodes,
  14752. nodesData = this.nodesData;
  14753. for (var i = 0, len = ids.length; i < len; i++) {
  14754. var id = ids[i];
  14755. var node = nodes[id];
  14756. var data = nodesData.get(id);
  14757. if (node) {
  14758. // update node
  14759. node.setProperties(data, this.constants);
  14760. }
  14761. else {
  14762. // create node
  14763. node = new Node(properties, this.images, this.groups, this.constants);
  14764. nodes[id] = node;
  14765. }
  14766. }
  14767. this.moving = true;
  14768. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14769. this._resetLevels();
  14770. this._setupHierarchicalLayout();
  14771. }
  14772. this._updateNodeIndexList();
  14773. this._reconnectEdges();
  14774. this._updateValueRange(nodes);
  14775. };
  14776. /**
  14777. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14778. * @param {Number[] | String[]} ids
  14779. * @private
  14780. */
  14781. Graph.prototype._removeNodes = function(ids) {
  14782. var nodes = this.nodes;
  14783. for (var i = 0, len = ids.length; i < len; i++) {
  14784. var id = ids[i];
  14785. delete nodes[id];
  14786. }
  14787. this._updateNodeIndexList();
  14788. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14789. this._resetLevels();
  14790. this._setupHierarchicalLayout();
  14791. }
  14792. this._updateCalculationNodes();
  14793. this._reconnectEdges();
  14794. this._updateSelection();
  14795. this._updateValueRange(nodes);
  14796. };
  14797. /**
  14798. * Load edges by reading the data table
  14799. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14800. * @private
  14801. * @private
  14802. */
  14803. Graph.prototype._setEdges = function(edges) {
  14804. var oldEdgesData = this.edgesData;
  14805. if (edges instanceof DataSet || edges instanceof DataView) {
  14806. this.edgesData = edges;
  14807. }
  14808. else if (edges instanceof Array) {
  14809. this.edgesData = new DataSet();
  14810. this.edgesData.add(edges);
  14811. }
  14812. else if (!edges) {
  14813. this.edgesData = new DataSet();
  14814. }
  14815. else {
  14816. throw new TypeError('Array or DataSet expected');
  14817. }
  14818. if (oldEdgesData) {
  14819. // unsubscribe from old dataset
  14820. util.forEach(this.edgesListeners, function (callback, event) {
  14821. oldEdgesData.off(event, callback);
  14822. });
  14823. }
  14824. // remove drawn edges
  14825. this.edges = {};
  14826. if (this.edgesData) {
  14827. // subscribe to new dataset
  14828. var me = this;
  14829. util.forEach(this.edgesListeners, function (callback, event) {
  14830. me.edgesData.on(event, callback);
  14831. });
  14832. // draw all new nodes
  14833. var ids = this.edgesData.getIds();
  14834. this._addEdges(ids);
  14835. }
  14836. this._reconnectEdges();
  14837. };
  14838. /**
  14839. * Add edges
  14840. * @param {Number[] | String[]} ids
  14841. * @private
  14842. */
  14843. Graph.prototype._addEdges = function (ids) {
  14844. var edges = this.edges,
  14845. edgesData = this.edgesData;
  14846. for (var i = 0, len = ids.length; i < len; i++) {
  14847. var id = ids[i];
  14848. var oldEdge = edges[id];
  14849. if (oldEdge) {
  14850. oldEdge.disconnect();
  14851. }
  14852. var data = edgesData.get(id, {"showInternalIds" : true});
  14853. edges[id] = new Edge(data, this, this.constants);
  14854. }
  14855. this.moving = true;
  14856. this._updateValueRange(edges);
  14857. this._createBezierNodes();
  14858. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14859. this._resetLevels();
  14860. this._setupHierarchicalLayout();
  14861. }
  14862. this._updateCalculationNodes();
  14863. };
  14864. /**
  14865. * Update existing edges, or create them when not yet existing
  14866. * @param {Number[] | String[]} ids
  14867. * @private
  14868. */
  14869. Graph.prototype._updateEdges = function (ids) {
  14870. var edges = this.edges,
  14871. edgesData = this.edgesData;
  14872. for (var i = 0, len = ids.length; i < len; i++) {
  14873. var id = ids[i];
  14874. var data = edgesData.get(id);
  14875. var edge = edges[id];
  14876. if (edge) {
  14877. // update edge
  14878. edge.disconnect();
  14879. edge.setProperties(data, this.constants);
  14880. edge.connect();
  14881. }
  14882. else {
  14883. // create edge
  14884. edge = new Edge(data, this, this.constants);
  14885. this.edges[id] = edge;
  14886. }
  14887. }
  14888. this._createBezierNodes();
  14889. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14890. this._resetLevels();
  14891. this._setupHierarchicalLayout();
  14892. }
  14893. this.moving = true;
  14894. this._updateValueRange(edges);
  14895. };
  14896. /**
  14897. * Remove existing edges. Non existing ids will be ignored
  14898. * @param {Number[] | String[]} ids
  14899. * @private
  14900. */
  14901. Graph.prototype._removeEdges = function (ids) {
  14902. var edges = this.edges;
  14903. for (var i = 0, len = ids.length; i < len; i++) {
  14904. var id = ids[i];
  14905. var edge = edges[id];
  14906. if (edge) {
  14907. if (edge.via != null) {
  14908. delete this.sectors['support']['nodes'][edge.via.id];
  14909. }
  14910. edge.disconnect();
  14911. delete edges[id];
  14912. }
  14913. }
  14914. this.moving = true;
  14915. this._updateValueRange(edges);
  14916. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14917. this._resetLevels();
  14918. this._setupHierarchicalLayout();
  14919. }
  14920. this._updateCalculationNodes();
  14921. };
  14922. /**
  14923. * Reconnect all edges
  14924. * @private
  14925. */
  14926. Graph.prototype._reconnectEdges = function() {
  14927. var id,
  14928. nodes = this.nodes,
  14929. edges = this.edges;
  14930. for (id in nodes) {
  14931. if (nodes.hasOwnProperty(id)) {
  14932. nodes[id].edges = [];
  14933. }
  14934. }
  14935. for (id in edges) {
  14936. if (edges.hasOwnProperty(id)) {
  14937. var edge = edges[id];
  14938. edge.from = null;
  14939. edge.to = null;
  14940. edge.connect();
  14941. }
  14942. }
  14943. };
  14944. /**
  14945. * Update the values of all object in the given array according to the current
  14946. * value range of the objects in the array.
  14947. * @param {Object} obj An object containing a set of Edges or Nodes
  14948. * The objects must have a method getValue() and
  14949. * setValueRange(min, max).
  14950. * @private
  14951. */
  14952. Graph.prototype._updateValueRange = function(obj) {
  14953. var id;
  14954. // determine the range of the objects
  14955. var valueMin = undefined;
  14956. var valueMax = undefined;
  14957. for (id in obj) {
  14958. if (obj.hasOwnProperty(id)) {
  14959. var value = obj[id].getValue();
  14960. if (value !== undefined) {
  14961. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14962. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14963. }
  14964. }
  14965. }
  14966. // adjust the range of all objects
  14967. if (valueMin !== undefined && valueMax !== undefined) {
  14968. for (id in obj) {
  14969. if (obj.hasOwnProperty(id)) {
  14970. obj[id].setValueRange(valueMin, valueMax);
  14971. }
  14972. }
  14973. }
  14974. };
  14975. /**
  14976. * Redraw the graph with the current data
  14977. * chart will be resized too.
  14978. */
  14979. Graph.prototype.redraw = function() {
  14980. this.setSize(this.width, this.height);
  14981. this._redraw();
  14982. };
  14983. /**
  14984. * Redraw the graph with the current data
  14985. * @private
  14986. */
  14987. Graph.prototype._redraw = function() {
  14988. var ctx = this.frame.canvas.getContext('2d');
  14989. // clear the canvas
  14990. var w = this.frame.canvas.width;
  14991. var h = this.frame.canvas.height;
  14992. ctx.clearRect(0, 0, w, h);
  14993. // set scaling and translation
  14994. ctx.save();
  14995. ctx.translate(this.translation.x, this.translation.y);
  14996. ctx.scale(this.scale, this.scale);
  14997. this.canvasTopLeft = {
  14998. "x": this._canvasToX(0),
  14999. "y": this._canvasToY(0)
  15000. };
  15001. this.canvasBottomRight = {
  15002. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15003. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15004. };
  15005. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15006. this._doInAllSectors("_drawEdges",ctx);
  15007. this._doInAllSectors("_drawNodes",ctx,false);
  15008. // this._doInSupportSector("_drawNodes",ctx,true);
  15009. // this._drawTree(ctx,"#F00F0F");
  15010. // restore original scaling and translation
  15011. ctx.restore();
  15012. };
  15013. /**
  15014. * Set the translation of the graph
  15015. * @param {Number} offsetX Horizontal offset
  15016. * @param {Number} offsetY Vertical offset
  15017. * @private
  15018. */
  15019. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15020. if (this.translation === undefined) {
  15021. this.translation = {
  15022. x: 0,
  15023. y: 0
  15024. };
  15025. }
  15026. if (offsetX !== undefined) {
  15027. this.translation.x = offsetX;
  15028. }
  15029. if (offsetY !== undefined) {
  15030. this.translation.y = offsetY;
  15031. }
  15032. };
  15033. /**
  15034. * Get the translation of the graph
  15035. * @return {Object} translation An object with parameters x and y, both a number
  15036. * @private
  15037. */
  15038. Graph.prototype._getTranslation = function() {
  15039. return {
  15040. x: this.translation.x,
  15041. y: this.translation.y
  15042. };
  15043. };
  15044. /**
  15045. * Scale the graph
  15046. * @param {Number} scale Scaling factor 1.0 is unscaled
  15047. * @private
  15048. */
  15049. Graph.prototype._setScale = function(scale) {
  15050. this.scale = scale;
  15051. };
  15052. /**
  15053. * Get the current scale of the graph
  15054. * @return {Number} scale Scaling factor 1.0 is unscaled
  15055. * @private
  15056. */
  15057. Graph.prototype._getScale = function() {
  15058. return this.scale;
  15059. };
  15060. /**
  15061. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15062. * @param {number} x
  15063. * @returns {number}
  15064. * @private
  15065. */
  15066. Graph.prototype._canvasToX = function(x) {
  15067. return (x - this.translation.x) / this.scale;
  15068. };
  15069. /**
  15070. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15071. * @param {number} x
  15072. * @returns {number}
  15073. * @private
  15074. */
  15075. Graph.prototype._xToCanvas = function(x) {
  15076. return x * this.scale + this.translation.x;
  15077. };
  15078. /**
  15079. * Convert a vertical point on the HTML canvas to the y-value of the model
  15080. * @param {number} y
  15081. * @returns {number}
  15082. * @private
  15083. */
  15084. Graph.prototype._canvasToY = function(y) {
  15085. return (y - this.translation.y) / this.scale;
  15086. };
  15087. /**
  15088. * Convert an y-value in the model to a vertical point on the HTML canvas
  15089. * @param {number} y
  15090. * @returns {number}
  15091. * @private
  15092. */
  15093. Graph.prototype._yToCanvas = function(y) {
  15094. return y * this.scale + this.translation.y ;
  15095. };
  15096. /**
  15097. * Redraw all nodes
  15098. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15099. * @param {CanvasRenderingContext2D} ctx
  15100. * @param {Boolean} [alwaysShow]
  15101. * @private
  15102. */
  15103. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15104. if (alwaysShow === undefined) {
  15105. alwaysShow = false;
  15106. }
  15107. // first draw the unselected nodes
  15108. var nodes = this.nodes;
  15109. var selected = [];
  15110. for (var id in nodes) {
  15111. if (nodes.hasOwnProperty(id)) {
  15112. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15113. if (nodes[id].isSelected()) {
  15114. selected.push(id);
  15115. }
  15116. else {
  15117. if (nodes[id].inArea() || alwaysShow) {
  15118. nodes[id].draw(ctx);
  15119. }
  15120. }
  15121. }
  15122. }
  15123. // draw the selected nodes on top
  15124. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15125. if (nodes[selected[s]].inArea() || alwaysShow) {
  15126. nodes[selected[s]].draw(ctx);
  15127. }
  15128. }
  15129. };
  15130. /**
  15131. * Redraw all edges
  15132. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15133. * @param {CanvasRenderingContext2D} ctx
  15134. * @private
  15135. */
  15136. Graph.prototype._drawEdges = function(ctx) {
  15137. var edges = this.edges;
  15138. for (var id in edges) {
  15139. if (edges.hasOwnProperty(id)) {
  15140. var edge = edges[id];
  15141. edge.setScale(this.scale);
  15142. if (edge.connected) {
  15143. edges[id].draw(ctx);
  15144. }
  15145. }
  15146. }
  15147. };
  15148. /**
  15149. * Find a stable position for all nodes
  15150. * @private
  15151. */
  15152. Graph.prototype._stabilize = function() {
  15153. if (this.constants.freezeForStabilization == true) {
  15154. this._freezeDefinedNodes();
  15155. }
  15156. // find stable position
  15157. var count = 0;
  15158. while (this.moving && count < this.constants.stabilizationIterations) {
  15159. this._physicsTick();
  15160. count++;
  15161. }
  15162. this.zoomExtent(false,true);
  15163. if (this.constants.freezeForStabilization == true) {
  15164. this._restoreFrozenNodes();
  15165. }
  15166. this.emit("stabilized",{iterations:count});
  15167. };
  15168. Graph.prototype._freezeDefinedNodes = function() {
  15169. var nodes = this.nodes;
  15170. for (var id in nodes) {
  15171. if (nodes.hasOwnProperty(id)) {
  15172. if (nodes[id].x != null && nodes[id].y != null) {
  15173. nodes[id].fixedData.x = nodes[id].xFixed;
  15174. nodes[id].fixedData.y = nodes[id].yFixed;
  15175. nodes[id].xFixed = true;
  15176. nodes[id].yFixed = true;
  15177. }
  15178. }
  15179. }
  15180. };
  15181. Graph.prototype._restoreFrozenNodes = function() {
  15182. var nodes = this.nodes;
  15183. for (var id in nodes) {
  15184. if (nodes.hasOwnProperty(id)) {
  15185. if (nodes[id].fixedData.x != null) {
  15186. nodes[id].xFixed = nodes[id].fixedData.x;
  15187. nodes[id].yFixed = nodes[id].fixedData.y;
  15188. }
  15189. }
  15190. }
  15191. };
  15192. /**
  15193. * Check if any of the nodes is still moving
  15194. * @param {number} vmin the minimum velocity considered as 'moving'
  15195. * @return {boolean} true if moving, false if non of the nodes is moving
  15196. * @private
  15197. */
  15198. Graph.prototype._isMoving = function(vmin) {
  15199. var nodes = this.nodes;
  15200. for (var id in nodes) {
  15201. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15202. return true;
  15203. }
  15204. }
  15205. return false;
  15206. };
  15207. /**
  15208. * /**
  15209. * Perform one discrete step for all nodes
  15210. *
  15211. * @private
  15212. */
  15213. Graph.prototype._discreteStepNodes = function() {
  15214. var interval = this.physicsDiscreteStepsize;
  15215. var nodes = this.nodes;
  15216. var nodeId;
  15217. var nodesPresent = false;
  15218. if (this.constants.maxVelocity > 0) {
  15219. for (nodeId in nodes) {
  15220. if (nodes.hasOwnProperty(nodeId)) {
  15221. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15222. nodesPresent = true;
  15223. }
  15224. }
  15225. }
  15226. else {
  15227. for (nodeId in nodes) {
  15228. if (nodes.hasOwnProperty(nodeId)) {
  15229. nodes[nodeId].discreteStep(interval);
  15230. nodesPresent = true;
  15231. }
  15232. }
  15233. }
  15234. if (nodesPresent == true) {
  15235. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15236. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15237. this.moving = true;
  15238. }
  15239. else {
  15240. this.moving = this._isMoving(vminCorrected);
  15241. }
  15242. }
  15243. };
  15244. Graph.prototype._physicsTick = function() {
  15245. if (!this.freezeSimulation) {
  15246. if (this.moving) {
  15247. this._doInAllActiveSectors("_initializeForceCalculation");
  15248. this._doInAllActiveSectors("_discreteStepNodes");
  15249. if (this.constants.smoothCurves) {
  15250. this._doInSupportSector("_discreteStepNodes");
  15251. }
  15252. this._findCenter(this._getRange())
  15253. }
  15254. }
  15255. };
  15256. /**
  15257. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15258. * It reschedules itself at the beginning of the function
  15259. *
  15260. * @private
  15261. */
  15262. Graph.prototype._animationStep = function() {
  15263. // reset the timer so a new scheduled animation step can be set
  15264. this.timer = undefined;
  15265. // handle the keyboad movement
  15266. this._handleNavigation();
  15267. // this schedules a new animation step
  15268. this.start();
  15269. // start the physics simulation
  15270. var calculationTime = Date.now();
  15271. var maxSteps = 1;
  15272. this._physicsTick();
  15273. var timeRequired = Date.now() - calculationTime;
  15274. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15275. this._physicsTick();
  15276. timeRequired = Date.now() - calculationTime;
  15277. maxSteps++;
  15278. }
  15279. // start the rendering process
  15280. var renderTime = Date.now();
  15281. this._redraw();
  15282. this.renderTime = Date.now() - renderTime;
  15283. };
  15284. if (typeof window !== 'undefined') {
  15285. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15286. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15287. }
  15288. /**
  15289. * Schedule a animation step with the refreshrate interval.
  15290. */
  15291. Graph.prototype.start = function() {
  15292. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15293. if (!this.timer) {
  15294. var ua = navigator.userAgent.toLowerCase();
  15295. var requiresTimeout = false;
  15296. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15297. requiresTimeout = true;
  15298. }
  15299. else if (ua.indexOf('safari') != -1) { // safari
  15300. if (ua.indexOf('chrome') <= -1) {
  15301. requiresTimeout = true;
  15302. }
  15303. }
  15304. if (requiresTimeout == true) {
  15305. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15306. }
  15307. else{
  15308. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15309. }
  15310. }
  15311. }
  15312. else {
  15313. this._redraw();
  15314. }
  15315. };
  15316. /**
  15317. * Move the graph according to the keyboard presses.
  15318. *
  15319. * @private
  15320. */
  15321. Graph.prototype._handleNavigation = function() {
  15322. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15323. var translation = this._getTranslation();
  15324. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15325. }
  15326. if (this.zoomIncrement != 0) {
  15327. var center = {
  15328. x: this.frame.canvas.clientWidth / 2,
  15329. y: this.frame.canvas.clientHeight / 2
  15330. };
  15331. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15332. }
  15333. };
  15334. /**
  15335. * Freeze the _animationStep
  15336. */
  15337. Graph.prototype.toggleFreeze = function() {
  15338. if (this.freezeSimulation == false) {
  15339. this.freezeSimulation = true;
  15340. }
  15341. else {
  15342. this.freezeSimulation = false;
  15343. this.start();
  15344. }
  15345. };
  15346. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15347. if (disableStart === undefined) {
  15348. disableStart = true;
  15349. }
  15350. if (this.constants.smoothCurves == true) {
  15351. this._createBezierNodes();
  15352. }
  15353. else {
  15354. // delete the support nodes
  15355. this.sectors['support']['nodes'] = {};
  15356. for (var edgeId in this.edges) {
  15357. if (this.edges.hasOwnProperty(edgeId)) {
  15358. this.edges[edgeId].smooth = false;
  15359. this.edges[edgeId].via = null;
  15360. }
  15361. }
  15362. }
  15363. this._updateCalculationNodes();
  15364. if (!disableStart) {
  15365. this.moving = true;
  15366. this.start();
  15367. }
  15368. };
  15369. Graph.prototype._createBezierNodes = function() {
  15370. if (this.constants.smoothCurves == true) {
  15371. for (var edgeId in this.edges) {
  15372. if (this.edges.hasOwnProperty(edgeId)) {
  15373. var edge = this.edges[edgeId];
  15374. if (edge.via == null) {
  15375. edge.smooth = true;
  15376. var nodeId = "edgeId:".concat(edge.id);
  15377. this.sectors['support']['nodes'][nodeId] = new Node(
  15378. {id:nodeId,
  15379. mass:1,
  15380. shape:'circle',
  15381. image:"",
  15382. internalMultiplier:1
  15383. },{},{},this.constants);
  15384. edge.via = this.sectors['support']['nodes'][nodeId];
  15385. edge.via.parentEdgeId = edge.id;
  15386. edge.positionBezierNode();
  15387. }
  15388. }
  15389. }
  15390. }
  15391. };
  15392. Graph.prototype._initializeMixinLoaders = function () {
  15393. for (var mixinFunction in graphMixinLoaders) {
  15394. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15395. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15396. }
  15397. }
  15398. };
  15399. /**
  15400. * Load the XY positions of the nodes into the dataset.
  15401. */
  15402. Graph.prototype.storePosition = function() {
  15403. var dataArray = [];
  15404. for (var nodeId in this.nodes) {
  15405. if (this.nodes.hasOwnProperty(nodeId)) {
  15406. var node = this.nodes[nodeId];
  15407. var allowedToMoveX = !this.nodes.xFixed;
  15408. var allowedToMoveY = !this.nodes.yFixed;
  15409. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15410. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15411. }
  15412. }
  15413. }
  15414. this.nodesData.update(dataArray);
  15415. };
  15416. /**
  15417. * vis.js module exports
  15418. */
  15419. var vis = {
  15420. util: util,
  15421. DataSet: DataSet,
  15422. DataView: DataView,
  15423. Range: Range,
  15424. Stack: Stack,
  15425. TimeStep: TimeStep,
  15426. components: {
  15427. items: {
  15428. Item: Item,
  15429. ItemBox: ItemBox,
  15430. ItemPoint: ItemPoint,
  15431. ItemRange: ItemRange
  15432. },
  15433. Component: Component,
  15434. Panel: Panel,
  15435. RootPanel: RootPanel,
  15436. ItemSet: ItemSet,
  15437. TimeAxis: TimeAxis
  15438. },
  15439. graph: {
  15440. Node: Node,
  15441. Edge: Edge,
  15442. Popup: Popup,
  15443. Groups: Groups,
  15444. Images: Images
  15445. },
  15446. Timeline: Timeline,
  15447. Graph: Graph
  15448. };
  15449. /**
  15450. * CommonJS module exports
  15451. */
  15452. if (typeof exports !== 'undefined') {
  15453. exports = vis;
  15454. }
  15455. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15456. module.exports = vis;
  15457. }
  15458. /**
  15459. * AMD module exports
  15460. */
  15461. if (typeof(define) === 'function') {
  15462. define(function () {
  15463. return vis;
  15464. });
  15465. }
  15466. /**
  15467. * Window exports
  15468. */
  15469. if (typeof window !== 'undefined') {
  15470. // attach the module to the window, load as a regular javascript file
  15471. window['vis'] = vis;
  15472. }
  15473. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15474. /**
  15475. * Expose `Emitter`.
  15476. */
  15477. module.exports = Emitter;
  15478. /**
  15479. * Initialize a new `Emitter`.
  15480. *
  15481. * @api public
  15482. */
  15483. function Emitter(obj) {
  15484. if (obj) return mixin(obj);
  15485. };
  15486. /**
  15487. * Mixin the emitter properties.
  15488. *
  15489. * @param {Object} obj
  15490. * @return {Object}
  15491. * @api private
  15492. */
  15493. function mixin(obj) {
  15494. for (var key in Emitter.prototype) {
  15495. obj[key] = Emitter.prototype[key];
  15496. }
  15497. return obj;
  15498. }
  15499. /**
  15500. * Listen on the given `event` with `fn`.
  15501. *
  15502. * @param {String} event
  15503. * @param {Function} fn
  15504. * @return {Emitter}
  15505. * @api public
  15506. */
  15507. Emitter.prototype.on =
  15508. Emitter.prototype.addEventListener = function(event, fn){
  15509. this._callbacks = this._callbacks || {};
  15510. (this._callbacks[event] = this._callbacks[event] || [])
  15511. .push(fn);
  15512. return this;
  15513. };
  15514. /**
  15515. * Adds an `event` listener that will be invoked a single
  15516. * time then automatically removed.
  15517. *
  15518. * @param {String} event
  15519. * @param {Function} fn
  15520. * @return {Emitter}
  15521. * @api public
  15522. */
  15523. Emitter.prototype.once = function(event, fn){
  15524. var self = this;
  15525. this._callbacks = this._callbacks || {};
  15526. function on() {
  15527. self.off(event, on);
  15528. fn.apply(this, arguments);
  15529. }
  15530. on.fn = fn;
  15531. this.on(event, on);
  15532. return this;
  15533. };
  15534. /**
  15535. * Remove the given callback for `event` or all
  15536. * registered callbacks.
  15537. *
  15538. * @param {String} event
  15539. * @param {Function} fn
  15540. * @return {Emitter}
  15541. * @api public
  15542. */
  15543. Emitter.prototype.off =
  15544. Emitter.prototype.removeListener =
  15545. Emitter.prototype.removeAllListeners =
  15546. Emitter.prototype.removeEventListener = function(event, fn){
  15547. this._callbacks = this._callbacks || {};
  15548. // all
  15549. if (0 == arguments.length) {
  15550. this._callbacks = {};
  15551. return this;
  15552. }
  15553. // specific event
  15554. var callbacks = this._callbacks[event];
  15555. if (!callbacks) return this;
  15556. // remove all handlers
  15557. if (1 == arguments.length) {
  15558. delete this._callbacks[event];
  15559. return this;
  15560. }
  15561. // remove specific handler
  15562. var cb;
  15563. for (var i = 0; i < callbacks.length; i++) {
  15564. cb = callbacks[i];
  15565. if (cb === fn || cb.fn === fn) {
  15566. callbacks.splice(i, 1);
  15567. break;
  15568. }
  15569. }
  15570. return this;
  15571. };
  15572. /**
  15573. * Emit `event` with the given args.
  15574. *
  15575. * @param {String} event
  15576. * @param {Mixed} ...
  15577. * @return {Emitter}
  15578. */
  15579. Emitter.prototype.emit = function(event){
  15580. this._callbacks = this._callbacks || {};
  15581. var args = [].slice.call(arguments, 1)
  15582. , callbacks = this._callbacks[event];
  15583. if (callbacks) {
  15584. callbacks = callbacks.slice(0);
  15585. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15586. callbacks[i].apply(this, args);
  15587. }
  15588. }
  15589. return this;
  15590. };
  15591. /**
  15592. * Return array of callbacks for `event`.
  15593. *
  15594. * @param {String} event
  15595. * @return {Array}
  15596. * @api public
  15597. */
  15598. Emitter.prototype.listeners = function(event){
  15599. this._callbacks = this._callbacks || {};
  15600. return this._callbacks[event] || [];
  15601. };
  15602. /**
  15603. * Check if this emitter has `event` handlers.
  15604. *
  15605. * @param {String} event
  15606. * @return {Boolean}
  15607. * @api public
  15608. */
  15609. Emitter.prototype.hasListeners = function(event){
  15610. return !! this.listeners(event).length;
  15611. };
  15612. },{}],3:[function(require,module,exports){
  15613. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15614. * http://eightmedia.github.com/hammer.js
  15615. *
  15616. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15617. * Licensed under the MIT license */
  15618. (function(window, undefined) {
  15619. 'use strict';
  15620. /**
  15621. * Hammer
  15622. * use this to create instances
  15623. * @param {HTMLElement} element
  15624. * @param {Object} options
  15625. * @returns {Hammer.Instance}
  15626. * @constructor
  15627. */
  15628. var Hammer = function(element, options) {
  15629. return new Hammer.Instance(element, options || {});
  15630. };
  15631. // default settings
  15632. Hammer.defaults = {
  15633. // add styles and attributes to the element to prevent the browser from doing
  15634. // its native behavior. this doesnt prevent the scrolling, but cancels
  15635. // the contextmenu, tap highlighting etc
  15636. // set to false to disable this
  15637. stop_browser_behavior: {
  15638. // this also triggers onselectstart=false for IE
  15639. userSelect: 'none',
  15640. // this makes the element blocking in IE10 >, you could experiment with the value
  15641. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15642. touchAction: 'none',
  15643. touchCallout: 'none',
  15644. contentZooming: 'none',
  15645. userDrag: 'none',
  15646. tapHighlightColor: 'rgba(0,0,0,0)'
  15647. }
  15648. // more settings are defined per gesture at gestures.js
  15649. };
  15650. // detect touchevents
  15651. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15652. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15653. // dont use mouseevents on mobile devices
  15654. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15655. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15656. // eventtypes per touchevent (start, move, end)
  15657. // are filled by Hammer.event.determineEventTypes on setup
  15658. Hammer.EVENT_TYPES = {};
  15659. // direction defines
  15660. Hammer.DIRECTION_DOWN = 'down';
  15661. Hammer.DIRECTION_LEFT = 'left';
  15662. Hammer.DIRECTION_UP = 'up';
  15663. Hammer.DIRECTION_RIGHT = 'right';
  15664. // pointer type
  15665. Hammer.POINTER_MOUSE = 'mouse';
  15666. Hammer.POINTER_TOUCH = 'touch';
  15667. Hammer.POINTER_PEN = 'pen';
  15668. // touch event defines
  15669. Hammer.EVENT_START = 'start';
  15670. Hammer.EVENT_MOVE = 'move';
  15671. Hammer.EVENT_END = 'end';
  15672. // hammer document where the base events are added at
  15673. Hammer.DOCUMENT = document;
  15674. // plugins namespace
  15675. Hammer.plugins = {};
  15676. // if the window events are set...
  15677. Hammer.READY = false;
  15678. /**
  15679. * setup events to detect gestures on the document
  15680. */
  15681. function setup() {
  15682. if(Hammer.READY) {
  15683. return;
  15684. }
  15685. // find what eventtypes we add listeners to
  15686. Hammer.event.determineEventTypes();
  15687. // Register all gestures inside Hammer.gestures
  15688. for(var name in Hammer.gestures) {
  15689. if(Hammer.gestures.hasOwnProperty(name)) {
  15690. Hammer.detection.register(Hammer.gestures[name]);
  15691. }
  15692. }
  15693. // Add touch events on the document
  15694. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15695. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15696. // Hammer is ready...!
  15697. Hammer.READY = true;
  15698. }
  15699. /**
  15700. * create new hammer instance
  15701. * all methods should return the instance itself, so it is chainable.
  15702. * @param {HTMLElement} element
  15703. * @param {Object} [options={}]
  15704. * @returns {Hammer.Instance}
  15705. * @constructor
  15706. */
  15707. Hammer.Instance = function(element, options) {
  15708. var self = this;
  15709. // setup HammerJS window events and register all gestures
  15710. // this also sets up the default options
  15711. setup();
  15712. this.element = element;
  15713. // start/stop detection option
  15714. this.enabled = true;
  15715. // merge options
  15716. this.options = Hammer.utils.extend(
  15717. Hammer.utils.extend({}, Hammer.defaults),
  15718. options || {});
  15719. // add some css to the element to prevent the browser from doing its native behavoir
  15720. if(this.options.stop_browser_behavior) {
  15721. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15722. }
  15723. // start detection on touchstart
  15724. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15725. if(self.enabled) {
  15726. Hammer.detection.startDetect(self, ev);
  15727. }
  15728. });
  15729. // return instance
  15730. return this;
  15731. };
  15732. Hammer.Instance.prototype = {
  15733. /**
  15734. * bind events to the instance
  15735. * @param {String} gesture
  15736. * @param {Function} handler
  15737. * @returns {Hammer.Instance}
  15738. */
  15739. on: function onEvent(gesture, handler){
  15740. var gestures = gesture.split(' ');
  15741. for(var t=0; t<gestures.length; t++) {
  15742. this.element.addEventListener(gestures[t], handler, false);
  15743. }
  15744. return this;
  15745. },
  15746. /**
  15747. * unbind events to the instance
  15748. * @param {String} gesture
  15749. * @param {Function} handler
  15750. * @returns {Hammer.Instance}
  15751. */
  15752. off: function offEvent(gesture, handler){
  15753. var gestures = gesture.split(' ');
  15754. for(var t=0; t<gestures.length; t++) {
  15755. this.element.removeEventListener(gestures[t], handler, false);
  15756. }
  15757. return this;
  15758. },
  15759. /**
  15760. * trigger gesture event
  15761. * @param {String} gesture
  15762. * @param {Object} eventData
  15763. * @returns {Hammer.Instance}
  15764. */
  15765. trigger: function triggerEvent(gesture, eventData){
  15766. // create DOM event
  15767. var event = Hammer.DOCUMENT.createEvent('Event');
  15768. event.initEvent(gesture, true, true);
  15769. event.gesture = eventData;
  15770. // trigger on the target if it is in the instance element,
  15771. // this is for event delegation tricks
  15772. var element = this.element;
  15773. if(Hammer.utils.hasParent(eventData.target, element)) {
  15774. element = eventData.target;
  15775. }
  15776. element.dispatchEvent(event);
  15777. return this;
  15778. },
  15779. /**
  15780. * enable of disable hammer.js detection
  15781. * @param {Boolean} state
  15782. * @returns {Hammer.Instance}
  15783. */
  15784. enable: function enable(state) {
  15785. this.enabled = state;
  15786. return this;
  15787. }
  15788. };
  15789. /**
  15790. * this holds the last move event,
  15791. * used to fix empty touchend issue
  15792. * see the onTouch event for an explanation
  15793. * @type {Object}
  15794. */
  15795. var last_move_event = null;
  15796. /**
  15797. * when the mouse is hold down, this is true
  15798. * @type {Boolean}
  15799. */
  15800. var enable_detect = false;
  15801. /**
  15802. * when touch events have been fired, this is true
  15803. * @type {Boolean}
  15804. */
  15805. var touch_triggered = false;
  15806. Hammer.event = {
  15807. /**
  15808. * simple addEventListener
  15809. * @param {HTMLElement} element
  15810. * @param {String} type
  15811. * @param {Function} handler
  15812. */
  15813. bindDom: function(element, type, handler) {
  15814. var types = type.split(' ');
  15815. for(var t=0; t<types.length; t++) {
  15816. element.addEventListener(types[t], handler, false);
  15817. }
  15818. },
  15819. /**
  15820. * touch events with mouse fallback
  15821. * @param {HTMLElement} element
  15822. * @param {String} eventType like Hammer.EVENT_MOVE
  15823. * @param {Function} handler
  15824. */
  15825. onTouch: function onTouch(element, eventType, handler) {
  15826. var self = this;
  15827. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15828. var sourceEventType = ev.type.toLowerCase();
  15829. // onmouseup, but when touchend has been fired we do nothing.
  15830. // this is for touchdevices which also fire a mouseup on touchend
  15831. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15832. return;
  15833. }
  15834. // mousebutton must be down or a touch event
  15835. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15836. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15837. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15838. ){
  15839. enable_detect = true;
  15840. }
  15841. // we are in a touch event, set the touch triggered bool to true,
  15842. // this for the conflicts that may occur on ios and android
  15843. if(sourceEventType.match(/touch|pointer/)) {
  15844. touch_triggered = true;
  15845. }
  15846. // count the total touches on the screen
  15847. var count_touches = 0;
  15848. // when touch has been triggered in this detection session
  15849. // and we are now handling a mouse event, we stop that to prevent conflicts
  15850. if(enable_detect) {
  15851. // update pointerevent
  15852. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15853. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15854. }
  15855. // touch
  15856. else if(sourceEventType.match(/touch/)) {
  15857. count_touches = ev.touches.length;
  15858. }
  15859. // mouse
  15860. else if(!touch_triggered) {
  15861. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15862. }
  15863. // if we are in a end event, but when we remove one touch and
  15864. // we still have enough, set eventType to move
  15865. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15866. eventType = Hammer.EVENT_MOVE;
  15867. }
  15868. // no touches, force the end event
  15869. else if(!count_touches) {
  15870. eventType = Hammer.EVENT_END;
  15871. }
  15872. // because touchend has no touches, and we often want to use these in our gestures,
  15873. // we send the last move event as our eventData in touchend
  15874. if(!count_touches && last_move_event !== null) {
  15875. ev = last_move_event;
  15876. }
  15877. // store the last move event
  15878. else {
  15879. last_move_event = ev;
  15880. }
  15881. // trigger the handler
  15882. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15883. // remove pointerevent from list
  15884. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15885. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15886. }
  15887. }
  15888. //debug(sourceEventType +" "+ eventType);
  15889. // on the end we reset everything
  15890. if(!count_touches) {
  15891. last_move_event = null;
  15892. enable_detect = false;
  15893. touch_triggered = false;
  15894. Hammer.PointerEvent.reset();
  15895. }
  15896. });
  15897. },
  15898. /**
  15899. * we have different events for each device/browser
  15900. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15901. */
  15902. determineEventTypes: function determineEventTypes() {
  15903. // determine the eventtype we want to set
  15904. var types;
  15905. // pointerEvents magic
  15906. if(Hammer.HAS_POINTEREVENTS) {
  15907. types = Hammer.PointerEvent.getEvents();
  15908. }
  15909. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15910. else if(Hammer.NO_MOUSEEVENTS) {
  15911. types = [
  15912. 'touchstart',
  15913. 'touchmove',
  15914. 'touchend touchcancel'];
  15915. }
  15916. // for non pointer events browsers and mixed browsers,
  15917. // like chrome on windows8 touch laptop
  15918. else {
  15919. types = [
  15920. 'touchstart mousedown',
  15921. 'touchmove mousemove',
  15922. 'touchend touchcancel mouseup'];
  15923. }
  15924. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  15925. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  15926. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  15927. },
  15928. /**
  15929. * create touchlist depending on the event
  15930. * @param {Object} ev
  15931. * @param {String} eventType used by the fakemultitouch plugin
  15932. */
  15933. getTouchList: function getTouchList(ev/*, eventType*/) {
  15934. // get the fake pointerEvent touchlist
  15935. if(Hammer.HAS_POINTEREVENTS) {
  15936. return Hammer.PointerEvent.getTouchList();
  15937. }
  15938. // get the touchlist
  15939. else if(ev.touches) {
  15940. return ev.touches;
  15941. }
  15942. // make fake touchlist from mouse position
  15943. else {
  15944. return [{
  15945. identifier: 1,
  15946. pageX: ev.pageX,
  15947. pageY: ev.pageY,
  15948. target: ev.target
  15949. }];
  15950. }
  15951. },
  15952. /**
  15953. * collect event data for Hammer js
  15954. * @param {HTMLElement} element
  15955. * @param {String} eventType like Hammer.EVENT_MOVE
  15956. * @param {Object} eventData
  15957. */
  15958. collectEventData: function collectEventData(element, eventType, ev) {
  15959. var touches = this.getTouchList(ev, eventType);
  15960. // find out pointerType
  15961. var pointerType = Hammer.POINTER_TOUCH;
  15962. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  15963. pointerType = Hammer.POINTER_MOUSE;
  15964. }
  15965. return {
  15966. center : Hammer.utils.getCenter(touches),
  15967. timeStamp : new Date().getTime(),
  15968. target : ev.target,
  15969. touches : touches,
  15970. eventType : eventType,
  15971. pointerType : pointerType,
  15972. srcEvent : ev,
  15973. /**
  15974. * prevent the browser default actions
  15975. * mostly used to disable scrolling of the browser
  15976. */
  15977. preventDefault: function() {
  15978. if(this.srcEvent.preventManipulation) {
  15979. this.srcEvent.preventManipulation();
  15980. }
  15981. if(this.srcEvent.preventDefault) {
  15982. this.srcEvent.preventDefault();
  15983. }
  15984. },
  15985. /**
  15986. * stop bubbling the event up to its parents
  15987. */
  15988. stopPropagation: function() {
  15989. this.srcEvent.stopPropagation();
  15990. },
  15991. /**
  15992. * immediately stop gesture detection
  15993. * might be useful after a swipe was detected
  15994. * @return {*}
  15995. */
  15996. stopDetect: function() {
  15997. return Hammer.detection.stopDetect();
  15998. }
  15999. };
  16000. }
  16001. };
  16002. Hammer.PointerEvent = {
  16003. /**
  16004. * holds all pointers
  16005. * @type {Object}
  16006. */
  16007. pointers: {},
  16008. /**
  16009. * get a list of pointers
  16010. * @returns {Array} touchlist
  16011. */
  16012. getTouchList: function() {
  16013. var self = this;
  16014. var touchlist = [];
  16015. // we can use forEach since pointerEvents only is in IE10
  16016. Object.keys(self.pointers).sort().forEach(function(id) {
  16017. touchlist.push(self.pointers[id]);
  16018. });
  16019. return touchlist;
  16020. },
  16021. /**
  16022. * update the position of a pointer
  16023. * @param {String} type Hammer.EVENT_END
  16024. * @param {Object} pointerEvent
  16025. */
  16026. updatePointer: function(type, pointerEvent) {
  16027. if(type == Hammer.EVENT_END) {
  16028. this.pointers = {};
  16029. }
  16030. else {
  16031. pointerEvent.identifier = pointerEvent.pointerId;
  16032. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16033. }
  16034. return Object.keys(this.pointers).length;
  16035. },
  16036. /**
  16037. * check if ev matches pointertype
  16038. * @param {String} pointerType Hammer.POINTER_MOUSE
  16039. * @param {PointerEvent} ev
  16040. */
  16041. matchType: function(pointerType, ev) {
  16042. if(!ev.pointerType) {
  16043. return false;
  16044. }
  16045. var types = {};
  16046. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16047. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16048. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16049. return types[pointerType];
  16050. },
  16051. /**
  16052. * get events
  16053. */
  16054. getEvents: function() {
  16055. return [
  16056. 'pointerdown MSPointerDown',
  16057. 'pointermove MSPointerMove',
  16058. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16059. ];
  16060. },
  16061. /**
  16062. * reset the list
  16063. */
  16064. reset: function() {
  16065. this.pointers = {};
  16066. }
  16067. };
  16068. Hammer.utils = {
  16069. /**
  16070. * extend method,
  16071. * also used for cloning when dest is an empty object
  16072. * @param {Object} dest
  16073. * @param {Object} src
  16074. * @parm {Boolean} merge do a merge
  16075. * @returns {Object} dest
  16076. */
  16077. extend: function extend(dest, src, merge) {
  16078. for (var key in src) {
  16079. if(dest[key] !== undefined && merge) {
  16080. continue;
  16081. }
  16082. dest[key] = src[key];
  16083. }
  16084. return dest;
  16085. },
  16086. /**
  16087. * find if a node is in the given parent
  16088. * used for event delegation tricks
  16089. * @param {HTMLElement} node
  16090. * @param {HTMLElement} parent
  16091. * @returns {boolean} has_parent
  16092. */
  16093. hasParent: function(node, parent) {
  16094. while(node){
  16095. if(node == parent) {
  16096. return true;
  16097. }
  16098. node = node.parentNode;
  16099. }
  16100. return false;
  16101. },
  16102. /**
  16103. * get the center of all the touches
  16104. * @param {Array} touches
  16105. * @returns {Object} center
  16106. */
  16107. getCenter: function getCenter(touches) {
  16108. var valuesX = [], valuesY = [];
  16109. for(var t= 0,len=touches.length; t<len; t++) {
  16110. valuesX.push(touches[t].pageX);
  16111. valuesY.push(touches[t].pageY);
  16112. }
  16113. return {
  16114. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16115. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16116. };
  16117. },
  16118. /**
  16119. * calculate the velocity between two points
  16120. * @param {Number} delta_time
  16121. * @param {Number} delta_x
  16122. * @param {Number} delta_y
  16123. * @returns {Object} velocity
  16124. */
  16125. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16126. return {
  16127. x: Math.abs(delta_x / delta_time) || 0,
  16128. y: Math.abs(delta_y / delta_time) || 0
  16129. };
  16130. },
  16131. /**
  16132. * calculate the angle between two coordinates
  16133. * @param {Touch} touch1
  16134. * @param {Touch} touch2
  16135. * @returns {Number} angle
  16136. */
  16137. getAngle: function getAngle(touch1, touch2) {
  16138. var y = touch2.pageY - touch1.pageY,
  16139. x = touch2.pageX - touch1.pageX;
  16140. return Math.atan2(y, x) * 180 / Math.PI;
  16141. },
  16142. /**
  16143. * angle to direction define
  16144. * @param {Touch} touch1
  16145. * @param {Touch} touch2
  16146. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16147. */
  16148. getDirection: function getDirection(touch1, touch2) {
  16149. var x = Math.abs(touch1.pageX - touch2.pageX),
  16150. y = Math.abs(touch1.pageY - touch2.pageY);
  16151. if(x >= y) {
  16152. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16153. }
  16154. else {
  16155. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16156. }
  16157. },
  16158. /**
  16159. * calculate the distance between two touches
  16160. * @param {Touch} touch1
  16161. * @param {Touch} touch2
  16162. * @returns {Number} distance
  16163. */
  16164. getDistance: function getDistance(touch1, touch2) {
  16165. var x = touch2.pageX - touch1.pageX,
  16166. y = touch2.pageY - touch1.pageY;
  16167. return Math.sqrt((x*x) + (y*y));
  16168. },
  16169. /**
  16170. * calculate the scale factor between two touchLists (fingers)
  16171. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16172. * @param {Array} start
  16173. * @param {Array} end
  16174. * @returns {Number} scale
  16175. */
  16176. getScale: function getScale(start, end) {
  16177. // need two fingers...
  16178. if(start.length >= 2 && end.length >= 2) {
  16179. return this.getDistance(end[0], end[1]) /
  16180. this.getDistance(start[0], start[1]);
  16181. }
  16182. return 1;
  16183. },
  16184. /**
  16185. * calculate the rotation degrees between two touchLists (fingers)
  16186. * @param {Array} start
  16187. * @param {Array} end
  16188. * @returns {Number} rotation
  16189. */
  16190. getRotation: function getRotation(start, end) {
  16191. // need two fingers
  16192. if(start.length >= 2 && end.length >= 2) {
  16193. return this.getAngle(end[1], end[0]) -
  16194. this.getAngle(start[1], start[0]);
  16195. }
  16196. return 0;
  16197. },
  16198. /**
  16199. * boolean if the direction is vertical
  16200. * @param {String} direction
  16201. * @returns {Boolean} is_vertical
  16202. */
  16203. isVertical: function isVertical(direction) {
  16204. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16205. },
  16206. /**
  16207. * stop browser default behavior with css props
  16208. * @param {HtmlElement} element
  16209. * @param {Object} css_props
  16210. */
  16211. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16212. var prop,
  16213. vendors = ['webkit','khtml','moz','ms','o',''];
  16214. if(!css_props || !element.style) {
  16215. return;
  16216. }
  16217. // with css properties for modern browsers
  16218. for(var i = 0; i < vendors.length; i++) {
  16219. for(var p in css_props) {
  16220. if(css_props.hasOwnProperty(p)) {
  16221. prop = p;
  16222. // vender prefix at the property
  16223. if(vendors[i]) {
  16224. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16225. }
  16226. // set the style
  16227. element.style[prop] = css_props[p];
  16228. }
  16229. }
  16230. }
  16231. // also the disable onselectstart
  16232. if(css_props.userSelect == 'none') {
  16233. element.onselectstart = function() {
  16234. return false;
  16235. };
  16236. }
  16237. }
  16238. };
  16239. Hammer.detection = {
  16240. // contains all registred Hammer.gestures in the correct order
  16241. gestures: [],
  16242. // data of the current Hammer.gesture detection session
  16243. current: null,
  16244. // the previous Hammer.gesture session data
  16245. // is a full clone of the previous gesture.current object
  16246. previous: null,
  16247. // when this becomes true, no gestures are fired
  16248. stopped: false,
  16249. /**
  16250. * start Hammer.gesture detection
  16251. * @param {Hammer.Instance} inst
  16252. * @param {Object} eventData
  16253. */
  16254. startDetect: function startDetect(inst, eventData) {
  16255. // already busy with a Hammer.gesture detection on an element
  16256. if(this.current) {
  16257. return;
  16258. }
  16259. this.stopped = false;
  16260. this.current = {
  16261. inst : inst, // reference to HammerInstance we're working for
  16262. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16263. lastEvent : false, // last eventData
  16264. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16265. };
  16266. this.detect(eventData);
  16267. },
  16268. /**
  16269. * Hammer.gesture detection
  16270. * @param {Object} eventData
  16271. * @param {Object} eventData
  16272. */
  16273. detect: function detect(eventData) {
  16274. if(!this.current || this.stopped) {
  16275. return;
  16276. }
  16277. // extend event data with calculations about scale, distance etc
  16278. eventData = this.extendEventData(eventData);
  16279. // instance options
  16280. var inst_options = this.current.inst.options;
  16281. // call Hammer.gesture handlers
  16282. for(var g=0,len=this.gestures.length; g<len; g++) {
  16283. var gesture = this.gestures[g];
  16284. // only when the instance options have enabled this gesture
  16285. if(!this.stopped && inst_options[gesture.name] !== false) {
  16286. // if a handler returns false, we stop with the detection
  16287. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16288. this.stopDetect();
  16289. break;
  16290. }
  16291. }
  16292. }
  16293. // store as previous event event
  16294. if(this.current) {
  16295. this.current.lastEvent = eventData;
  16296. }
  16297. // endevent, but not the last touch, so dont stop
  16298. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16299. this.stopDetect();
  16300. }
  16301. return eventData;
  16302. },
  16303. /**
  16304. * clear the Hammer.gesture vars
  16305. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16306. * to stop other Hammer.gestures from being fired
  16307. */
  16308. stopDetect: function stopDetect() {
  16309. // clone current data to the store as the previous gesture
  16310. // used for the double tap gesture, since this is an other gesture detect session
  16311. this.previous = Hammer.utils.extend({}, this.current);
  16312. // reset the current
  16313. this.current = null;
  16314. // stopped!
  16315. this.stopped = true;
  16316. },
  16317. /**
  16318. * extend eventData for Hammer.gestures
  16319. * @param {Object} ev
  16320. * @returns {Object} ev
  16321. */
  16322. extendEventData: function extendEventData(ev) {
  16323. var startEv = this.current.startEvent;
  16324. // if the touches change, set the new touches over the startEvent touches
  16325. // this because touchevents don't have all the touches on touchstart, or the
  16326. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16327. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16328. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16329. // extend 1 level deep to get the touchlist with the touch objects
  16330. startEv.touches = [];
  16331. for(var i=0,len=ev.touches.length; i<len; i++) {
  16332. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16333. }
  16334. }
  16335. var delta_time = ev.timeStamp - startEv.timeStamp,
  16336. delta_x = ev.center.pageX - startEv.center.pageX,
  16337. delta_y = ev.center.pageY - startEv.center.pageY,
  16338. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16339. Hammer.utils.extend(ev, {
  16340. deltaTime : delta_time,
  16341. deltaX : delta_x,
  16342. deltaY : delta_y,
  16343. velocityX : velocity.x,
  16344. velocityY : velocity.y,
  16345. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16346. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16347. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16348. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16349. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16350. startEvent : startEv
  16351. });
  16352. return ev;
  16353. },
  16354. /**
  16355. * register new gesture
  16356. * @param {Object} gesture object, see gestures.js for documentation
  16357. * @returns {Array} gestures
  16358. */
  16359. register: function register(gesture) {
  16360. // add an enable gesture options if there is no given
  16361. var options = gesture.defaults || {};
  16362. if(options[gesture.name] === undefined) {
  16363. options[gesture.name] = true;
  16364. }
  16365. // extend Hammer default options with the Hammer.gesture options
  16366. Hammer.utils.extend(Hammer.defaults, options, true);
  16367. // set its index
  16368. gesture.index = gesture.index || 1000;
  16369. // add Hammer.gesture to the list
  16370. this.gestures.push(gesture);
  16371. // sort the list by index
  16372. this.gestures.sort(function(a, b) {
  16373. if (a.index < b.index) {
  16374. return -1;
  16375. }
  16376. if (a.index > b.index) {
  16377. return 1;
  16378. }
  16379. return 0;
  16380. });
  16381. return this.gestures;
  16382. }
  16383. };
  16384. Hammer.gestures = Hammer.gestures || {};
  16385. /**
  16386. * Custom gestures
  16387. * ==============================
  16388. *
  16389. * Gesture object
  16390. * --------------------
  16391. * The object structure of a gesture:
  16392. *
  16393. * { name: 'mygesture',
  16394. * index: 1337,
  16395. * defaults: {
  16396. * mygesture_option: true
  16397. * }
  16398. * handler: function(type, ev, inst) {
  16399. * // trigger gesture event
  16400. * inst.trigger(this.name, ev);
  16401. * }
  16402. * }
  16403. * @param {String} name
  16404. * this should be the name of the gesture, lowercase
  16405. * it is also being used to disable/enable the gesture per instance config.
  16406. *
  16407. * @param {Number} [index=1000]
  16408. * the index of the gesture, where it is going to be in the stack of gestures detection
  16409. * like when you build an gesture that depends on the drag gesture, it is a good
  16410. * idea to place it after the index of the drag gesture.
  16411. *
  16412. * @param {Object} [defaults={}]
  16413. * the default settings of the gesture. these are added to the instance settings,
  16414. * and can be overruled per instance. you can also add the name of the gesture,
  16415. * but this is also added by default (and set to true).
  16416. *
  16417. * @param {Function} handler
  16418. * this handles the gesture detection of your custom gesture and receives the
  16419. * following arguments:
  16420. *
  16421. * @param {Object} eventData
  16422. * event data containing the following properties:
  16423. * timeStamp {Number} time the event occurred
  16424. * target {HTMLElement} target element
  16425. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16426. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16427. * center {Object} center position of the touches. contains pageX and pageY
  16428. * deltaTime {Number} the total time of the touches in the screen
  16429. * deltaX {Number} the delta on x axis we haved moved
  16430. * deltaY {Number} the delta on y axis we haved moved
  16431. * velocityX {Number} the velocity on the x
  16432. * velocityY {Number} the velocity on y
  16433. * angle {Number} the angle we are moving
  16434. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16435. * distance {Number} the distance we haved moved
  16436. * scale {Number} scaling of the touches, needs 2 touches
  16437. * rotation {Number} rotation of the touches, needs 2 touches *
  16438. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16439. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16440. * startEvent {Object} contains the same properties as above,
  16441. * but from the first touch. this is used to calculate
  16442. * distances, deltaTime, scaling etc
  16443. *
  16444. * @param {Hammer.Instance} inst
  16445. * the instance we are doing the detection for. you can get the options from
  16446. * the inst.options object and trigger the gesture event by calling inst.trigger
  16447. *
  16448. *
  16449. * Handle gestures
  16450. * --------------------
  16451. * inside the handler you can get/set Hammer.detection.current. This is the current
  16452. * detection session. It has the following properties
  16453. * @param {String} name
  16454. * contains the name of the gesture we have detected. it has not a real function,
  16455. * only to check in other gestures if something is detected.
  16456. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16457. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16458. *
  16459. * @readonly
  16460. * @param {Hammer.Instance} inst
  16461. * the instance we do the detection for
  16462. *
  16463. * @readonly
  16464. * @param {Object} startEvent
  16465. * contains the properties of the first gesture detection in this session.
  16466. * Used for calculations about timing, distance, etc.
  16467. *
  16468. * @readonly
  16469. * @param {Object} lastEvent
  16470. * contains all the properties of the last gesture detect in this session.
  16471. *
  16472. * after the gesture detection session has been completed (user has released the screen)
  16473. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16474. * this is usefull for gestures like doubletap, where you need to know if the
  16475. * previous gesture was a tap
  16476. *
  16477. * options that have been set by the instance can be received by calling inst.options
  16478. *
  16479. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16480. * The first param is the name of your gesture, the second the event argument
  16481. *
  16482. *
  16483. * Register gestures
  16484. * --------------------
  16485. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16486. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16487. * manually and pass your gesture object as a param
  16488. *
  16489. */
  16490. /**
  16491. * Hold
  16492. * Touch stays at the same place for x time
  16493. * @events hold
  16494. */
  16495. Hammer.gestures.Hold = {
  16496. name: 'hold',
  16497. index: 10,
  16498. defaults: {
  16499. hold_timeout : 500,
  16500. hold_threshold : 1
  16501. },
  16502. timer: null,
  16503. handler: function holdGesture(ev, inst) {
  16504. switch(ev.eventType) {
  16505. case Hammer.EVENT_START:
  16506. // clear any running timers
  16507. clearTimeout(this.timer);
  16508. // set the gesture so we can check in the timeout if it still is
  16509. Hammer.detection.current.name = this.name;
  16510. // set timer and if after the timeout it still is hold,
  16511. // we trigger the hold event
  16512. this.timer = setTimeout(function() {
  16513. if(Hammer.detection.current.name == 'hold') {
  16514. inst.trigger('hold', ev);
  16515. }
  16516. }, inst.options.hold_timeout);
  16517. break;
  16518. // when you move or end we clear the timer
  16519. case Hammer.EVENT_MOVE:
  16520. if(ev.distance > inst.options.hold_threshold) {
  16521. clearTimeout(this.timer);
  16522. }
  16523. break;
  16524. case Hammer.EVENT_END:
  16525. clearTimeout(this.timer);
  16526. break;
  16527. }
  16528. }
  16529. };
  16530. /**
  16531. * Tap/DoubleTap
  16532. * Quick touch at a place or double at the same place
  16533. * @events tap, doubletap
  16534. */
  16535. Hammer.gestures.Tap = {
  16536. name: 'tap',
  16537. index: 100,
  16538. defaults: {
  16539. tap_max_touchtime : 250,
  16540. tap_max_distance : 10,
  16541. tap_always : true,
  16542. doubletap_distance : 20,
  16543. doubletap_interval : 300
  16544. },
  16545. handler: function tapGesture(ev, inst) {
  16546. if(ev.eventType == Hammer.EVENT_END) {
  16547. // previous gesture, for the double tap since these are two different gesture detections
  16548. var prev = Hammer.detection.previous,
  16549. did_doubletap = false;
  16550. // when the touchtime is higher then the max touch time
  16551. // or when the moving distance is too much
  16552. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16553. ev.distance > inst.options.tap_max_distance) {
  16554. return;
  16555. }
  16556. // check if double tap
  16557. if(prev && prev.name == 'tap' &&
  16558. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16559. ev.distance < inst.options.doubletap_distance) {
  16560. inst.trigger('doubletap', ev);
  16561. did_doubletap = true;
  16562. }
  16563. // do a single tap
  16564. if(!did_doubletap || inst.options.tap_always) {
  16565. Hammer.detection.current.name = 'tap';
  16566. inst.trigger(Hammer.detection.current.name, ev);
  16567. }
  16568. }
  16569. }
  16570. };
  16571. /**
  16572. * Swipe
  16573. * triggers swipe events when the end velocity is above the threshold
  16574. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16575. */
  16576. Hammer.gestures.Swipe = {
  16577. name: 'swipe',
  16578. index: 40,
  16579. defaults: {
  16580. // set 0 for unlimited, but this can conflict with transform
  16581. swipe_max_touches : 1,
  16582. swipe_velocity : 0.7
  16583. },
  16584. handler: function swipeGesture(ev, inst) {
  16585. if(ev.eventType == Hammer.EVENT_END) {
  16586. // max touches
  16587. if(inst.options.swipe_max_touches > 0 &&
  16588. ev.touches.length > inst.options.swipe_max_touches) {
  16589. return;
  16590. }
  16591. // when the distance we moved is too small we skip this gesture
  16592. // or we can be already in dragging
  16593. if(ev.velocityX > inst.options.swipe_velocity ||
  16594. ev.velocityY > inst.options.swipe_velocity) {
  16595. // trigger swipe events
  16596. inst.trigger(this.name, ev);
  16597. inst.trigger(this.name + ev.direction, ev);
  16598. }
  16599. }
  16600. }
  16601. };
  16602. /**
  16603. * Drag
  16604. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16605. * moving left and right is a good practice. When all the drag events are blocking
  16606. * you disable scrolling on that area.
  16607. * @events drag, drapleft, dragright, dragup, dragdown
  16608. */
  16609. Hammer.gestures.Drag = {
  16610. name: 'drag',
  16611. index: 50,
  16612. defaults: {
  16613. drag_min_distance : 10,
  16614. // set 0 for unlimited, but this can conflict with transform
  16615. drag_max_touches : 1,
  16616. // prevent default browser behavior when dragging occurs
  16617. // be careful with it, it makes the element a blocking element
  16618. // when you are using the drag gesture, it is a good practice to set this true
  16619. drag_block_horizontal : false,
  16620. drag_block_vertical : false,
  16621. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16622. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16623. drag_lock_to_axis : false,
  16624. // drag lock only kicks in when distance > drag_lock_min_distance
  16625. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16626. drag_lock_min_distance : 25
  16627. },
  16628. triggered: false,
  16629. handler: function dragGesture(ev, inst) {
  16630. // current gesture isnt drag, but dragged is true
  16631. // this means an other gesture is busy. now call dragend
  16632. if(Hammer.detection.current.name != this.name && this.triggered) {
  16633. inst.trigger(this.name +'end', ev);
  16634. this.triggered = false;
  16635. return;
  16636. }
  16637. // max touches
  16638. if(inst.options.drag_max_touches > 0 &&
  16639. ev.touches.length > inst.options.drag_max_touches) {
  16640. return;
  16641. }
  16642. switch(ev.eventType) {
  16643. case Hammer.EVENT_START:
  16644. this.triggered = false;
  16645. break;
  16646. case Hammer.EVENT_MOVE:
  16647. // when the distance we moved is too small we skip this gesture
  16648. // or we can be already in dragging
  16649. if(ev.distance < inst.options.drag_min_distance &&
  16650. Hammer.detection.current.name != this.name) {
  16651. return;
  16652. }
  16653. // we are dragging!
  16654. Hammer.detection.current.name = this.name;
  16655. // lock drag to axis?
  16656. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16657. ev.drag_locked_to_axis = true;
  16658. }
  16659. var last_direction = Hammer.detection.current.lastEvent.direction;
  16660. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16661. // keep direction on the axis that the drag gesture started on
  16662. if(Hammer.utils.isVertical(last_direction)) {
  16663. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16664. }
  16665. else {
  16666. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16667. }
  16668. }
  16669. // first time, trigger dragstart event
  16670. if(!this.triggered) {
  16671. inst.trigger(this.name +'start', ev);
  16672. this.triggered = true;
  16673. }
  16674. // trigger normal event
  16675. inst.trigger(this.name, ev);
  16676. // direction event, like dragdown
  16677. inst.trigger(this.name + ev.direction, ev);
  16678. // block the browser events
  16679. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16680. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16681. ev.preventDefault();
  16682. }
  16683. break;
  16684. case Hammer.EVENT_END:
  16685. // trigger dragend
  16686. if(this.triggered) {
  16687. inst.trigger(this.name +'end', ev);
  16688. }
  16689. this.triggered = false;
  16690. break;
  16691. }
  16692. }
  16693. };
  16694. /**
  16695. * Transform
  16696. * User want to scale or rotate with 2 fingers
  16697. * @events transform, pinch, pinchin, pinchout, rotate
  16698. */
  16699. Hammer.gestures.Transform = {
  16700. name: 'transform',
  16701. index: 45,
  16702. defaults: {
  16703. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16704. transform_min_scale : 0.01,
  16705. // rotation in degrees
  16706. transform_min_rotation : 1,
  16707. // prevent default browser behavior when two touches are on the screen
  16708. // but it makes the element a blocking element
  16709. // when you are using the transform gesture, it is a good practice to set this true
  16710. transform_always_block : false
  16711. },
  16712. triggered: false,
  16713. handler: function transformGesture(ev, inst) {
  16714. // current gesture isnt drag, but dragged is true
  16715. // this means an other gesture is busy. now call dragend
  16716. if(Hammer.detection.current.name != this.name && this.triggered) {
  16717. inst.trigger(this.name +'end', ev);
  16718. this.triggered = false;
  16719. return;
  16720. }
  16721. // atleast multitouch
  16722. if(ev.touches.length < 2) {
  16723. return;
  16724. }
  16725. // prevent default when two fingers are on the screen
  16726. if(inst.options.transform_always_block) {
  16727. ev.preventDefault();
  16728. }
  16729. switch(ev.eventType) {
  16730. case Hammer.EVENT_START:
  16731. this.triggered = false;
  16732. break;
  16733. case Hammer.EVENT_MOVE:
  16734. var scale_threshold = Math.abs(1-ev.scale);
  16735. var rotation_threshold = Math.abs(ev.rotation);
  16736. // when the distance we moved is too small we skip this gesture
  16737. // or we can be already in dragging
  16738. if(scale_threshold < inst.options.transform_min_scale &&
  16739. rotation_threshold < inst.options.transform_min_rotation) {
  16740. return;
  16741. }
  16742. // we are transforming!
  16743. Hammer.detection.current.name = this.name;
  16744. // first time, trigger dragstart event
  16745. if(!this.triggered) {
  16746. inst.trigger(this.name +'start', ev);
  16747. this.triggered = true;
  16748. }
  16749. inst.trigger(this.name, ev); // basic transform event
  16750. // trigger rotate event
  16751. if(rotation_threshold > inst.options.transform_min_rotation) {
  16752. inst.trigger('rotate', ev);
  16753. }
  16754. // trigger pinch event
  16755. if(scale_threshold > inst.options.transform_min_scale) {
  16756. inst.trigger('pinch', ev);
  16757. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16758. }
  16759. break;
  16760. case Hammer.EVENT_END:
  16761. // trigger dragend
  16762. if(this.triggered) {
  16763. inst.trigger(this.name +'end', ev);
  16764. }
  16765. this.triggered = false;
  16766. break;
  16767. }
  16768. }
  16769. };
  16770. /**
  16771. * Touch
  16772. * Called as first, tells the user has touched the screen
  16773. * @events touch
  16774. */
  16775. Hammer.gestures.Touch = {
  16776. name: 'touch',
  16777. index: -Infinity,
  16778. defaults: {
  16779. // call preventDefault at touchstart, and makes the element blocking by
  16780. // disabling the scrolling of the page, but it improves gestures like
  16781. // transforming and dragging.
  16782. // be careful with using this, it can be very annoying for users to be stuck
  16783. // on the page
  16784. prevent_default: false,
  16785. // disable mouse events, so only touch (or pen!) input triggers events
  16786. prevent_mouseevents: false
  16787. },
  16788. handler: function touchGesture(ev, inst) {
  16789. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16790. ev.stopDetect();
  16791. return;
  16792. }
  16793. if(inst.options.prevent_default) {
  16794. ev.preventDefault();
  16795. }
  16796. if(ev.eventType == Hammer.EVENT_START) {
  16797. inst.trigger(this.name, ev);
  16798. }
  16799. }
  16800. };
  16801. /**
  16802. * Release
  16803. * Called as last, tells the user has released the screen
  16804. * @events release
  16805. */
  16806. Hammer.gestures.Release = {
  16807. name: 'release',
  16808. index: Infinity,
  16809. handler: function releaseGesture(ev, inst) {
  16810. if(ev.eventType == Hammer.EVENT_END) {
  16811. inst.trigger(this.name, ev);
  16812. }
  16813. }
  16814. };
  16815. // node export
  16816. if(typeof module === 'object' && typeof module.exports === 'object'){
  16817. module.exports = Hammer;
  16818. }
  16819. // just window export
  16820. else {
  16821. window.Hammer = Hammer;
  16822. // requireJS module definition
  16823. if(typeof window.define === 'function' && window.define.amd) {
  16824. window.define('hammer', [], function() {
  16825. return Hammer;
  16826. });
  16827. }
  16828. }
  16829. })(this);
  16830. },{}],4:[function(require,module,exports){
  16831. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  16832. //! version : 2.6.0
  16833. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16834. //! license : MIT
  16835. //! momentjs.com
  16836. (function (undefined) {
  16837. /************************************
  16838. Constants
  16839. ************************************/
  16840. var moment,
  16841. VERSION = "2.6.0",
  16842. // the global-scope this is NOT the global object in Node.js
  16843. globalScope = typeof global !== 'undefined' ? global : this,
  16844. oldGlobalMoment,
  16845. round = Math.round,
  16846. i,
  16847. YEAR = 0,
  16848. MONTH = 1,
  16849. DATE = 2,
  16850. HOUR = 3,
  16851. MINUTE = 4,
  16852. SECOND = 5,
  16853. MILLISECOND = 6,
  16854. // internal storage for language config files
  16855. languages = {},
  16856. // moment internal properties
  16857. momentProperties = {
  16858. _isAMomentObject: null,
  16859. _i : null,
  16860. _f : null,
  16861. _l : null,
  16862. _strict : null,
  16863. _isUTC : null,
  16864. _offset : null, // optional. Combine with _isUTC
  16865. _pf : null,
  16866. _lang : null // optional
  16867. },
  16868. // check for nodeJS
  16869. hasModule = (typeof module !== 'undefined' && module.exports),
  16870. // ASP.NET json date format regex
  16871. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16872. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16873. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16874. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16875. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16876. // format tokens
  16877. 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,
  16878. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16879. // parsing token regexes
  16880. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16881. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16882. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16883. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16884. parseTokenDigits = /\d+/, // nonzero number of digits
  16885. 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.
  16886. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16887. parseTokenT = /T/i, // T (ISO separator)
  16888. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16889. parseTokenOrdinal = /\d{1,2}/,
  16890. //strict parsing regexes
  16891. parseTokenOneDigit = /\d/, // 0 - 9
  16892. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16893. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16894. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16895. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16896. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16897. // iso 8601 regex
  16898. // 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)
  16899. 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)?)?$/,
  16900. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16901. isoDates = [
  16902. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16903. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16904. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16905. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16906. ['YYYY-DDD', /\d{4}-\d{3}/]
  16907. ],
  16908. // iso time formats and regexes
  16909. isoTimes = [
  16910. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  16911. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  16912. ['HH:mm', /(T| )\d\d:\d\d/],
  16913. ['HH', /(T| )\d\d/]
  16914. ],
  16915. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  16916. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  16917. // getter and setter names
  16918. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  16919. unitMillisecondFactors = {
  16920. 'Milliseconds' : 1,
  16921. 'Seconds' : 1e3,
  16922. 'Minutes' : 6e4,
  16923. 'Hours' : 36e5,
  16924. 'Days' : 864e5,
  16925. 'Months' : 2592e6,
  16926. 'Years' : 31536e6
  16927. },
  16928. unitAliases = {
  16929. ms : 'millisecond',
  16930. s : 'second',
  16931. m : 'minute',
  16932. h : 'hour',
  16933. d : 'day',
  16934. D : 'date',
  16935. w : 'week',
  16936. W : 'isoWeek',
  16937. M : 'month',
  16938. Q : 'quarter',
  16939. y : 'year',
  16940. DDD : 'dayOfYear',
  16941. e : 'weekday',
  16942. E : 'isoWeekday',
  16943. gg: 'weekYear',
  16944. GG: 'isoWeekYear'
  16945. },
  16946. camelFunctions = {
  16947. dayofyear : 'dayOfYear',
  16948. isoweekday : 'isoWeekday',
  16949. isoweek : 'isoWeek',
  16950. weekyear : 'weekYear',
  16951. isoweekyear : 'isoWeekYear'
  16952. },
  16953. // format function strings
  16954. formatFunctions = {},
  16955. // tokens to ordinalize and pad
  16956. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  16957. paddedTokens = 'M D H h m s w W'.split(' '),
  16958. formatTokenFunctions = {
  16959. M : function () {
  16960. return this.month() + 1;
  16961. },
  16962. MMM : function (format) {
  16963. return this.lang().monthsShort(this, format);
  16964. },
  16965. MMMM : function (format) {
  16966. return this.lang().months(this, format);
  16967. },
  16968. D : function () {
  16969. return this.date();
  16970. },
  16971. DDD : function () {
  16972. return this.dayOfYear();
  16973. },
  16974. d : function () {
  16975. return this.day();
  16976. },
  16977. dd : function (format) {
  16978. return this.lang().weekdaysMin(this, format);
  16979. },
  16980. ddd : function (format) {
  16981. return this.lang().weekdaysShort(this, format);
  16982. },
  16983. dddd : function (format) {
  16984. return this.lang().weekdays(this, format);
  16985. },
  16986. w : function () {
  16987. return this.week();
  16988. },
  16989. W : function () {
  16990. return this.isoWeek();
  16991. },
  16992. YY : function () {
  16993. return leftZeroFill(this.year() % 100, 2);
  16994. },
  16995. YYYY : function () {
  16996. return leftZeroFill(this.year(), 4);
  16997. },
  16998. YYYYY : function () {
  16999. return leftZeroFill(this.year(), 5);
  17000. },
  17001. YYYYYY : function () {
  17002. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17003. return sign + leftZeroFill(Math.abs(y), 6);
  17004. },
  17005. gg : function () {
  17006. return leftZeroFill(this.weekYear() % 100, 2);
  17007. },
  17008. gggg : function () {
  17009. return leftZeroFill(this.weekYear(), 4);
  17010. },
  17011. ggggg : function () {
  17012. return leftZeroFill(this.weekYear(), 5);
  17013. },
  17014. GG : function () {
  17015. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17016. },
  17017. GGGG : function () {
  17018. return leftZeroFill(this.isoWeekYear(), 4);
  17019. },
  17020. GGGGG : function () {
  17021. return leftZeroFill(this.isoWeekYear(), 5);
  17022. },
  17023. e : function () {
  17024. return this.weekday();
  17025. },
  17026. E : function () {
  17027. return this.isoWeekday();
  17028. },
  17029. a : function () {
  17030. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17031. },
  17032. A : function () {
  17033. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17034. },
  17035. H : function () {
  17036. return this.hours();
  17037. },
  17038. h : function () {
  17039. return this.hours() % 12 || 12;
  17040. },
  17041. m : function () {
  17042. return this.minutes();
  17043. },
  17044. s : function () {
  17045. return this.seconds();
  17046. },
  17047. S : function () {
  17048. return toInt(this.milliseconds() / 100);
  17049. },
  17050. SS : function () {
  17051. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17052. },
  17053. SSS : function () {
  17054. return leftZeroFill(this.milliseconds(), 3);
  17055. },
  17056. SSSS : function () {
  17057. return leftZeroFill(this.milliseconds(), 3);
  17058. },
  17059. Z : function () {
  17060. var a = -this.zone(),
  17061. b = "+";
  17062. if (a < 0) {
  17063. a = -a;
  17064. b = "-";
  17065. }
  17066. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17067. },
  17068. ZZ : function () {
  17069. var a = -this.zone(),
  17070. b = "+";
  17071. if (a < 0) {
  17072. a = -a;
  17073. b = "-";
  17074. }
  17075. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17076. },
  17077. z : function () {
  17078. return this.zoneAbbr();
  17079. },
  17080. zz : function () {
  17081. return this.zoneName();
  17082. },
  17083. X : function () {
  17084. return this.unix();
  17085. },
  17086. Q : function () {
  17087. return this.quarter();
  17088. }
  17089. },
  17090. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17091. function defaultParsingFlags() {
  17092. // We need to deep clone this object, and es5 standard is not very
  17093. // helpful.
  17094. return {
  17095. empty : false,
  17096. unusedTokens : [],
  17097. unusedInput : [],
  17098. overflow : -2,
  17099. charsLeftOver : 0,
  17100. nullInput : false,
  17101. invalidMonth : null,
  17102. invalidFormat : false,
  17103. userInvalidated : false,
  17104. iso: false
  17105. };
  17106. }
  17107. function deprecate(msg, fn) {
  17108. var firstTime = true;
  17109. function printMsg() {
  17110. if (moment.suppressDeprecationWarnings === false &&
  17111. typeof console !== 'undefined' && console.warn) {
  17112. console.warn("Deprecation warning: " + msg);
  17113. }
  17114. }
  17115. return extend(function () {
  17116. if (firstTime) {
  17117. printMsg();
  17118. firstTime = false;
  17119. }
  17120. return fn.apply(this, arguments);
  17121. }, fn);
  17122. }
  17123. function padToken(func, count) {
  17124. return function (a) {
  17125. return leftZeroFill(func.call(this, a), count);
  17126. };
  17127. }
  17128. function ordinalizeToken(func, period) {
  17129. return function (a) {
  17130. return this.lang().ordinal(func.call(this, a), period);
  17131. };
  17132. }
  17133. while (ordinalizeTokens.length) {
  17134. i = ordinalizeTokens.pop();
  17135. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17136. }
  17137. while (paddedTokens.length) {
  17138. i = paddedTokens.pop();
  17139. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17140. }
  17141. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17142. /************************************
  17143. Constructors
  17144. ************************************/
  17145. function Language() {
  17146. }
  17147. // Moment prototype object
  17148. function Moment(config) {
  17149. checkOverflow(config);
  17150. extend(this, config);
  17151. }
  17152. // Duration Constructor
  17153. function Duration(duration) {
  17154. var normalizedInput = normalizeObjectUnits(duration),
  17155. years = normalizedInput.year || 0,
  17156. quarters = normalizedInput.quarter || 0,
  17157. months = normalizedInput.month || 0,
  17158. weeks = normalizedInput.week || 0,
  17159. days = normalizedInput.day || 0,
  17160. hours = normalizedInput.hour || 0,
  17161. minutes = normalizedInput.minute || 0,
  17162. seconds = normalizedInput.second || 0,
  17163. milliseconds = normalizedInput.millisecond || 0;
  17164. // representation for dateAddRemove
  17165. this._milliseconds = +milliseconds +
  17166. seconds * 1e3 + // 1000
  17167. minutes * 6e4 + // 1000 * 60
  17168. hours * 36e5; // 1000 * 60 * 60
  17169. // Because of dateAddRemove treats 24 hours as different from a
  17170. // day when working around DST, we need to store them separately
  17171. this._days = +days +
  17172. weeks * 7;
  17173. // It is impossible translate months into days without knowing
  17174. // which months you are are talking about, so we have to store
  17175. // it separately.
  17176. this._months = +months +
  17177. quarters * 3 +
  17178. years * 12;
  17179. this._data = {};
  17180. this._bubble();
  17181. }
  17182. /************************************
  17183. Helpers
  17184. ************************************/
  17185. function extend(a, b) {
  17186. for (var i in b) {
  17187. if (b.hasOwnProperty(i)) {
  17188. a[i] = b[i];
  17189. }
  17190. }
  17191. if (b.hasOwnProperty("toString")) {
  17192. a.toString = b.toString;
  17193. }
  17194. if (b.hasOwnProperty("valueOf")) {
  17195. a.valueOf = b.valueOf;
  17196. }
  17197. return a;
  17198. }
  17199. function cloneMoment(m) {
  17200. var result = {}, i;
  17201. for (i in m) {
  17202. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17203. result[i] = m[i];
  17204. }
  17205. }
  17206. return result;
  17207. }
  17208. function absRound(number) {
  17209. if (number < 0) {
  17210. return Math.ceil(number);
  17211. } else {
  17212. return Math.floor(number);
  17213. }
  17214. }
  17215. // left zero fill a number
  17216. // see http://jsperf.com/left-zero-filling for performance comparison
  17217. function leftZeroFill(number, targetLength, forceSign) {
  17218. var output = '' + Math.abs(number),
  17219. sign = number >= 0;
  17220. while (output.length < targetLength) {
  17221. output = '0' + output;
  17222. }
  17223. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17224. }
  17225. // helper function for _.addTime and _.subtractTime
  17226. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17227. var milliseconds = duration._milliseconds,
  17228. days = duration._days,
  17229. months = duration._months;
  17230. updateOffset = updateOffset == null ? true : updateOffset;
  17231. if (milliseconds) {
  17232. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17233. }
  17234. if (days) {
  17235. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17236. }
  17237. if (months) {
  17238. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17239. }
  17240. if (updateOffset) {
  17241. moment.updateOffset(mom, days || months);
  17242. }
  17243. }
  17244. // check if is an array
  17245. function isArray(input) {
  17246. return Object.prototype.toString.call(input) === '[object Array]';
  17247. }
  17248. function isDate(input) {
  17249. return Object.prototype.toString.call(input) === '[object Date]' ||
  17250. input instanceof Date;
  17251. }
  17252. // compare two arrays, return the number of differences
  17253. function compareArrays(array1, array2, dontConvert) {
  17254. var len = Math.min(array1.length, array2.length),
  17255. lengthDiff = Math.abs(array1.length - array2.length),
  17256. diffs = 0,
  17257. i;
  17258. for (i = 0; i < len; i++) {
  17259. if ((dontConvert && array1[i] !== array2[i]) ||
  17260. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17261. diffs++;
  17262. }
  17263. }
  17264. return diffs + lengthDiff;
  17265. }
  17266. function normalizeUnits(units) {
  17267. if (units) {
  17268. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17269. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17270. }
  17271. return units;
  17272. }
  17273. function normalizeObjectUnits(inputObject) {
  17274. var normalizedInput = {},
  17275. normalizedProp,
  17276. prop;
  17277. for (prop in inputObject) {
  17278. if (inputObject.hasOwnProperty(prop)) {
  17279. normalizedProp = normalizeUnits(prop);
  17280. if (normalizedProp) {
  17281. normalizedInput[normalizedProp] = inputObject[prop];
  17282. }
  17283. }
  17284. }
  17285. return normalizedInput;
  17286. }
  17287. function makeList(field) {
  17288. var count, setter;
  17289. if (field.indexOf('week') === 0) {
  17290. count = 7;
  17291. setter = 'day';
  17292. }
  17293. else if (field.indexOf('month') === 0) {
  17294. count = 12;
  17295. setter = 'month';
  17296. }
  17297. else {
  17298. return;
  17299. }
  17300. moment[field] = function (format, index) {
  17301. var i, getter,
  17302. method = moment.fn._lang[field],
  17303. results = [];
  17304. if (typeof format === 'number') {
  17305. index = format;
  17306. format = undefined;
  17307. }
  17308. getter = function (i) {
  17309. var m = moment().utc().set(setter, i);
  17310. return method.call(moment.fn._lang, m, format || '');
  17311. };
  17312. if (index != null) {
  17313. return getter(index);
  17314. }
  17315. else {
  17316. for (i = 0; i < count; i++) {
  17317. results.push(getter(i));
  17318. }
  17319. return results;
  17320. }
  17321. };
  17322. }
  17323. function toInt(argumentForCoercion) {
  17324. var coercedNumber = +argumentForCoercion,
  17325. value = 0;
  17326. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17327. if (coercedNumber >= 0) {
  17328. value = Math.floor(coercedNumber);
  17329. } else {
  17330. value = Math.ceil(coercedNumber);
  17331. }
  17332. }
  17333. return value;
  17334. }
  17335. function daysInMonth(year, month) {
  17336. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17337. }
  17338. function weeksInYear(year, dow, doy) {
  17339. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17340. }
  17341. function daysInYear(year) {
  17342. return isLeapYear(year) ? 366 : 365;
  17343. }
  17344. function isLeapYear(year) {
  17345. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17346. }
  17347. function checkOverflow(m) {
  17348. var overflow;
  17349. if (m._a && m._pf.overflow === -2) {
  17350. overflow =
  17351. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17352. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17353. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17354. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17355. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17356. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17357. -1;
  17358. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17359. overflow = DATE;
  17360. }
  17361. m._pf.overflow = overflow;
  17362. }
  17363. }
  17364. function isValid(m) {
  17365. if (m._isValid == null) {
  17366. m._isValid = !isNaN(m._d.getTime()) &&
  17367. m._pf.overflow < 0 &&
  17368. !m._pf.empty &&
  17369. !m._pf.invalidMonth &&
  17370. !m._pf.nullInput &&
  17371. !m._pf.invalidFormat &&
  17372. !m._pf.userInvalidated;
  17373. if (m._strict) {
  17374. m._isValid = m._isValid &&
  17375. m._pf.charsLeftOver === 0 &&
  17376. m._pf.unusedTokens.length === 0;
  17377. }
  17378. }
  17379. return m._isValid;
  17380. }
  17381. function normalizeLanguage(key) {
  17382. return key ? key.toLowerCase().replace('_', '-') : key;
  17383. }
  17384. // Return a moment from input, that is local/utc/zone equivalent to model.
  17385. function makeAs(input, model) {
  17386. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17387. moment(input).local();
  17388. }
  17389. /************************************
  17390. Languages
  17391. ************************************/
  17392. extend(Language.prototype, {
  17393. set : function (config) {
  17394. var prop, i;
  17395. for (i in config) {
  17396. prop = config[i];
  17397. if (typeof prop === 'function') {
  17398. this[i] = prop;
  17399. } else {
  17400. this['_' + i] = prop;
  17401. }
  17402. }
  17403. },
  17404. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17405. months : function (m) {
  17406. return this._months[m.month()];
  17407. },
  17408. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17409. monthsShort : function (m) {
  17410. return this._monthsShort[m.month()];
  17411. },
  17412. monthsParse : function (monthName) {
  17413. var i, mom, regex;
  17414. if (!this._monthsParse) {
  17415. this._monthsParse = [];
  17416. }
  17417. for (i = 0; i < 12; i++) {
  17418. // make the regex if we don't have it already
  17419. if (!this._monthsParse[i]) {
  17420. mom = moment.utc([2000, i]);
  17421. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17422. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17423. }
  17424. // test the regex
  17425. if (this._monthsParse[i].test(monthName)) {
  17426. return i;
  17427. }
  17428. }
  17429. },
  17430. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17431. weekdays : function (m) {
  17432. return this._weekdays[m.day()];
  17433. },
  17434. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17435. weekdaysShort : function (m) {
  17436. return this._weekdaysShort[m.day()];
  17437. },
  17438. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17439. weekdaysMin : function (m) {
  17440. return this._weekdaysMin[m.day()];
  17441. },
  17442. weekdaysParse : function (weekdayName) {
  17443. var i, mom, regex;
  17444. if (!this._weekdaysParse) {
  17445. this._weekdaysParse = [];
  17446. }
  17447. for (i = 0; i < 7; i++) {
  17448. // make the regex if we don't have it already
  17449. if (!this._weekdaysParse[i]) {
  17450. mom = moment([2000, 1]).day(i);
  17451. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17452. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17453. }
  17454. // test the regex
  17455. if (this._weekdaysParse[i].test(weekdayName)) {
  17456. return i;
  17457. }
  17458. }
  17459. },
  17460. _longDateFormat : {
  17461. LT : "h:mm A",
  17462. L : "MM/DD/YYYY",
  17463. LL : "MMMM D YYYY",
  17464. LLL : "MMMM D YYYY LT",
  17465. LLLL : "dddd, MMMM D YYYY LT"
  17466. },
  17467. longDateFormat : function (key) {
  17468. var output = this._longDateFormat[key];
  17469. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17470. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17471. return val.slice(1);
  17472. });
  17473. this._longDateFormat[key] = output;
  17474. }
  17475. return output;
  17476. },
  17477. isPM : function (input) {
  17478. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17479. // Using charAt should be more compatible.
  17480. return ((input + '').toLowerCase().charAt(0) === 'p');
  17481. },
  17482. _meridiemParse : /[ap]\.?m?\.?/i,
  17483. meridiem : function (hours, minutes, isLower) {
  17484. if (hours > 11) {
  17485. return isLower ? 'pm' : 'PM';
  17486. } else {
  17487. return isLower ? 'am' : 'AM';
  17488. }
  17489. },
  17490. _calendar : {
  17491. sameDay : '[Today at] LT',
  17492. nextDay : '[Tomorrow at] LT',
  17493. nextWeek : 'dddd [at] LT',
  17494. lastDay : '[Yesterday at] LT',
  17495. lastWeek : '[Last] dddd [at] LT',
  17496. sameElse : 'L'
  17497. },
  17498. calendar : function (key, mom) {
  17499. var output = this._calendar[key];
  17500. return typeof output === 'function' ? output.apply(mom) : output;
  17501. },
  17502. _relativeTime : {
  17503. future : "in %s",
  17504. past : "%s ago",
  17505. s : "a few seconds",
  17506. m : "a minute",
  17507. mm : "%d minutes",
  17508. h : "an hour",
  17509. hh : "%d hours",
  17510. d : "a day",
  17511. dd : "%d days",
  17512. M : "a month",
  17513. MM : "%d months",
  17514. y : "a year",
  17515. yy : "%d years"
  17516. },
  17517. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17518. var output = this._relativeTime[string];
  17519. return (typeof output === 'function') ?
  17520. output(number, withoutSuffix, string, isFuture) :
  17521. output.replace(/%d/i, number);
  17522. },
  17523. pastFuture : function (diff, output) {
  17524. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17525. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17526. },
  17527. ordinal : function (number) {
  17528. return this._ordinal.replace("%d", number);
  17529. },
  17530. _ordinal : "%d",
  17531. preparse : function (string) {
  17532. return string;
  17533. },
  17534. postformat : function (string) {
  17535. return string;
  17536. },
  17537. week : function (mom) {
  17538. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17539. },
  17540. _week : {
  17541. dow : 0, // Sunday is the first day of the week.
  17542. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17543. },
  17544. _invalidDate: 'Invalid date',
  17545. invalidDate: function () {
  17546. return this._invalidDate;
  17547. }
  17548. });
  17549. // Loads a language definition into the `languages` cache. The function
  17550. // takes a key and optionally values. If not in the browser and no values
  17551. // are provided, it will load the language file module. As a convenience,
  17552. // this function also returns the language values.
  17553. function loadLang(key, values) {
  17554. values.abbr = key;
  17555. if (!languages[key]) {
  17556. languages[key] = new Language();
  17557. }
  17558. languages[key].set(values);
  17559. return languages[key];
  17560. }
  17561. // Remove a language from the `languages` cache. Mostly useful in tests.
  17562. function unloadLang(key) {
  17563. delete languages[key];
  17564. }
  17565. // Determines which language definition to use and returns it.
  17566. //
  17567. // With no parameters, it will return the global language. If you
  17568. // pass in a language key, such as 'en', it will return the
  17569. // definition for 'en', so long as 'en' has already been loaded using
  17570. // moment.lang.
  17571. function getLangDefinition(key) {
  17572. var i = 0, j, lang, next, split,
  17573. get = function (k) {
  17574. if (!languages[k] && hasModule) {
  17575. try {
  17576. require('./lang/' + k);
  17577. } catch (e) { }
  17578. }
  17579. return languages[k];
  17580. };
  17581. if (!key) {
  17582. return moment.fn._lang;
  17583. }
  17584. if (!isArray(key)) {
  17585. //short-circuit everything else
  17586. lang = get(key);
  17587. if (lang) {
  17588. return lang;
  17589. }
  17590. key = [key];
  17591. }
  17592. //pick the language from the array
  17593. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17594. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17595. while (i < key.length) {
  17596. split = normalizeLanguage(key[i]).split('-');
  17597. j = split.length;
  17598. next = normalizeLanguage(key[i + 1]);
  17599. next = next ? next.split('-') : null;
  17600. while (j > 0) {
  17601. lang = get(split.slice(0, j).join('-'));
  17602. if (lang) {
  17603. return lang;
  17604. }
  17605. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17606. //the next array item is better than a shallower substring of this one
  17607. break;
  17608. }
  17609. j--;
  17610. }
  17611. i++;
  17612. }
  17613. return moment.fn._lang;
  17614. }
  17615. /************************************
  17616. Formatting
  17617. ************************************/
  17618. function removeFormattingTokens(input) {
  17619. if (input.match(/\[[\s\S]/)) {
  17620. return input.replace(/^\[|\]$/g, "");
  17621. }
  17622. return input.replace(/\\/g, "");
  17623. }
  17624. function makeFormatFunction(format) {
  17625. var array = format.match(formattingTokens), i, length;
  17626. for (i = 0, length = array.length; i < length; i++) {
  17627. if (formatTokenFunctions[array[i]]) {
  17628. array[i] = formatTokenFunctions[array[i]];
  17629. } else {
  17630. array[i] = removeFormattingTokens(array[i]);
  17631. }
  17632. }
  17633. return function (mom) {
  17634. var output = "";
  17635. for (i = 0; i < length; i++) {
  17636. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17637. }
  17638. return output;
  17639. };
  17640. }
  17641. // format date using native date object
  17642. function formatMoment(m, format) {
  17643. if (!m.isValid()) {
  17644. return m.lang().invalidDate();
  17645. }
  17646. format = expandFormat(format, m.lang());
  17647. if (!formatFunctions[format]) {
  17648. formatFunctions[format] = makeFormatFunction(format);
  17649. }
  17650. return formatFunctions[format](m);
  17651. }
  17652. function expandFormat(format, lang) {
  17653. var i = 5;
  17654. function replaceLongDateFormatTokens(input) {
  17655. return lang.longDateFormat(input) || input;
  17656. }
  17657. localFormattingTokens.lastIndex = 0;
  17658. while (i >= 0 && localFormattingTokens.test(format)) {
  17659. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17660. localFormattingTokens.lastIndex = 0;
  17661. i -= 1;
  17662. }
  17663. return format;
  17664. }
  17665. /************************************
  17666. Parsing
  17667. ************************************/
  17668. // get the regex to find the next token
  17669. function getParseRegexForToken(token, config) {
  17670. var a, strict = config._strict;
  17671. switch (token) {
  17672. case 'Q':
  17673. return parseTokenOneDigit;
  17674. case 'DDDD':
  17675. return parseTokenThreeDigits;
  17676. case 'YYYY':
  17677. case 'GGGG':
  17678. case 'gggg':
  17679. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17680. case 'Y':
  17681. case 'G':
  17682. case 'g':
  17683. return parseTokenSignedNumber;
  17684. case 'YYYYYY':
  17685. case 'YYYYY':
  17686. case 'GGGGG':
  17687. case 'ggggg':
  17688. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17689. case 'S':
  17690. if (strict) { return parseTokenOneDigit; }
  17691. /* falls through */
  17692. case 'SS':
  17693. if (strict) { return parseTokenTwoDigits; }
  17694. /* falls through */
  17695. case 'SSS':
  17696. if (strict) { return parseTokenThreeDigits; }
  17697. /* falls through */
  17698. case 'DDD':
  17699. return parseTokenOneToThreeDigits;
  17700. case 'MMM':
  17701. case 'MMMM':
  17702. case 'dd':
  17703. case 'ddd':
  17704. case 'dddd':
  17705. return parseTokenWord;
  17706. case 'a':
  17707. case 'A':
  17708. return getLangDefinition(config._l)._meridiemParse;
  17709. case 'X':
  17710. return parseTokenTimestampMs;
  17711. case 'Z':
  17712. case 'ZZ':
  17713. return parseTokenTimezone;
  17714. case 'T':
  17715. return parseTokenT;
  17716. case 'SSSS':
  17717. return parseTokenDigits;
  17718. case 'MM':
  17719. case 'DD':
  17720. case 'YY':
  17721. case 'GG':
  17722. case 'gg':
  17723. case 'HH':
  17724. case 'hh':
  17725. case 'mm':
  17726. case 'ss':
  17727. case 'ww':
  17728. case 'WW':
  17729. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17730. case 'M':
  17731. case 'D':
  17732. case 'd':
  17733. case 'H':
  17734. case 'h':
  17735. case 'm':
  17736. case 's':
  17737. case 'w':
  17738. case 'W':
  17739. case 'e':
  17740. case 'E':
  17741. return parseTokenOneOrTwoDigits;
  17742. case 'Do':
  17743. return parseTokenOrdinal;
  17744. default :
  17745. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17746. return a;
  17747. }
  17748. }
  17749. function timezoneMinutesFromString(string) {
  17750. string = string || "";
  17751. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17752. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17753. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17754. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17755. return parts[0] === '+' ? -minutes : minutes;
  17756. }
  17757. // function to convert string input to date
  17758. function addTimeToArrayFromToken(token, input, config) {
  17759. var a, datePartArray = config._a;
  17760. switch (token) {
  17761. // QUARTER
  17762. case 'Q':
  17763. if (input != null) {
  17764. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  17765. }
  17766. break;
  17767. // MONTH
  17768. case 'M' : // fall through to MM
  17769. case 'MM' :
  17770. if (input != null) {
  17771. datePartArray[MONTH] = toInt(input) - 1;
  17772. }
  17773. break;
  17774. case 'MMM' : // fall through to MMMM
  17775. case 'MMMM' :
  17776. a = getLangDefinition(config._l).monthsParse(input);
  17777. // if we didn't find a month name, mark the date as invalid.
  17778. if (a != null) {
  17779. datePartArray[MONTH] = a;
  17780. } else {
  17781. config._pf.invalidMonth = input;
  17782. }
  17783. break;
  17784. // DAY OF MONTH
  17785. case 'D' : // fall through to DD
  17786. case 'DD' :
  17787. if (input != null) {
  17788. datePartArray[DATE] = toInt(input);
  17789. }
  17790. break;
  17791. case 'Do' :
  17792. if (input != null) {
  17793. datePartArray[DATE] = toInt(parseInt(input, 10));
  17794. }
  17795. break;
  17796. // DAY OF YEAR
  17797. case 'DDD' : // fall through to DDDD
  17798. case 'DDDD' :
  17799. if (input != null) {
  17800. config._dayOfYear = toInt(input);
  17801. }
  17802. break;
  17803. // YEAR
  17804. case 'YY' :
  17805. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  17806. break;
  17807. case 'YYYY' :
  17808. case 'YYYYY' :
  17809. case 'YYYYYY' :
  17810. datePartArray[YEAR] = toInt(input);
  17811. break;
  17812. // AM / PM
  17813. case 'a' : // fall through to A
  17814. case 'A' :
  17815. config._isPm = getLangDefinition(config._l).isPM(input);
  17816. break;
  17817. // 24 HOUR
  17818. case 'H' : // fall through to hh
  17819. case 'HH' : // fall through to hh
  17820. case 'h' : // fall through to hh
  17821. case 'hh' :
  17822. datePartArray[HOUR] = toInt(input);
  17823. break;
  17824. // MINUTE
  17825. case 'm' : // fall through to mm
  17826. case 'mm' :
  17827. datePartArray[MINUTE] = toInt(input);
  17828. break;
  17829. // SECOND
  17830. case 's' : // fall through to ss
  17831. case 'ss' :
  17832. datePartArray[SECOND] = toInt(input);
  17833. break;
  17834. // MILLISECOND
  17835. case 'S' :
  17836. case 'SS' :
  17837. case 'SSS' :
  17838. case 'SSSS' :
  17839. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17840. break;
  17841. // UNIX TIMESTAMP WITH MS
  17842. case 'X':
  17843. config._d = new Date(parseFloat(input) * 1000);
  17844. break;
  17845. // TIMEZONE
  17846. case 'Z' : // fall through to ZZ
  17847. case 'ZZ' :
  17848. config._useUTC = true;
  17849. config._tzm = timezoneMinutesFromString(input);
  17850. break;
  17851. case 'w':
  17852. case 'ww':
  17853. case 'W':
  17854. case 'WW':
  17855. case 'd':
  17856. case 'dd':
  17857. case 'ddd':
  17858. case 'dddd':
  17859. case 'e':
  17860. case 'E':
  17861. token = token.substr(0, 1);
  17862. /* falls through */
  17863. case 'gg':
  17864. case 'gggg':
  17865. case 'GG':
  17866. case 'GGGG':
  17867. case 'GGGGG':
  17868. token = token.substr(0, 2);
  17869. if (input) {
  17870. config._w = config._w || {};
  17871. config._w[token] = input;
  17872. }
  17873. break;
  17874. }
  17875. }
  17876. // convert an array to a date.
  17877. // the array should mirror the parameters below
  17878. // note: all values past the year are optional and will default to the lowest possible value.
  17879. // [year, month, day , hour, minute, second, millisecond]
  17880. function dateFromConfig(config) {
  17881. var i, date, input = [], currentDate,
  17882. yearToUse, fixYear, w, temp, lang, weekday, week;
  17883. if (config._d) {
  17884. return;
  17885. }
  17886. currentDate = currentDateArray(config);
  17887. //compute day of the year from weeks and weekdays
  17888. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17889. fixYear = function (val) {
  17890. var intVal = parseInt(val, 10);
  17891. return val ?
  17892. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  17893. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17894. };
  17895. w = config._w;
  17896. if (w.GG != null || w.W != null || w.E != null) {
  17897. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17898. }
  17899. else {
  17900. lang = getLangDefinition(config._l);
  17901. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17902. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17903. week = parseInt(w.w, 10) || 1;
  17904. //if we're parsing 'd', then the low day numbers may be next week
  17905. if (w.d != null && weekday < lang._week.dow) {
  17906. week++;
  17907. }
  17908. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17909. }
  17910. config._a[YEAR] = temp.year;
  17911. config._dayOfYear = temp.dayOfYear;
  17912. }
  17913. //if the day of the year is set, figure out what it is
  17914. if (config._dayOfYear) {
  17915. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17916. if (config._dayOfYear > daysInYear(yearToUse)) {
  17917. config._pf._overflowDayOfYear = true;
  17918. }
  17919. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17920. config._a[MONTH] = date.getUTCMonth();
  17921. config._a[DATE] = date.getUTCDate();
  17922. }
  17923. // Default to current date.
  17924. // * if no year, month, day of month are given, default to today
  17925. // * if day of month is given, default month and year
  17926. // * if month is given, default only year
  17927. // * if year is given, don't default anything
  17928. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17929. config._a[i] = input[i] = currentDate[i];
  17930. }
  17931. // Zero out whatever was not defaulted, including time
  17932. for (; i < 7; i++) {
  17933. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  17934. }
  17935. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  17936. input[HOUR] += toInt((config._tzm || 0) / 60);
  17937. input[MINUTE] += toInt((config._tzm || 0) % 60);
  17938. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  17939. }
  17940. function dateFromObject(config) {
  17941. var normalizedInput;
  17942. if (config._d) {
  17943. return;
  17944. }
  17945. normalizedInput = normalizeObjectUnits(config._i);
  17946. config._a = [
  17947. normalizedInput.year,
  17948. normalizedInput.month,
  17949. normalizedInput.day,
  17950. normalizedInput.hour,
  17951. normalizedInput.minute,
  17952. normalizedInput.second,
  17953. normalizedInput.millisecond
  17954. ];
  17955. dateFromConfig(config);
  17956. }
  17957. function currentDateArray(config) {
  17958. var now = new Date();
  17959. if (config._useUTC) {
  17960. return [
  17961. now.getUTCFullYear(),
  17962. now.getUTCMonth(),
  17963. now.getUTCDate()
  17964. ];
  17965. } else {
  17966. return [now.getFullYear(), now.getMonth(), now.getDate()];
  17967. }
  17968. }
  17969. // date from string and format string
  17970. function makeDateFromStringAndFormat(config) {
  17971. config._a = [];
  17972. config._pf.empty = true;
  17973. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  17974. var lang = getLangDefinition(config._l),
  17975. string = '' + config._i,
  17976. i, parsedInput, tokens, token, skipped,
  17977. stringLength = string.length,
  17978. totalParsedInputLength = 0;
  17979. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  17980. for (i = 0; i < tokens.length; i++) {
  17981. token = tokens[i];
  17982. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  17983. if (parsedInput) {
  17984. skipped = string.substr(0, string.indexOf(parsedInput));
  17985. if (skipped.length > 0) {
  17986. config._pf.unusedInput.push(skipped);
  17987. }
  17988. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  17989. totalParsedInputLength += parsedInput.length;
  17990. }
  17991. // don't parse if it's not a known token
  17992. if (formatTokenFunctions[token]) {
  17993. if (parsedInput) {
  17994. config._pf.empty = false;
  17995. }
  17996. else {
  17997. config._pf.unusedTokens.push(token);
  17998. }
  17999. addTimeToArrayFromToken(token, parsedInput, config);
  18000. }
  18001. else if (config._strict && !parsedInput) {
  18002. config._pf.unusedTokens.push(token);
  18003. }
  18004. }
  18005. // add remaining unparsed input length to the string
  18006. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18007. if (string.length > 0) {
  18008. config._pf.unusedInput.push(string);
  18009. }
  18010. // handle am pm
  18011. if (config._isPm && config._a[HOUR] < 12) {
  18012. config._a[HOUR] += 12;
  18013. }
  18014. // if is 12 am, change hours to 0
  18015. if (config._isPm === false && config._a[HOUR] === 12) {
  18016. config._a[HOUR] = 0;
  18017. }
  18018. dateFromConfig(config);
  18019. checkOverflow(config);
  18020. }
  18021. function unescapeFormat(s) {
  18022. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18023. return p1 || p2 || p3 || p4;
  18024. });
  18025. }
  18026. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18027. function regexpEscape(s) {
  18028. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18029. }
  18030. // date from string and array of format strings
  18031. function makeDateFromStringAndArray(config) {
  18032. var tempConfig,
  18033. bestMoment,
  18034. scoreToBeat,
  18035. i,
  18036. currentScore;
  18037. if (config._f.length === 0) {
  18038. config._pf.invalidFormat = true;
  18039. config._d = new Date(NaN);
  18040. return;
  18041. }
  18042. for (i = 0; i < config._f.length; i++) {
  18043. currentScore = 0;
  18044. tempConfig = extend({}, config);
  18045. tempConfig._pf = defaultParsingFlags();
  18046. tempConfig._f = config._f[i];
  18047. makeDateFromStringAndFormat(tempConfig);
  18048. if (!isValid(tempConfig)) {
  18049. continue;
  18050. }
  18051. // if there is any input that was not parsed add a penalty for that format
  18052. currentScore += tempConfig._pf.charsLeftOver;
  18053. //or tokens
  18054. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18055. tempConfig._pf.score = currentScore;
  18056. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18057. scoreToBeat = currentScore;
  18058. bestMoment = tempConfig;
  18059. }
  18060. }
  18061. extend(config, bestMoment || tempConfig);
  18062. }
  18063. // date from iso format
  18064. function makeDateFromString(config) {
  18065. var i, l,
  18066. string = config._i,
  18067. match = isoRegex.exec(string);
  18068. if (match) {
  18069. config._pf.iso = true;
  18070. for (i = 0, l = isoDates.length; i < l; i++) {
  18071. if (isoDates[i][1].exec(string)) {
  18072. // match[5] should be "T" or undefined
  18073. config._f = isoDates[i][0] + (match[6] || " ");
  18074. break;
  18075. }
  18076. }
  18077. for (i = 0, l = isoTimes.length; i < l; i++) {
  18078. if (isoTimes[i][1].exec(string)) {
  18079. config._f += isoTimes[i][0];
  18080. break;
  18081. }
  18082. }
  18083. if (string.match(parseTokenTimezone)) {
  18084. config._f += "Z";
  18085. }
  18086. makeDateFromStringAndFormat(config);
  18087. }
  18088. else {
  18089. moment.createFromInputFallback(config);
  18090. }
  18091. }
  18092. function makeDateFromInput(config) {
  18093. var input = config._i,
  18094. matched = aspNetJsonRegex.exec(input);
  18095. if (input === undefined) {
  18096. config._d = new Date();
  18097. } else if (matched) {
  18098. config._d = new Date(+matched[1]);
  18099. } else if (typeof input === 'string') {
  18100. makeDateFromString(config);
  18101. } else if (isArray(input)) {
  18102. config._a = input.slice(0);
  18103. dateFromConfig(config);
  18104. } else if (isDate(input)) {
  18105. config._d = new Date(+input);
  18106. } else if (typeof(input) === 'object') {
  18107. dateFromObject(config);
  18108. } else if (typeof(input) === 'number') {
  18109. // from milliseconds
  18110. config._d = new Date(input);
  18111. } else {
  18112. moment.createFromInputFallback(config);
  18113. }
  18114. }
  18115. function makeDate(y, m, d, h, M, s, ms) {
  18116. //can't just apply() to create a date:
  18117. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18118. var date = new Date(y, m, d, h, M, s, ms);
  18119. //the date constructor doesn't accept years < 1970
  18120. if (y < 1970) {
  18121. date.setFullYear(y);
  18122. }
  18123. return date;
  18124. }
  18125. function makeUTCDate(y) {
  18126. var date = new Date(Date.UTC.apply(null, arguments));
  18127. if (y < 1970) {
  18128. date.setUTCFullYear(y);
  18129. }
  18130. return date;
  18131. }
  18132. function parseWeekday(input, language) {
  18133. if (typeof input === 'string') {
  18134. if (!isNaN(input)) {
  18135. input = parseInt(input, 10);
  18136. }
  18137. else {
  18138. input = language.weekdaysParse(input);
  18139. if (typeof input !== 'number') {
  18140. return null;
  18141. }
  18142. }
  18143. }
  18144. return input;
  18145. }
  18146. /************************************
  18147. Relative Time
  18148. ************************************/
  18149. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18150. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18151. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18152. }
  18153. function relativeTime(milliseconds, withoutSuffix, lang) {
  18154. var seconds = round(Math.abs(milliseconds) / 1000),
  18155. minutes = round(seconds / 60),
  18156. hours = round(minutes / 60),
  18157. days = round(hours / 24),
  18158. years = round(days / 365),
  18159. args = seconds < 45 && ['s', seconds] ||
  18160. minutes === 1 && ['m'] ||
  18161. minutes < 45 && ['mm', minutes] ||
  18162. hours === 1 && ['h'] ||
  18163. hours < 22 && ['hh', hours] ||
  18164. days === 1 && ['d'] ||
  18165. days <= 25 && ['dd', days] ||
  18166. days <= 45 && ['M'] ||
  18167. days < 345 && ['MM', round(days / 30)] ||
  18168. years === 1 && ['y'] || ['yy', years];
  18169. args[2] = withoutSuffix;
  18170. args[3] = milliseconds > 0;
  18171. args[4] = lang;
  18172. return substituteTimeAgo.apply({}, args);
  18173. }
  18174. /************************************
  18175. Week of Year
  18176. ************************************/
  18177. // firstDayOfWeek 0 = sun, 6 = sat
  18178. // the day of the week that starts the week
  18179. // (usually sunday or monday)
  18180. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18181. // the first week is the week that contains the first
  18182. // of this day of the week
  18183. // (eg. ISO weeks use thursday (4))
  18184. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18185. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18186. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18187. adjustedMoment;
  18188. if (daysToDayOfWeek > end) {
  18189. daysToDayOfWeek -= 7;
  18190. }
  18191. if (daysToDayOfWeek < end - 7) {
  18192. daysToDayOfWeek += 7;
  18193. }
  18194. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18195. return {
  18196. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18197. year: adjustedMoment.year()
  18198. };
  18199. }
  18200. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18201. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18202. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18203. weekday = weekday != null ? weekday : firstDayOfWeek;
  18204. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18205. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18206. return {
  18207. year: dayOfYear > 0 ? year : year - 1,
  18208. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18209. };
  18210. }
  18211. /************************************
  18212. Top Level Functions
  18213. ************************************/
  18214. function makeMoment(config) {
  18215. var input = config._i,
  18216. format = config._f;
  18217. if (input === null || (format === undefined && input === '')) {
  18218. return moment.invalid({nullInput: true});
  18219. }
  18220. if (typeof input === 'string') {
  18221. config._i = input = getLangDefinition().preparse(input);
  18222. }
  18223. if (moment.isMoment(input)) {
  18224. config = cloneMoment(input);
  18225. config._d = new Date(+input._d);
  18226. } else if (format) {
  18227. if (isArray(format)) {
  18228. makeDateFromStringAndArray(config);
  18229. } else {
  18230. makeDateFromStringAndFormat(config);
  18231. }
  18232. } else {
  18233. makeDateFromInput(config);
  18234. }
  18235. return new Moment(config);
  18236. }
  18237. moment = function (input, format, lang, strict) {
  18238. var c;
  18239. if (typeof(lang) === "boolean") {
  18240. strict = lang;
  18241. lang = undefined;
  18242. }
  18243. // object construction must be done this way.
  18244. // https://github.com/moment/moment/issues/1423
  18245. c = {};
  18246. c._isAMomentObject = true;
  18247. c._i = input;
  18248. c._f = format;
  18249. c._l = lang;
  18250. c._strict = strict;
  18251. c._isUTC = false;
  18252. c._pf = defaultParsingFlags();
  18253. return makeMoment(c);
  18254. };
  18255. moment.suppressDeprecationWarnings = false;
  18256. moment.createFromInputFallback = deprecate(
  18257. "moment construction falls back to js Date. This is " +
  18258. "discouraged and will be removed in upcoming major " +
  18259. "release. Please refer to " +
  18260. "https://github.com/moment/moment/issues/1407 for more info.",
  18261. function (config) {
  18262. config._d = new Date(config._i);
  18263. });
  18264. // creating with utc
  18265. moment.utc = function (input, format, lang, strict) {
  18266. var c;
  18267. if (typeof(lang) === "boolean") {
  18268. strict = lang;
  18269. lang = undefined;
  18270. }
  18271. // object construction must be done this way.
  18272. // https://github.com/moment/moment/issues/1423
  18273. c = {};
  18274. c._isAMomentObject = true;
  18275. c._useUTC = true;
  18276. c._isUTC = true;
  18277. c._l = lang;
  18278. c._i = input;
  18279. c._f = format;
  18280. c._strict = strict;
  18281. c._pf = defaultParsingFlags();
  18282. return makeMoment(c).utc();
  18283. };
  18284. // creating with unix timestamp (in seconds)
  18285. moment.unix = function (input) {
  18286. return moment(input * 1000);
  18287. };
  18288. // duration
  18289. moment.duration = function (input, key) {
  18290. var duration = input,
  18291. // matching against regexp is expensive, do it on demand
  18292. match = null,
  18293. sign,
  18294. ret,
  18295. parseIso;
  18296. if (moment.isDuration(input)) {
  18297. duration = {
  18298. ms: input._milliseconds,
  18299. d: input._days,
  18300. M: input._months
  18301. };
  18302. } else if (typeof input === 'number') {
  18303. duration = {};
  18304. if (key) {
  18305. duration[key] = input;
  18306. } else {
  18307. duration.milliseconds = input;
  18308. }
  18309. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18310. sign = (match[1] === "-") ? -1 : 1;
  18311. duration = {
  18312. y: 0,
  18313. d: toInt(match[DATE]) * sign,
  18314. h: toInt(match[HOUR]) * sign,
  18315. m: toInt(match[MINUTE]) * sign,
  18316. s: toInt(match[SECOND]) * sign,
  18317. ms: toInt(match[MILLISECOND]) * sign
  18318. };
  18319. } else if (!!(match = isoDurationRegex.exec(input))) {
  18320. sign = (match[1] === "-") ? -1 : 1;
  18321. parseIso = function (inp) {
  18322. // We'd normally use ~~inp for this, but unfortunately it also
  18323. // converts floats to ints.
  18324. // inp may be undefined, so careful calling replace on it.
  18325. var res = inp && parseFloat(inp.replace(',', '.'));
  18326. // apply sign while we're at it
  18327. return (isNaN(res) ? 0 : res) * sign;
  18328. };
  18329. duration = {
  18330. y: parseIso(match[2]),
  18331. M: parseIso(match[3]),
  18332. d: parseIso(match[4]),
  18333. h: parseIso(match[5]),
  18334. m: parseIso(match[6]),
  18335. s: parseIso(match[7]),
  18336. w: parseIso(match[8])
  18337. };
  18338. }
  18339. ret = new Duration(duration);
  18340. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18341. ret._lang = input._lang;
  18342. }
  18343. return ret;
  18344. };
  18345. // version number
  18346. moment.version = VERSION;
  18347. // default format
  18348. moment.defaultFormat = isoFormat;
  18349. // Plugins that add properties should also add the key here (null value),
  18350. // so we can properly clone ourselves.
  18351. moment.momentProperties = momentProperties;
  18352. // This function will be called whenever a moment is mutated.
  18353. // It is intended to keep the offset in sync with the timezone.
  18354. moment.updateOffset = function () {};
  18355. // This function will load languages and then set the global language. If
  18356. // no arguments are passed in, it will simply return the current global
  18357. // language key.
  18358. moment.lang = function (key, values) {
  18359. var r;
  18360. if (!key) {
  18361. return moment.fn._lang._abbr;
  18362. }
  18363. if (values) {
  18364. loadLang(normalizeLanguage(key), values);
  18365. } else if (values === null) {
  18366. unloadLang(key);
  18367. key = 'en';
  18368. } else if (!languages[key]) {
  18369. getLangDefinition(key);
  18370. }
  18371. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18372. return r._abbr;
  18373. };
  18374. // returns language data
  18375. moment.langData = function (key) {
  18376. if (key && key._lang && key._lang._abbr) {
  18377. key = key._lang._abbr;
  18378. }
  18379. return getLangDefinition(key);
  18380. };
  18381. // compare moment object
  18382. moment.isMoment = function (obj) {
  18383. return obj instanceof Moment ||
  18384. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18385. };
  18386. // for typechecking Duration objects
  18387. moment.isDuration = function (obj) {
  18388. return obj instanceof Duration;
  18389. };
  18390. for (i = lists.length - 1; i >= 0; --i) {
  18391. makeList(lists[i]);
  18392. }
  18393. moment.normalizeUnits = function (units) {
  18394. return normalizeUnits(units);
  18395. };
  18396. moment.invalid = function (flags) {
  18397. var m = moment.utc(NaN);
  18398. if (flags != null) {
  18399. extend(m._pf, flags);
  18400. }
  18401. else {
  18402. m._pf.userInvalidated = true;
  18403. }
  18404. return m;
  18405. };
  18406. moment.parseZone = function () {
  18407. return moment.apply(null, arguments).parseZone();
  18408. };
  18409. moment.parseTwoDigitYear = function (input) {
  18410. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18411. };
  18412. /************************************
  18413. Moment Prototype
  18414. ************************************/
  18415. extend(moment.fn = Moment.prototype, {
  18416. clone : function () {
  18417. return moment(this);
  18418. },
  18419. valueOf : function () {
  18420. return +this._d + ((this._offset || 0) * 60000);
  18421. },
  18422. unix : function () {
  18423. return Math.floor(+this / 1000);
  18424. },
  18425. toString : function () {
  18426. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18427. },
  18428. toDate : function () {
  18429. return this._offset ? new Date(+this) : this._d;
  18430. },
  18431. toISOString : function () {
  18432. var m = moment(this).utc();
  18433. if (0 < m.year() && m.year() <= 9999) {
  18434. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18435. } else {
  18436. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18437. }
  18438. },
  18439. toArray : function () {
  18440. var m = this;
  18441. return [
  18442. m.year(),
  18443. m.month(),
  18444. m.date(),
  18445. m.hours(),
  18446. m.minutes(),
  18447. m.seconds(),
  18448. m.milliseconds()
  18449. ];
  18450. },
  18451. isValid : function () {
  18452. return isValid(this);
  18453. },
  18454. isDSTShifted : function () {
  18455. if (this._a) {
  18456. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18457. }
  18458. return false;
  18459. },
  18460. parsingFlags : function () {
  18461. return extend({}, this._pf);
  18462. },
  18463. invalidAt: function () {
  18464. return this._pf.overflow;
  18465. },
  18466. utc : function () {
  18467. return this.zone(0);
  18468. },
  18469. local : function () {
  18470. this.zone(0);
  18471. this._isUTC = false;
  18472. return this;
  18473. },
  18474. format : function (inputString) {
  18475. var output = formatMoment(this, inputString || moment.defaultFormat);
  18476. return this.lang().postformat(output);
  18477. },
  18478. add : function (input, val) {
  18479. var dur;
  18480. // switch args to support add('s', 1) and add(1, 's')
  18481. if (typeof input === 'string') {
  18482. dur = moment.duration(+val, input);
  18483. } else {
  18484. dur = moment.duration(input, val);
  18485. }
  18486. addOrSubtractDurationFromMoment(this, dur, 1);
  18487. return this;
  18488. },
  18489. subtract : function (input, val) {
  18490. var dur;
  18491. // switch args to support subtract('s', 1) and subtract(1, 's')
  18492. if (typeof input === 'string') {
  18493. dur = moment.duration(+val, input);
  18494. } else {
  18495. dur = moment.duration(input, val);
  18496. }
  18497. addOrSubtractDurationFromMoment(this, dur, -1);
  18498. return this;
  18499. },
  18500. diff : function (input, units, asFloat) {
  18501. var that = makeAs(input, this),
  18502. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18503. diff, output;
  18504. units = normalizeUnits(units);
  18505. if (units === 'year' || units === 'month') {
  18506. // average number of days in the months in the given dates
  18507. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18508. // difference in months
  18509. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18510. // adjust by taking difference in days, average number of days
  18511. // and dst in the given months.
  18512. output += ((this - moment(this).startOf('month')) -
  18513. (that - moment(that).startOf('month'))) / diff;
  18514. // same as above but with zones, to negate all dst
  18515. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18516. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18517. if (units === 'year') {
  18518. output = output / 12;
  18519. }
  18520. } else {
  18521. diff = (this - that);
  18522. output = units === 'second' ? diff / 1e3 : // 1000
  18523. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18524. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18525. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18526. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18527. diff;
  18528. }
  18529. return asFloat ? output : absRound(output);
  18530. },
  18531. from : function (time, withoutSuffix) {
  18532. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18533. },
  18534. fromNow : function (withoutSuffix) {
  18535. return this.from(moment(), withoutSuffix);
  18536. },
  18537. calendar : function () {
  18538. // We want to compare the start of today, vs this.
  18539. // Getting start-of-today depends on whether we're zone'd or not.
  18540. var sod = makeAs(moment(), this).startOf('day'),
  18541. diff = this.diff(sod, 'days', true),
  18542. format = diff < -6 ? 'sameElse' :
  18543. diff < -1 ? 'lastWeek' :
  18544. diff < 0 ? 'lastDay' :
  18545. diff < 1 ? 'sameDay' :
  18546. diff < 2 ? 'nextDay' :
  18547. diff < 7 ? 'nextWeek' : 'sameElse';
  18548. return this.format(this.lang().calendar(format, this));
  18549. },
  18550. isLeapYear : function () {
  18551. return isLeapYear(this.year());
  18552. },
  18553. isDST : function () {
  18554. return (this.zone() < this.clone().month(0).zone() ||
  18555. this.zone() < this.clone().month(5).zone());
  18556. },
  18557. day : function (input) {
  18558. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18559. if (input != null) {
  18560. input = parseWeekday(input, this.lang());
  18561. return this.add({ d : input - day });
  18562. } else {
  18563. return day;
  18564. }
  18565. },
  18566. month : makeAccessor('Month', true),
  18567. startOf: function (units) {
  18568. units = normalizeUnits(units);
  18569. // the following switch intentionally omits break keywords
  18570. // to utilize falling through the cases.
  18571. switch (units) {
  18572. case 'year':
  18573. this.month(0);
  18574. /* falls through */
  18575. case 'quarter':
  18576. case 'month':
  18577. this.date(1);
  18578. /* falls through */
  18579. case 'week':
  18580. case 'isoWeek':
  18581. case 'day':
  18582. this.hours(0);
  18583. /* falls through */
  18584. case 'hour':
  18585. this.minutes(0);
  18586. /* falls through */
  18587. case 'minute':
  18588. this.seconds(0);
  18589. /* falls through */
  18590. case 'second':
  18591. this.milliseconds(0);
  18592. /* falls through */
  18593. }
  18594. // weeks are a special case
  18595. if (units === 'week') {
  18596. this.weekday(0);
  18597. } else if (units === 'isoWeek') {
  18598. this.isoWeekday(1);
  18599. }
  18600. // quarters are also special
  18601. if (units === 'quarter') {
  18602. this.month(Math.floor(this.month() / 3) * 3);
  18603. }
  18604. return this;
  18605. },
  18606. endOf: function (units) {
  18607. units = normalizeUnits(units);
  18608. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18609. },
  18610. isAfter: function (input, units) {
  18611. units = typeof units !== 'undefined' ? units : 'millisecond';
  18612. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18613. },
  18614. isBefore: function (input, units) {
  18615. units = typeof units !== 'undefined' ? units : 'millisecond';
  18616. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18617. },
  18618. isSame: function (input, units) {
  18619. units = units || 'ms';
  18620. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18621. },
  18622. min: function (other) {
  18623. other = moment.apply(null, arguments);
  18624. return other < this ? this : other;
  18625. },
  18626. max: function (other) {
  18627. other = moment.apply(null, arguments);
  18628. return other > this ? this : other;
  18629. },
  18630. // keepTime = true means only change the timezone, without affecting
  18631. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18632. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18633. // adjust the time as needed, to be valid.
  18634. //
  18635. // Keeping the time actually adds/subtracts (one hour)
  18636. // from the actual represented time. That is why we call updateOffset
  18637. // a second time. In case it wants us to change the offset again
  18638. // _changeInProgress == true case, then we have to adjust, because
  18639. // there is no such time in the given timezone.
  18640. zone : function (input, keepTime) {
  18641. var offset = this._offset || 0;
  18642. if (input != null) {
  18643. if (typeof input === "string") {
  18644. input = timezoneMinutesFromString(input);
  18645. }
  18646. if (Math.abs(input) < 16) {
  18647. input = input * 60;
  18648. }
  18649. this._offset = input;
  18650. this._isUTC = true;
  18651. if (offset !== input) {
  18652. if (!keepTime || this._changeInProgress) {
  18653. addOrSubtractDurationFromMoment(this,
  18654. moment.duration(offset - input, 'm'), 1, false);
  18655. } else if (!this._changeInProgress) {
  18656. this._changeInProgress = true;
  18657. moment.updateOffset(this, true);
  18658. this._changeInProgress = null;
  18659. }
  18660. }
  18661. } else {
  18662. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18663. }
  18664. return this;
  18665. },
  18666. zoneAbbr : function () {
  18667. return this._isUTC ? "UTC" : "";
  18668. },
  18669. zoneName : function () {
  18670. return this._isUTC ? "Coordinated Universal Time" : "";
  18671. },
  18672. parseZone : function () {
  18673. if (this._tzm) {
  18674. this.zone(this._tzm);
  18675. } else if (typeof this._i === 'string') {
  18676. this.zone(this._i);
  18677. }
  18678. return this;
  18679. },
  18680. hasAlignedHourOffset : function (input) {
  18681. if (!input) {
  18682. input = 0;
  18683. }
  18684. else {
  18685. input = moment(input).zone();
  18686. }
  18687. return (this.zone() - input) % 60 === 0;
  18688. },
  18689. daysInMonth : function () {
  18690. return daysInMonth(this.year(), this.month());
  18691. },
  18692. dayOfYear : function (input) {
  18693. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18694. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18695. },
  18696. quarter : function (input) {
  18697. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  18698. },
  18699. weekYear : function (input) {
  18700. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18701. return input == null ? year : this.add("y", (input - year));
  18702. },
  18703. isoWeekYear : function (input) {
  18704. var year = weekOfYear(this, 1, 4).year;
  18705. return input == null ? year : this.add("y", (input - year));
  18706. },
  18707. week : function (input) {
  18708. var week = this.lang().week(this);
  18709. return input == null ? week : this.add("d", (input - week) * 7);
  18710. },
  18711. isoWeek : function (input) {
  18712. var week = weekOfYear(this, 1, 4).week;
  18713. return input == null ? week : this.add("d", (input - week) * 7);
  18714. },
  18715. weekday : function (input) {
  18716. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18717. return input == null ? weekday : this.add("d", input - weekday);
  18718. },
  18719. isoWeekday : function (input) {
  18720. // behaves the same as moment#day except
  18721. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18722. // as a setter, sunday should belong to the previous week.
  18723. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18724. },
  18725. isoWeeksInYear : function () {
  18726. return weeksInYear(this.year(), 1, 4);
  18727. },
  18728. weeksInYear : function () {
  18729. var weekInfo = this._lang._week;
  18730. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  18731. },
  18732. get : function (units) {
  18733. units = normalizeUnits(units);
  18734. return this[units]();
  18735. },
  18736. set : function (units, value) {
  18737. units = normalizeUnits(units);
  18738. if (typeof this[units] === 'function') {
  18739. this[units](value);
  18740. }
  18741. return this;
  18742. },
  18743. // If passed a language key, it will set the language for this
  18744. // instance. Otherwise, it will return the language configuration
  18745. // variables for this instance.
  18746. lang : function (key) {
  18747. if (key === undefined) {
  18748. return this._lang;
  18749. } else {
  18750. this._lang = getLangDefinition(key);
  18751. return this;
  18752. }
  18753. }
  18754. });
  18755. function rawMonthSetter(mom, value) {
  18756. var dayOfMonth;
  18757. // TODO: Move this out of here!
  18758. if (typeof value === 'string') {
  18759. value = mom.lang().monthsParse(value);
  18760. // TODO: Another silent failure?
  18761. if (typeof value !== 'number') {
  18762. return mom;
  18763. }
  18764. }
  18765. dayOfMonth = Math.min(mom.date(),
  18766. daysInMonth(mom.year(), value));
  18767. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  18768. return mom;
  18769. }
  18770. function rawGetter(mom, unit) {
  18771. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  18772. }
  18773. function rawSetter(mom, unit, value) {
  18774. if (unit === 'Month') {
  18775. return rawMonthSetter(mom, value);
  18776. } else {
  18777. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  18778. }
  18779. }
  18780. function makeAccessor(unit, keepTime) {
  18781. return function (value) {
  18782. if (value != null) {
  18783. rawSetter(this, unit, value);
  18784. moment.updateOffset(this, keepTime);
  18785. return this;
  18786. } else {
  18787. return rawGetter(this, unit);
  18788. }
  18789. };
  18790. }
  18791. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  18792. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  18793. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  18794. // Setting the hour should keep the time, because the user explicitly
  18795. // specified which hour he wants. So trying to maintain the same hour (in
  18796. // a new timezone) makes sense. Adding/subtracting hours does not follow
  18797. // this rule.
  18798. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  18799. // moment.fn.month is defined separately
  18800. moment.fn.date = makeAccessor('Date', true);
  18801. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  18802. moment.fn.year = makeAccessor('FullYear', true);
  18803. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  18804. // add plural methods
  18805. moment.fn.days = moment.fn.day;
  18806. moment.fn.months = moment.fn.month;
  18807. moment.fn.weeks = moment.fn.week;
  18808. moment.fn.isoWeeks = moment.fn.isoWeek;
  18809. moment.fn.quarters = moment.fn.quarter;
  18810. // add aliased format methods
  18811. moment.fn.toJSON = moment.fn.toISOString;
  18812. /************************************
  18813. Duration Prototype
  18814. ************************************/
  18815. extend(moment.duration.fn = Duration.prototype, {
  18816. _bubble : function () {
  18817. var milliseconds = this._milliseconds,
  18818. days = this._days,
  18819. months = this._months,
  18820. data = this._data,
  18821. seconds, minutes, hours, years;
  18822. // The following code bubbles up values, see the tests for
  18823. // examples of what that means.
  18824. data.milliseconds = milliseconds % 1000;
  18825. seconds = absRound(milliseconds / 1000);
  18826. data.seconds = seconds % 60;
  18827. minutes = absRound(seconds / 60);
  18828. data.minutes = minutes % 60;
  18829. hours = absRound(minutes / 60);
  18830. data.hours = hours % 24;
  18831. days += absRound(hours / 24);
  18832. data.days = days % 30;
  18833. months += absRound(days / 30);
  18834. data.months = months % 12;
  18835. years = absRound(months / 12);
  18836. data.years = years;
  18837. },
  18838. weeks : function () {
  18839. return absRound(this.days() / 7);
  18840. },
  18841. valueOf : function () {
  18842. return this._milliseconds +
  18843. this._days * 864e5 +
  18844. (this._months % 12) * 2592e6 +
  18845. toInt(this._months / 12) * 31536e6;
  18846. },
  18847. humanize : function (withSuffix) {
  18848. var difference = +this,
  18849. output = relativeTime(difference, !withSuffix, this.lang());
  18850. if (withSuffix) {
  18851. output = this.lang().pastFuture(difference, output);
  18852. }
  18853. return this.lang().postformat(output);
  18854. },
  18855. add : function (input, val) {
  18856. // supports only 2.0-style add(1, 's') or add(moment)
  18857. var dur = moment.duration(input, val);
  18858. this._milliseconds += dur._milliseconds;
  18859. this._days += dur._days;
  18860. this._months += dur._months;
  18861. this._bubble();
  18862. return this;
  18863. },
  18864. subtract : function (input, val) {
  18865. var dur = moment.duration(input, val);
  18866. this._milliseconds -= dur._milliseconds;
  18867. this._days -= dur._days;
  18868. this._months -= dur._months;
  18869. this._bubble();
  18870. return this;
  18871. },
  18872. get : function (units) {
  18873. units = normalizeUnits(units);
  18874. return this[units.toLowerCase() + 's']();
  18875. },
  18876. as : function (units) {
  18877. units = normalizeUnits(units);
  18878. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18879. },
  18880. lang : moment.fn.lang,
  18881. toIsoString : function () {
  18882. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18883. var years = Math.abs(this.years()),
  18884. months = Math.abs(this.months()),
  18885. days = Math.abs(this.days()),
  18886. hours = Math.abs(this.hours()),
  18887. minutes = Math.abs(this.minutes()),
  18888. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18889. if (!this.asSeconds()) {
  18890. // this is the same as C#'s (Noda) and python (isodate)...
  18891. // but not other JS (goog.date)
  18892. return 'P0D';
  18893. }
  18894. return (this.asSeconds() < 0 ? '-' : '') +
  18895. 'P' +
  18896. (years ? years + 'Y' : '') +
  18897. (months ? months + 'M' : '') +
  18898. (days ? days + 'D' : '') +
  18899. ((hours || minutes || seconds) ? 'T' : '') +
  18900. (hours ? hours + 'H' : '') +
  18901. (minutes ? minutes + 'M' : '') +
  18902. (seconds ? seconds + 'S' : '');
  18903. }
  18904. });
  18905. function makeDurationGetter(name) {
  18906. moment.duration.fn[name] = function () {
  18907. return this._data[name];
  18908. };
  18909. }
  18910. function makeDurationAsGetter(name, factor) {
  18911. moment.duration.fn['as' + name] = function () {
  18912. return +this / factor;
  18913. };
  18914. }
  18915. for (i in unitMillisecondFactors) {
  18916. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18917. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18918. makeDurationGetter(i.toLowerCase());
  18919. }
  18920. }
  18921. makeDurationAsGetter('Weeks', 6048e5);
  18922. moment.duration.fn.asMonths = function () {
  18923. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18924. };
  18925. /************************************
  18926. Default Lang
  18927. ************************************/
  18928. // Set default language, other languages will inherit from English.
  18929. moment.lang('en', {
  18930. ordinal : function (number) {
  18931. var b = number % 10,
  18932. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18933. (b === 1) ? 'st' :
  18934. (b === 2) ? 'nd' :
  18935. (b === 3) ? 'rd' : 'th';
  18936. return number + output;
  18937. }
  18938. });
  18939. /* EMBED_LANGUAGES */
  18940. /************************************
  18941. Exposing Moment
  18942. ************************************/
  18943. function makeGlobal(shouldDeprecate) {
  18944. /*global ender:false */
  18945. if (typeof ender !== 'undefined') {
  18946. return;
  18947. }
  18948. oldGlobalMoment = globalScope.moment;
  18949. if (shouldDeprecate) {
  18950. globalScope.moment = deprecate(
  18951. "Accessing Moment through the global scope is " +
  18952. "deprecated, and will be removed in an upcoming " +
  18953. "release.",
  18954. moment);
  18955. } else {
  18956. globalScope.moment = moment;
  18957. }
  18958. }
  18959. // CommonJS module is defined
  18960. if (hasModule) {
  18961. module.exports = moment;
  18962. } else if (typeof define === "function" && define.amd) {
  18963. define("moment", function (require, exports, module) {
  18964. if (module.config && module.config() && module.config().noGlobal === true) {
  18965. // release the global variable
  18966. globalScope.moment = oldGlobalMoment;
  18967. }
  18968. return moment;
  18969. });
  18970. makeGlobal(true);
  18971. } else {
  18972. makeGlobal();
  18973. }
  18974. }).call(this);
  18975. },{}],5:[function(require,module,exports){
  18976. /**
  18977. * Copyright 2012 Craig Campbell
  18978. *
  18979. * Licensed under the Apache License, Version 2.0 (the "License");
  18980. * you may not use this file except in compliance with the License.
  18981. * You may obtain a copy of the License at
  18982. *
  18983. * http://www.apache.org/licenses/LICENSE-2.0
  18984. *
  18985. * Unless required by applicable law or agreed to in writing, software
  18986. * distributed under the License is distributed on an "AS IS" BASIS,
  18987. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18988. * See the License for the specific language governing permissions and
  18989. * limitations under the License.
  18990. *
  18991. * Mousetrap is a simple keyboard shortcut library for Javascript with
  18992. * no external dependencies
  18993. *
  18994. * @version 1.1.2
  18995. * @url craig.is/killing/mice
  18996. */
  18997. /**
  18998. * mapping of special keycodes to their corresponding keys
  18999. *
  19000. * everything in this dictionary cannot use keypress events
  19001. * so it has to be here to map to the correct keycodes for
  19002. * keyup/keydown events
  19003. *
  19004. * @type {Object}
  19005. */
  19006. var _MAP = {
  19007. 8: 'backspace',
  19008. 9: 'tab',
  19009. 13: 'enter',
  19010. 16: 'shift',
  19011. 17: 'ctrl',
  19012. 18: 'alt',
  19013. 20: 'capslock',
  19014. 27: 'esc',
  19015. 32: 'space',
  19016. 33: 'pageup',
  19017. 34: 'pagedown',
  19018. 35: 'end',
  19019. 36: 'home',
  19020. 37: 'left',
  19021. 38: 'up',
  19022. 39: 'right',
  19023. 40: 'down',
  19024. 45: 'ins',
  19025. 46: 'del',
  19026. 91: 'meta',
  19027. 93: 'meta',
  19028. 224: 'meta'
  19029. },
  19030. /**
  19031. * mapping for special characters so they can support
  19032. *
  19033. * this dictionary is only used incase you want to bind a
  19034. * keyup or keydown event to one of these keys
  19035. *
  19036. * @type {Object}
  19037. */
  19038. _KEYCODE_MAP = {
  19039. 106: '*',
  19040. 107: '+',
  19041. 109: '-',
  19042. 110: '.',
  19043. 111 : '/',
  19044. 186: ';',
  19045. 187: '=',
  19046. 188: ',',
  19047. 189: '-',
  19048. 190: '.',
  19049. 191: '/',
  19050. 192: '`',
  19051. 219: '[',
  19052. 220: '\\',
  19053. 221: ']',
  19054. 222: '\''
  19055. },
  19056. /**
  19057. * this is a mapping of keys that require shift on a US keypad
  19058. * back to the non shift equivelents
  19059. *
  19060. * this is so you can use keyup events with these keys
  19061. *
  19062. * note that this will only work reliably on US keyboards
  19063. *
  19064. * @type {Object}
  19065. */
  19066. _SHIFT_MAP = {
  19067. '~': '`',
  19068. '!': '1',
  19069. '@': '2',
  19070. '#': '3',
  19071. '$': '4',
  19072. '%': '5',
  19073. '^': '6',
  19074. '&': '7',
  19075. '*': '8',
  19076. '(': '9',
  19077. ')': '0',
  19078. '_': '-',
  19079. '+': '=',
  19080. ':': ';',
  19081. '\"': '\'',
  19082. '<': ',',
  19083. '>': '.',
  19084. '?': '/',
  19085. '|': '\\'
  19086. },
  19087. /**
  19088. * this is a list of special strings you can use to map
  19089. * to modifier keys when you specify your keyboard shortcuts
  19090. *
  19091. * @type {Object}
  19092. */
  19093. _SPECIAL_ALIASES = {
  19094. 'option': 'alt',
  19095. 'command': 'meta',
  19096. 'return': 'enter',
  19097. 'escape': 'esc'
  19098. },
  19099. /**
  19100. * variable to store the flipped version of _MAP from above
  19101. * needed to check if we should use keypress or not when no action
  19102. * is specified
  19103. *
  19104. * @type {Object|undefined}
  19105. */
  19106. _REVERSE_MAP,
  19107. /**
  19108. * a list of all the callbacks setup via Mousetrap.bind()
  19109. *
  19110. * @type {Object}
  19111. */
  19112. _callbacks = {},
  19113. /**
  19114. * direct map of string combinations to callbacks used for trigger()
  19115. *
  19116. * @type {Object}
  19117. */
  19118. _direct_map = {},
  19119. /**
  19120. * keeps track of what level each sequence is at since multiple
  19121. * sequences can start out with the same sequence
  19122. *
  19123. * @type {Object}
  19124. */
  19125. _sequence_levels = {},
  19126. /**
  19127. * variable to store the setTimeout call
  19128. *
  19129. * @type {null|number}
  19130. */
  19131. _reset_timer,
  19132. /**
  19133. * temporary state where we will ignore the next keyup
  19134. *
  19135. * @type {boolean|string}
  19136. */
  19137. _ignore_next_keyup = false,
  19138. /**
  19139. * are we currently inside of a sequence?
  19140. * type of action ("keyup" or "keydown" or "keypress") or false
  19141. *
  19142. * @type {boolean|string}
  19143. */
  19144. _inside_sequence = false;
  19145. /**
  19146. * loop through the f keys, f1 to f19 and add them to the map
  19147. * programatically
  19148. */
  19149. for (var i = 1; i < 20; ++i) {
  19150. _MAP[111 + i] = 'f' + i;
  19151. }
  19152. /**
  19153. * loop through to map numbers on the numeric keypad
  19154. */
  19155. for (i = 0; i <= 9; ++i) {
  19156. _MAP[i + 96] = i;
  19157. }
  19158. /**
  19159. * cross browser add event method
  19160. *
  19161. * @param {Element|HTMLDocument} object
  19162. * @param {string} type
  19163. * @param {Function} callback
  19164. * @returns void
  19165. */
  19166. function _addEvent(object, type, callback) {
  19167. if (object.addEventListener) {
  19168. return object.addEventListener(type, callback, false);
  19169. }
  19170. object.attachEvent('on' + type, callback);
  19171. }
  19172. /**
  19173. * takes the event and returns the key character
  19174. *
  19175. * @param {Event} e
  19176. * @return {string}
  19177. */
  19178. function _characterFromEvent(e) {
  19179. // for keypress events we should return the character as is
  19180. if (e.type == 'keypress') {
  19181. return String.fromCharCode(e.which);
  19182. }
  19183. // for non keypress events the special maps are needed
  19184. if (_MAP[e.which]) {
  19185. return _MAP[e.which];
  19186. }
  19187. if (_KEYCODE_MAP[e.which]) {
  19188. return _KEYCODE_MAP[e.which];
  19189. }
  19190. // if it is not in the special map
  19191. return String.fromCharCode(e.which).toLowerCase();
  19192. }
  19193. /**
  19194. * should we stop this event before firing off callbacks
  19195. *
  19196. * @param {Event} e
  19197. * @return {boolean}
  19198. */
  19199. function _stop(e) {
  19200. var element = e.target || e.srcElement,
  19201. tag_name = element.tagName;
  19202. // if the element has the class "mousetrap" then no need to stop
  19203. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19204. return false;
  19205. }
  19206. // stop for input, select, and textarea
  19207. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19208. }
  19209. /**
  19210. * checks if two arrays are equal
  19211. *
  19212. * @param {Array} modifiers1
  19213. * @param {Array} modifiers2
  19214. * @returns {boolean}
  19215. */
  19216. function _modifiersMatch(modifiers1, modifiers2) {
  19217. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19218. }
  19219. /**
  19220. * resets all sequence counters except for the ones passed in
  19221. *
  19222. * @param {Object} do_not_reset
  19223. * @returns void
  19224. */
  19225. function _resetSequences(do_not_reset) {
  19226. do_not_reset = do_not_reset || {};
  19227. var active_sequences = false,
  19228. key;
  19229. for (key in _sequence_levels) {
  19230. if (do_not_reset[key]) {
  19231. active_sequences = true;
  19232. continue;
  19233. }
  19234. _sequence_levels[key] = 0;
  19235. }
  19236. if (!active_sequences) {
  19237. _inside_sequence = false;
  19238. }
  19239. }
  19240. /**
  19241. * finds all callbacks that match based on the keycode, modifiers,
  19242. * and action
  19243. *
  19244. * @param {string} character
  19245. * @param {Array} modifiers
  19246. * @param {string} action
  19247. * @param {boolean=} remove - should we remove any matches
  19248. * @param {string=} combination
  19249. * @returns {Array}
  19250. */
  19251. function _getMatches(character, modifiers, action, remove, combination) {
  19252. var i,
  19253. callback,
  19254. matches = [];
  19255. // if there are no events related to this keycode
  19256. if (!_callbacks[character]) {
  19257. return [];
  19258. }
  19259. // if a modifier key is coming up on its own we should allow it
  19260. if (action == 'keyup' && _isModifier(character)) {
  19261. modifiers = [character];
  19262. }
  19263. // loop through all callbacks for the key that was pressed
  19264. // and see if any of them match
  19265. for (i = 0; i < _callbacks[character].length; ++i) {
  19266. callback = _callbacks[character][i];
  19267. // if this is a sequence but it is not at the right level
  19268. // then move onto the next match
  19269. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19270. continue;
  19271. }
  19272. // if the action we are looking for doesn't match the action we got
  19273. // then we should keep going
  19274. if (action != callback.action) {
  19275. continue;
  19276. }
  19277. // if this is a keypress event that means that we need to only
  19278. // look at the character, otherwise check the modifiers as
  19279. // well
  19280. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19281. // remove is used so if you change your mind and call bind a
  19282. // second time with a new function the first one is overwritten
  19283. if (remove && callback.combo == combination) {
  19284. _callbacks[character].splice(i, 1);
  19285. }
  19286. matches.push(callback);
  19287. }
  19288. }
  19289. return matches;
  19290. }
  19291. /**
  19292. * takes a key event and figures out what the modifiers are
  19293. *
  19294. * @param {Event} e
  19295. * @returns {Array}
  19296. */
  19297. function _eventModifiers(e) {
  19298. var modifiers = [];
  19299. if (e.shiftKey) {
  19300. modifiers.push('shift');
  19301. }
  19302. if (e.altKey) {
  19303. modifiers.push('alt');
  19304. }
  19305. if (e.ctrlKey) {
  19306. modifiers.push('ctrl');
  19307. }
  19308. if (e.metaKey) {
  19309. modifiers.push('meta');
  19310. }
  19311. return modifiers;
  19312. }
  19313. /**
  19314. * actually calls the callback function
  19315. *
  19316. * if your callback function returns false this will use the jquery
  19317. * convention - prevent default and stop propogation on the event
  19318. *
  19319. * @param {Function} callback
  19320. * @param {Event} e
  19321. * @returns void
  19322. */
  19323. function _fireCallback(callback, e) {
  19324. if (callback(e) === false) {
  19325. if (e.preventDefault) {
  19326. e.preventDefault();
  19327. }
  19328. if (e.stopPropagation) {
  19329. e.stopPropagation();
  19330. }
  19331. e.returnValue = false;
  19332. e.cancelBubble = true;
  19333. }
  19334. }
  19335. /**
  19336. * handles a character key event
  19337. *
  19338. * @param {string} character
  19339. * @param {Event} e
  19340. * @returns void
  19341. */
  19342. function _handleCharacter(character, e) {
  19343. // if this event should not happen stop here
  19344. if (_stop(e)) {
  19345. return;
  19346. }
  19347. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19348. i,
  19349. do_not_reset = {},
  19350. processed_sequence_callback = false;
  19351. // loop through matching callbacks for this key event
  19352. for (i = 0; i < callbacks.length; ++i) {
  19353. // fire for all sequence callbacks
  19354. // this is because if for example you have multiple sequences
  19355. // bound such as "g i" and "g t" they both need to fire the
  19356. // callback for matching g cause otherwise you can only ever
  19357. // match the first one
  19358. if (callbacks[i].seq) {
  19359. processed_sequence_callback = true;
  19360. // keep a list of which sequences were matches for later
  19361. do_not_reset[callbacks[i].seq] = 1;
  19362. _fireCallback(callbacks[i].callback, e);
  19363. continue;
  19364. }
  19365. // if there were no sequence matches but we are still here
  19366. // that means this is a regular match so we should fire that
  19367. if (!processed_sequence_callback && !_inside_sequence) {
  19368. _fireCallback(callbacks[i].callback, e);
  19369. }
  19370. }
  19371. // if you are inside of a sequence and the key you are pressing
  19372. // is not a modifier key then we should reset all sequences
  19373. // that were not matched by this key event
  19374. if (e.type == _inside_sequence && !_isModifier(character)) {
  19375. _resetSequences(do_not_reset);
  19376. }
  19377. }
  19378. /**
  19379. * handles a keydown event
  19380. *
  19381. * @param {Event} e
  19382. * @returns void
  19383. */
  19384. function _handleKey(e) {
  19385. // normalize e.which for key events
  19386. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19387. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19388. var character = _characterFromEvent(e);
  19389. // no character found then stop
  19390. if (!character) {
  19391. return;
  19392. }
  19393. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19394. _ignore_next_keyup = false;
  19395. return;
  19396. }
  19397. _handleCharacter(character, e);
  19398. }
  19399. /**
  19400. * determines if the keycode specified is a modifier key or not
  19401. *
  19402. * @param {string} key
  19403. * @returns {boolean}
  19404. */
  19405. function _isModifier(key) {
  19406. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19407. }
  19408. /**
  19409. * called to set a 1 second timeout on the specified sequence
  19410. *
  19411. * this is so after each key press in the sequence you have 1 second
  19412. * to press the next key before you have to start over
  19413. *
  19414. * @returns void
  19415. */
  19416. function _resetSequenceTimer() {
  19417. clearTimeout(_reset_timer);
  19418. _reset_timer = setTimeout(_resetSequences, 1000);
  19419. }
  19420. /**
  19421. * reverses the map lookup so that we can look for specific keys
  19422. * to see what can and can't use keypress
  19423. *
  19424. * @return {Object}
  19425. */
  19426. function _getReverseMap() {
  19427. if (!_REVERSE_MAP) {
  19428. _REVERSE_MAP = {};
  19429. for (var key in _MAP) {
  19430. // pull out the numeric keypad from here cause keypress should
  19431. // be able to detect the keys from the character
  19432. if (key > 95 && key < 112) {
  19433. continue;
  19434. }
  19435. if (_MAP.hasOwnProperty(key)) {
  19436. _REVERSE_MAP[_MAP[key]] = key;
  19437. }
  19438. }
  19439. }
  19440. return _REVERSE_MAP;
  19441. }
  19442. /**
  19443. * picks the best action based on the key combination
  19444. *
  19445. * @param {string} key - character for key
  19446. * @param {Array} modifiers
  19447. * @param {string=} action passed in
  19448. */
  19449. function _pickBestAction(key, modifiers, action) {
  19450. // if no action was picked in we should try to pick the one
  19451. // that we think would work best for this key
  19452. if (!action) {
  19453. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19454. }
  19455. // modifier keys don't work as expected with keypress,
  19456. // switch to keydown
  19457. if (action == 'keypress' && modifiers.length) {
  19458. action = 'keydown';
  19459. }
  19460. return action;
  19461. }
  19462. /**
  19463. * binds a key sequence to an event
  19464. *
  19465. * @param {string} combo - combo specified in bind call
  19466. * @param {Array} keys
  19467. * @param {Function} callback
  19468. * @param {string=} action
  19469. * @returns void
  19470. */
  19471. function _bindSequence(combo, keys, callback, action) {
  19472. // start off by adding a sequence level record for this combination
  19473. // and setting the level to 0
  19474. _sequence_levels[combo] = 0;
  19475. // if there is no action pick the best one for the first key
  19476. // in the sequence
  19477. if (!action) {
  19478. action = _pickBestAction(keys[0], []);
  19479. }
  19480. /**
  19481. * callback to increase the sequence level for this sequence and reset
  19482. * all other sequences that were active
  19483. *
  19484. * @param {Event} e
  19485. * @returns void
  19486. */
  19487. var _increaseSequence = function(e) {
  19488. _inside_sequence = action;
  19489. ++_sequence_levels[combo];
  19490. _resetSequenceTimer();
  19491. },
  19492. /**
  19493. * wraps the specified callback inside of another function in order
  19494. * to reset all sequence counters as soon as this sequence is done
  19495. *
  19496. * @param {Event} e
  19497. * @returns void
  19498. */
  19499. _callbackAndReset = function(e) {
  19500. _fireCallback(callback, e);
  19501. // we should ignore the next key up if the action is key down
  19502. // or keypress. this is so if you finish a sequence and
  19503. // release the key the final key will not trigger a keyup
  19504. if (action !== 'keyup') {
  19505. _ignore_next_keyup = _characterFromEvent(e);
  19506. }
  19507. // weird race condition if a sequence ends with the key
  19508. // another sequence begins with
  19509. setTimeout(_resetSequences, 10);
  19510. },
  19511. i;
  19512. // loop through keys one at a time and bind the appropriate callback
  19513. // function. for any key leading up to the final one it should
  19514. // increase the sequence. after the final, it should reset all sequences
  19515. for (i = 0; i < keys.length; ++i) {
  19516. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19517. }
  19518. }
  19519. /**
  19520. * binds a single keyboard combination
  19521. *
  19522. * @param {string} combination
  19523. * @param {Function} callback
  19524. * @param {string=} action
  19525. * @param {string=} sequence_name - name of sequence if part of sequence
  19526. * @param {number=} level - what part of the sequence the command is
  19527. * @returns void
  19528. */
  19529. function _bindSingle(combination, callback, action, sequence_name, level) {
  19530. // make sure multiple spaces in a row become a single space
  19531. combination = combination.replace(/\s+/g, ' ');
  19532. var sequence = combination.split(' '),
  19533. i,
  19534. key,
  19535. keys,
  19536. modifiers = [];
  19537. // if this pattern is a sequence of keys then run through this method
  19538. // to reprocess each pattern one key at a time
  19539. if (sequence.length > 1) {
  19540. return _bindSequence(combination, sequence, callback, action);
  19541. }
  19542. // take the keys from this pattern and figure out what the actual
  19543. // pattern is all about
  19544. keys = combination === '+' ? ['+'] : combination.split('+');
  19545. for (i = 0; i < keys.length; ++i) {
  19546. key = keys[i];
  19547. // normalize key names
  19548. if (_SPECIAL_ALIASES[key]) {
  19549. key = _SPECIAL_ALIASES[key];
  19550. }
  19551. // if this is not a keypress event then we should
  19552. // be smart about using shift keys
  19553. // this will only work for US keyboards however
  19554. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19555. key = _SHIFT_MAP[key];
  19556. modifiers.push('shift');
  19557. }
  19558. // if this key is a modifier then add it to the list of modifiers
  19559. if (_isModifier(key)) {
  19560. modifiers.push(key);
  19561. }
  19562. }
  19563. // depending on what the key combination is
  19564. // we will try to pick the best event for it
  19565. action = _pickBestAction(key, modifiers, action);
  19566. // make sure to initialize array if this is the first time
  19567. // a callback is added for this key
  19568. if (!_callbacks[key]) {
  19569. _callbacks[key] = [];
  19570. }
  19571. // remove an existing match if there is one
  19572. _getMatches(key, modifiers, action, !sequence_name, combination);
  19573. // add this call back to the array
  19574. // if it is a sequence put it at the beginning
  19575. // if not put it at the end
  19576. //
  19577. // this is important because the way these are processed expects
  19578. // the sequence ones to come first
  19579. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19580. callback: callback,
  19581. modifiers: modifiers,
  19582. action: action,
  19583. seq: sequence_name,
  19584. level: level,
  19585. combo: combination
  19586. });
  19587. }
  19588. /**
  19589. * binds multiple combinations to the same callback
  19590. *
  19591. * @param {Array} combinations
  19592. * @param {Function} callback
  19593. * @param {string|undefined} action
  19594. * @returns void
  19595. */
  19596. function _bindMultiple(combinations, callback, action) {
  19597. for (var i = 0; i < combinations.length; ++i) {
  19598. _bindSingle(combinations[i], callback, action);
  19599. }
  19600. }
  19601. // start!
  19602. _addEvent(document, 'keypress', _handleKey);
  19603. _addEvent(document, 'keydown', _handleKey);
  19604. _addEvent(document, 'keyup', _handleKey);
  19605. var mousetrap = {
  19606. /**
  19607. * binds an event to mousetrap
  19608. *
  19609. * can be a single key, a combination of keys separated with +,
  19610. * a comma separated list of keys, an array of keys, or
  19611. * a sequence of keys separated by spaces
  19612. *
  19613. * be sure to list the modifier keys first to make sure that the
  19614. * correct key ends up getting bound (the last key in the pattern)
  19615. *
  19616. * @param {string|Array} keys
  19617. * @param {Function} callback
  19618. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19619. * @returns void
  19620. */
  19621. bind: function(keys, callback, action) {
  19622. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19623. _direct_map[keys + ':' + action] = callback;
  19624. return this;
  19625. },
  19626. /**
  19627. * unbinds an event to mousetrap
  19628. *
  19629. * the unbinding sets the callback function of the specified key combo
  19630. * to an empty function and deletes the corresponding key in the
  19631. * _direct_map dict.
  19632. *
  19633. * the keycombo+action has to be exactly the same as
  19634. * it was defined in the bind method
  19635. *
  19636. * TODO: actually remove this from the _callbacks dictionary instead
  19637. * of binding an empty function
  19638. *
  19639. * @param {string|Array} keys
  19640. * @param {string} action
  19641. * @returns void
  19642. */
  19643. unbind: function(keys, action) {
  19644. if (_direct_map[keys + ':' + action]) {
  19645. delete _direct_map[keys + ':' + action];
  19646. this.bind(keys, function() {}, action);
  19647. }
  19648. return this;
  19649. },
  19650. /**
  19651. * triggers an event that has already been bound
  19652. *
  19653. * @param {string} keys
  19654. * @param {string=} action
  19655. * @returns void
  19656. */
  19657. trigger: function(keys, action) {
  19658. _direct_map[keys + ':' + action]();
  19659. return this;
  19660. },
  19661. /**
  19662. * resets the library back to its initial state. this is useful
  19663. * if you want to clear out the current keyboard shortcuts and bind
  19664. * new ones - for example if you switch to another page
  19665. *
  19666. * @returns void
  19667. */
  19668. reset: function() {
  19669. _callbacks = {};
  19670. _direct_map = {};
  19671. return this;
  19672. }
  19673. };
  19674. module.exports = mousetrap;
  19675. },{}]},{},[1])
  19676. (1)
  19677. });