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.

22691 lines
670 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
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
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
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
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
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
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
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 1.0.2-SNAPSHOT
  8. * @date 2014-05-23
  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 = 0, 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. * @param {function} callback
  1550. * @param {Object} [options] Available options:
  1551. * {Object.<String, String>} [convert]
  1552. * {String[]} [fields] filter fields
  1553. * {function} [filter] filter items
  1554. * {String | function} [order] Order the items by
  1555. * a field name or custom sort function.
  1556. */
  1557. DataSet.prototype.forEach = function (callback, options) {
  1558. var filter = options && options.filter,
  1559. convert = options && options.convert || this.options.convert,
  1560. data = this.data,
  1561. item,
  1562. id;
  1563. if (options && options.order) {
  1564. // execute forEach on ordered list
  1565. var items = this.get(options);
  1566. for (var i = 0, len = items.length; i < len; i++) {
  1567. item = items[i];
  1568. id = item[this.fieldId];
  1569. callback(item, id);
  1570. }
  1571. }
  1572. else {
  1573. // unordered
  1574. for (id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. callback(item, id);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. };
  1584. /**
  1585. * Map every item in the dataset.
  1586. * @param {function} callback
  1587. * @param {Object} [options] Available options:
  1588. * {Object.<String, String>} [convert]
  1589. * {String[]} [fields] filter fields
  1590. * {function} [filter] filter items
  1591. * {String | function} [order] Order the items by
  1592. * a field name or custom sort function.
  1593. * @return {Object[]} mappedItems
  1594. */
  1595. DataSet.prototype.map = function (callback, options) {
  1596. var filter = options && options.filter,
  1597. convert = options && options.convert || this.options.convert,
  1598. mappedItems = [],
  1599. data = this.data,
  1600. item;
  1601. // convert and filter items
  1602. for (var id in data) {
  1603. if (data.hasOwnProperty(id)) {
  1604. item = this._getItem(id, convert);
  1605. if (!filter || filter(item)) {
  1606. mappedItems.push(callback(item, id));
  1607. }
  1608. }
  1609. }
  1610. // order items
  1611. if (options && options.order) {
  1612. this._sort(mappedItems, options.order);
  1613. }
  1614. return mappedItems;
  1615. };
  1616. /**
  1617. * Filter the fields of an item
  1618. * @param {Object} item
  1619. * @param {String[]} fields Field names
  1620. * @return {Object} filteredItem
  1621. * @private
  1622. */
  1623. DataSet.prototype._filterFields = function (item, fields) {
  1624. var filteredItem = {};
  1625. for (var field in item) {
  1626. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1627. filteredItem[field] = item[field];
  1628. }
  1629. }
  1630. return filteredItem;
  1631. };
  1632. /**
  1633. * Sort the provided array with items
  1634. * @param {Object[]} items
  1635. * @param {String | function} order A field name or custom sort function.
  1636. * @private
  1637. */
  1638. DataSet.prototype._sort = function (items, order) {
  1639. if (util.isString(order)) {
  1640. // order by provided field name
  1641. var name = order; // field name
  1642. items.sort(function (a, b) {
  1643. var av = a[name];
  1644. var bv = b[name];
  1645. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1646. });
  1647. }
  1648. else if (typeof order === 'function') {
  1649. // order by sort function
  1650. items.sort(order);
  1651. }
  1652. // TODO: extend order by an Object {field:String, direction:String}
  1653. // where direction can be 'asc' or 'desc'
  1654. else {
  1655. throw new TypeError('Order must be a function or a string');
  1656. }
  1657. };
  1658. /**
  1659. * Remove an object by pointer or by id
  1660. * @param {String | Number | Object | Array} id Object or id, or an array with
  1661. * objects or ids to be removed
  1662. * @param {String} [senderId] Optional sender id
  1663. * @return {Array} removedIds
  1664. */
  1665. DataSet.prototype.remove = function (id, senderId) {
  1666. var removedIds = [],
  1667. i, len, removedId;
  1668. if (id instanceof Array) {
  1669. for (i = 0, len = id.length; i < len; i++) {
  1670. removedId = this._remove(id[i]);
  1671. if (removedId != null) {
  1672. removedIds.push(removedId);
  1673. }
  1674. }
  1675. }
  1676. else {
  1677. removedId = this._remove(id);
  1678. if (removedId != null) {
  1679. removedIds.push(removedId);
  1680. }
  1681. }
  1682. if (removedIds.length) {
  1683. this._trigger('remove', {items: removedIds}, senderId);
  1684. }
  1685. return removedIds;
  1686. };
  1687. /**
  1688. * Remove an item by its id
  1689. * @param {Number | String | Object} id id or item
  1690. * @returns {Number | String | null} id
  1691. * @private
  1692. */
  1693. DataSet.prototype._remove = function (id) {
  1694. if (util.isNumber(id) || util.isString(id)) {
  1695. if (this.data[id]) {
  1696. delete this.data[id];
  1697. delete this.internalIds[id];
  1698. return id;
  1699. }
  1700. }
  1701. else if (id instanceof Object) {
  1702. var itemId = id[this.fieldId];
  1703. if (itemId && this.data[itemId]) {
  1704. delete this.data[itemId];
  1705. delete this.internalIds[itemId];
  1706. return itemId;
  1707. }
  1708. }
  1709. return null;
  1710. };
  1711. /**
  1712. * Clear the data
  1713. * @param {String} [senderId] Optional sender id
  1714. * @return {Array} removedIds The ids of all removed items
  1715. */
  1716. DataSet.prototype.clear = function (senderId) {
  1717. var ids = Object.keys(this.data);
  1718. this.data = {};
  1719. this.internalIds = {};
  1720. this._trigger('remove', {items: ids}, senderId);
  1721. return ids;
  1722. };
  1723. /**
  1724. * Find the item with maximum value of a specified field
  1725. * @param {String} field
  1726. * @return {Object | null} item Item containing max value, or null if no items
  1727. */
  1728. DataSet.prototype.max = function (field) {
  1729. var data = this.data,
  1730. max = null,
  1731. maxField = null;
  1732. for (var id in data) {
  1733. if (data.hasOwnProperty(id)) {
  1734. var item = data[id];
  1735. var itemField = item[field];
  1736. if (itemField != null && (!max || itemField > maxField)) {
  1737. max = item;
  1738. maxField = itemField;
  1739. }
  1740. }
  1741. }
  1742. return max;
  1743. };
  1744. /**
  1745. * Find the item with minimum value of a specified field
  1746. * @param {String} field
  1747. * @return {Object | null} item Item containing max value, or null if no items
  1748. */
  1749. DataSet.prototype.min = function (field) {
  1750. var data = this.data,
  1751. min = null,
  1752. minField = null;
  1753. for (var id in data) {
  1754. if (data.hasOwnProperty(id)) {
  1755. var item = data[id];
  1756. var itemField = item[field];
  1757. if (itemField != null && (!min || itemField < minField)) {
  1758. min = item;
  1759. minField = itemField;
  1760. }
  1761. }
  1762. }
  1763. return min;
  1764. };
  1765. /**
  1766. * Find all distinct values of a specified field
  1767. * @param {String} field
  1768. * @return {Array} values Array containing all distinct values. If data items
  1769. * do not contain the specified field are ignored.
  1770. * The returned array is unordered.
  1771. */
  1772. DataSet.prototype.distinct = function (field) {
  1773. var data = this.data,
  1774. values = [],
  1775. fieldType = this.options.convert[field],
  1776. count = 0;
  1777. for (var prop in data) {
  1778. if (data.hasOwnProperty(prop)) {
  1779. var item = data[prop];
  1780. var value = util.convert(item[field], fieldType);
  1781. var exists = false;
  1782. for (var i = 0; i < count; i++) {
  1783. if (values[i] == value) {
  1784. exists = true;
  1785. break;
  1786. }
  1787. }
  1788. if (!exists && (value !== undefined)) {
  1789. values[count] = value;
  1790. count++;
  1791. }
  1792. }
  1793. }
  1794. return values;
  1795. };
  1796. /**
  1797. * Add a single item. Will fail when an item with the same id already exists.
  1798. * @param {Object} item
  1799. * @return {String} id
  1800. * @private
  1801. */
  1802. DataSet.prototype._addItem = function (item) {
  1803. var id = item[this.fieldId];
  1804. if (id != undefined) {
  1805. // check whether this id is already taken
  1806. if (this.data[id]) {
  1807. // item already exists
  1808. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1809. }
  1810. }
  1811. else {
  1812. // generate an id
  1813. id = util.randomUUID();
  1814. item[this.fieldId] = id;
  1815. this.internalIds[id] = item;
  1816. }
  1817. var d = {};
  1818. for (var field in item) {
  1819. if (item.hasOwnProperty(field)) {
  1820. var fieldType = this.convert[field]; // type may be undefined
  1821. d[field] = util.convert(item[field], fieldType);
  1822. }
  1823. }
  1824. this.data[id] = d;
  1825. return id;
  1826. };
  1827. /**
  1828. * Get an item. Fields can be converted to a specific type
  1829. * @param {String} id
  1830. * @param {Object.<String, String>} [convert] field types to convert
  1831. * @return {Object | null} item
  1832. * @private
  1833. */
  1834. DataSet.prototype._getItem = function (id, convert) {
  1835. var field, value;
  1836. // get the item from the dataset
  1837. var raw = this.data[id];
  1838. if (!raw) {
  1839. return null;
  1840. }
  1841. // convert the items field types
  1842. var converted = {},
  1843. fieldId = this.fieldId,
  1844. internalIds = this.internalIds;
  1845. if (convert) {
  1846. for (field in raw) {
  1847. if (raw.hasOwnProperty(field)) {
  1848. value = raw[field];
  1849. // output all fields, except internal ids
  1850. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1851. converted[field] = util.convert(value, convert[field]);
  1852. }
  1853. }
  1854. }
  1855. }
  1856. else {
  1857. // no field types specified, no converting needed
  1858. for (field in raw) {
  1859. if (raw.hasOwnProperty(field)) {
  1860. value = raw[field];
  1861. // output all fields, except internal ids
  1862. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1863. converted[field] = value;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. return converted;
  1869. };
  1870. /**
  1871. * Update a single item: merge with existing item.
  1872. * Will fail when the item has no id, or when there does not exist an item
  1873. * with the same id.
  1874. * @param {Object} item
  1875. * @return {String} id
  1876. * @private
  1877. */
  1878. DataSet.prototype._updateItem = function (item) {
  1879. var id = item[this.fieldId];
  1880. if (id == undefined) {
  1881. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1882. }
  1883. var d = this.data[id];
  1884. if (!d) {
  1885. // item doesn't exist
  1886. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1887. }
  1888. // merge with current item
  1889. for (var field in item) {
  1890. if (item.hasOwnProperty(field)) {
  1891. var fieldType = this.convert[field]; // type may be undefined
  1892. d[field] = util.convert(item[field], fieldType);
  1893. }
  1894. }
  1895. return id;
  1896. };
  1897. /**
  1898. * check if an id is an internal or external id
  1899. * @param id
  1900. * @returns {boolean}
  1901. * @private
  1902. */
  1903. DataSet.prototype.isInternalId = function(id) {
  1904. return (id in this.internalIds);
  1905. };
  1906. /**
  1907. * Get an array with the column names of a Google DataTable
  1908. * @param {DataTable} dataTable
  1909. * @return {String[]} columnNames
  1910. * @private
  1911. */
  1912. DataSet.prototype._getColumnNames = function (dataTable) {
  1913. var columns = [];
  1914. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1915. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1916. }
  1917. return columns;
  1918. };
  1919. /**
  1920. * Append an item as a row to the dataTable
  1921. * @param dataTable
  1922. * @param columns
  1923. * @param item
  1924. * @private
  1925. */
  1926. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1927. var row = dataTable.addRow();
  1928. for (var col = 0, cols = columns.length; col < cols; col++) {
  1929. var field = columns[col];
  1930. dataTable.setValue(row, col, item[field]);
  1931. }
  1932. };
  1933. /**
  1934. * DataView
  1935. *
  1936. * a dataview offers a filtered view on a dataset or an other dataview.
  1937. *
  1938. * @param {DataSet | DataView} data
  1939. * @param {Object} [options] Available options: see method get
  1940. *
  1941. * @constructor DataView
  1942. */
  1943. function DataView (data, options) {
  1944. this.id = util.randomUUID();
  1945. this.data = null;
  1946. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1947. this.options = options || {};
  1948. this.fieldId = 'id'; // name of the field containing id
  1949. this.subscribers = {}; // event subscribers
  1950. var me = this;
  1951. this.listener = function () {
  1952. me._onEvent.apply(me, arguments);
  1953. };
  1954. this.setData(data);
  1955. }
  1956. // TODO: implement a function .config() to dynamically update things like configured filter
  1957. // and trigger changes accordingly
  1958. /**
  1959. * Set a data source for the view
  1960. * @param {DataSet | DataView} data
  1961. */
  1962. DataView.prototype.setData = function (data) {
  1963. var ids, dataItems, i, len;
  1964. if (this.data) {
  1965. // unsubscribe from current dataset
  1966. if (this.data.unsubscribe) {
  1967. this.data.unsubscribe('*', this.listener);
  1968. }
  1969. // trigger a remove of all items in memory
  1970. ids = [];
  1971. for (var id in this.ids) {
  1972. if (this.ids.hasOwnProperty(id)) {
  1973. ids.push(id);
  1974. }
  1975. }
  1976. this.ids = {};
  1977. this._trigger('remove', {items: ids});
  1978. }
  1979. this.data = data;
  1980. if (this.data) {
  1981. // update fieldId
  1982. this.fieldId = this.options.fieldId ||
  1983. (this.data && this.data.options && this.data.options.fieldId) ||
  1984. 'id';
  1985. // trigger an add of all added items
  1986. ids = this.data.getIds({filter: this.options && this.options.filter});
  1987. for (i = 0, len = ids.length; i < len; i++) {
  1988. id = ids[i];
  1989. this.ids[id] = true;
  1990. }
  1991. this._trigger('add', {items: ids});
  1992. // subscribe to new dataset
  1993. if (this.data.on) {
  1994. this.data.on('*', this.listener);
  1995. }
  1996. }
  1997. };
  1998. /**
  1999. * Get data from the data view
  2000. *
  2001. * Usage:
  2002. *
  2003. * get()
  2004. * get(options: Object)
  2005. * get(options: Object, data: Array | DataTable)
  2006. *
  2007. * get(id: Number)
  2008. * get(id: Number, options: Object)
  2009. * get(id: Number, options: Object, data: Array | DataTable)
  2010. *
  2011. * get(ids: Number[])
  2012. * get(ids: Number[], options: Object)
  2013. * get(ids: Number[], options: Object, data: Array | DataTable)
  2014. *
  2015. * Where:
  2016. *
  2017. * {Number | String} id The id of an item
  2018. * {Number[] | String{}} ids An array with ids of items
  2019. * {Object} options An Object with options. Available options:
  2020. * {String} [type] Type of data to be returned. Can
  2021. * be 'DataTable' or 'Array' (default)
  2022. * {Object.<String, String>} [convert]
  2023. * {String[]} [fields] field names to be returned
  2024. * {function} [filter] filter items
  2025. * {String | function} [order] Order the items by
  2026. * a field name or custom sort function.
  2027. * {Array | DataTable} [data] If provided, items will be appended to this
  2028. * array or table. Required in case of Google
  2029. * DataTable.
  2030. * @param args
  2031. */
  2032. DataView.prototype.get = function (args) {
  2033. var me = this;
  2034. // parse the arguments
  2035. var ids, options, data;
  2036. var firstType = util.getType(arguments[0]);
  2037. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2038. // get(id(s) [, options] [, data])
  2039. ids = arguments[0]; // can be a single id or an array with ids
  2040. options = arguments[1];
  2041. data = arguments[2];
  2042. }
  2043. else {
  2044. // get([, options] [, data])
  2045. options = arguments[0];
  2046. data = arguments[1];
  2047. }
  2048. // extend the options with the default options and provided options
  2049. var viewOptions = util.extend({}, this.options, options);
  2050. // create a combined filter method when needed
  2051. if (this.options.filter && options && options.filter) {
  2052. viewOptions.filter = function (item) {
  2053. return me.options.filter(item) && options.filter(item);
  2054. }
  2055. }
  2056. // build up the call to the linked data set
  2057. var getArguments = [];
  2058. if (ids != undefined) {
  2059. getArguments.push(ids);
  2060. }
  2061. getArguments.push(viewOptions);
  2062. getArguments.push(data);
  2063. return this.data && this.data.get.apply(this.data, getArguments);
  2064. };
  2065. /**
  2066. * Get ids of all items or from a filtered set of items.
  2067. * @param {Object} [options] An Object with options. Available options:
  2068. * {function} [filter] filter items
  2069. * {String | function} [order] Order the items by
  2070. * a field name or custom sort function.
  2071. * @return {Array} ids
  2072. */
  2073. DataView.prototype.getIds = function (options) {
  2074. var ids;
  2075. if (this.data) {
  2076. var defaultFilter = this.options.filter;
  2077. var filter;
  2078. if (options && options.filter) {
  2079. if (defaultFilter) {
  2080. filter = function (item) {
  2081. return defaultFilter(item) && options.filter(item);
  2082. }
  2083. }
  2084. else {
  2085. filter = options.filter;
  2086. }
  2087. }
  2088. else {
  2089. filter = defaultFilter;
  2090. }
  2091. ids = this.data.getIds({
  2092. filter: filter,
  2093. order: options && options.order
  2094. });
  2095. }
  2096. else {
  2097. ids = [];
  2098. }
  2099. return ids;
  2100. };
  2101. /**
  2102. * Event listener. Will propagate all events from the connected data set to
  2103. * the subscribers of the DataView, but will filter the items and only trigger
  2104. * when there are changes in the filtered data set.
  2105. * @param {String} event
  2106. * @param {Object | null} params
  2107. * @param {String} senderId
  2108. * @private
  2109. */
  2110. DataView.prototype._onEvent = function (event, params, senderId) {
  2111. var i, len, id, item,
  2112. ids = params && params.items,
  2113. data = this.data,
  2114. added = [],
  2115. updated = [],
  2116. removed = [];
  2117. if (ids && data) {
  2118. switch (event) {
  2119. case 'add':
  2120. // filter the ids of the added items
  2121. for (i = 0, len = ids.length; i < len; i++) {
  2122. id = ids[i];
  2123. item = this.get(id);
  2124. if (item) {
  2125. this.ids[id] = true;
  2126. added.push(id);
  2127. }
  2128. }
  2129. break;
  2130. case 'update':
  2131. // determine the event from the views viewpoint: an updated
  2132. // item can be added, updated, or removed from this view.
  2133. for (i = 0, len = ids.length; i < len; i++) {
  2134. id = ids[i];
  2135. item = this.get(id);
  2136. if (item) {
  2137. if (this.ids[id]) {
  2138. updated.push(id);
  2139. }
  2140. else {
  2141. this.ids[id] = true;
  2142. added.push(id);
  2143. }
  2144. }
  2145. else {
  2146. if (this.ids[id]) {
  2147. delete this.ids[id];
  2148. removed.push(id);
  2149. }
  2150. else {
  2151. // nothing interesting for me :-(
  2152. }
  2153. }
  2154. }
  2155. break;
  2156. case 'remove':
  2157. // filter the ids of the removed items
  2158. for (i = 0, len = ids.length; i < len; i++) {
  2159. id = ids[i];
  2160. if (this.ids[id]) {
  2161. delete this.ids[id];
  2162. removed.push(id);
  2163. }
  2164. }
  2165. break;
  2166. }
  2167. if (added.length) {
  2168. this._trigger('add', {items: added}, senderId);
  2169. }
  2170. if (updated.length) {
  2171. this._trigger('update', {items: updated}, senderId);
  2172. }
  2173. if (removed.length) {
  2174. this._trigger('remove', {items: removed}, senderId);
  2175. }
  2176. }
  2177. };
  2178. // copy subscription functionality from DataSet
  2179. DataView.prototype.on = DataSet.prototype.on;
  2180. DataView.prototype.off = DataSet.prototype.off;
  2181. DataView.prototype._trigger = DataSet.prototype._trigger;
  2182. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2183. DataView.prototype.subscribe = DataView.prototype.on;
  2184. DataView.prototype.unsubscribe = DataView.prototype.off;
  2185. /**
  2186. * Utility functions for ordering and stacking of items
  2187. */
  2188. var stack = {};
  2189. /**
  2190. * Order items by their start data
  2191. * @param {Item[]} items
  2192. */
  2193. stack.orderByStart = function orderByStart(items) {
  2194. items.sort(function (a, b) {
  2195. return a.data.start - b.data.start;
  2196. });
  2197. };
  2198. /**
  2199. * Order items by their end date. If they have no end date, their start date
  2200. * is used.
  2201. * @param {Item[]} items
  2202. */
  2203. stack.orderByEnd = function orderByEnd(items) {
  2204. items.sort(function (a, b) {
  2205. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2206. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2207. return aTime - bTime;
  2208. });
  2209. };
  2210. /**
  2211. * Adjust vertical positions of the items such that they don't overlap each
  2212. * other.
  2213. * @param {Item[]} items
  2214. * All visible items
  2215. * @param {{item: number, axis: number}} margin
  2216. * Margins between items and between items and the axis.
  2217. * @param {boolean} [force=false]
  2218. * If true, all items will be repositioned. If false (default), only
  2219. * items having a top===null will be re-stacked
  2220. */
  2221. stack.stack = function _stack (items, margin, force) {
  2222. var i, iMax;
  2223. if (force) {
  2224. // reset top position of all items
  2225. for (i = 0, iMax = items.length; i < iMax; i++) {
  2226. items[i].top = null;
  2227. }
  2228. }
  2229. // calculate new, non-overlapping positions
  2230. for (i = 0, iMax = items.length; i < iMax; i++) {
  2231. var item = items[i];
  2232. if (item.top === null) {
  2233. // initialize top position
  2234. item.top = margin.axis;
  2235. do {
  2236. // TODO: optimize checking for overlap. when there is a gap without items,
  2237. // you only need to check for items from the next item on, not from zero
  2238. var collidingItem = null;
  2239. for (var j = 0, jj = items.length; j < jj; j++) {
  2240. var other = items[j];
  2241. if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
  2242. collidingItem = other;
  2243. break;
  2244. }
  2245. }
  2246. if (collidingItem != null) {
  2247. // There is a collision. Reposition the items above the colliding element
  2248. item.top = collidingItem.top + collidingItem.height + margin.item;
  2249. }
  2250. } while (collidingItem);
  2251. }
  2252. }
  2253. };
  2254. /**
  2255. * Adjust vertical positions of the items without stacking them
  2256. * @param {Item[]} items
  2257. * All visible items
  2258. * @param {{item: number, axis: number}} margin
  2259. * Margins between items and between items and the axis.
  2260. */
  2261. stack.nostack = function nostack (items, margin) {
  2262. var i, iMax;
  2263. // reset top position of all items
  2264. for (i = 0, iMax = items.length; i < iMax; i++) {
  2265. items[i].top = margin.axis;
  2266. }
  2267. };
  2268. /**
  2269. * Test if the two provided items collide
  2270. * The items must have parameters left, width, top, and height.
  2271. * @param {Item} a The first item
  2272. * @param {Item} b The second item
  2273. * @param {Number} margin A minimum required margin.
  2274. * If margin is provided, the two items will be
  2275. * marked colliding when they overlap or
  2276. * when the margin between the two is smaller than
  2277. * the requested margin.
  2278. * @return {boolean} true if a and b collide, else false
  2279. */
  2280. stack.collision = function collision (a, b, margin) {
  2281. return ((a.left - margin) < (b.left + b.width) &&
  2282. (a.left + a.width + margin) > b.left &&
  2283. (a.top - margin) < (b.top + b.height) &&
  2284. (a.top + a.height + margin) > b.top);
  2285. };
  2286. /**
  2287. * @constructor TimeStep
  2288. * The class TimeStep is an iterator for dates. You provide a start date and an
  2289. * end date. The class itself determines the best scale (step size) based on the
  2290. * provided start Date, end Date, and minimumStep.
  2291. *
  2292. * If minimumStep is provided, the step size is chosen as close as possible
  2293. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2294. * provided, the scale is set to 1 DAY.
  2295. * The minimumStep should correspond with the onscreen size of about 6 characters
  2296. *
  2297. * Alternatively, you can set a scale by hand.
  2298. * After creation, you can initialize the class by executing first(). Then you
  2299. * can iterate from the start date to the end date via next(). You can check if
  2300. * the end date is reached with the function hasNext(). After each step, you can
  2301. * retrieve the current date via getCurrent().
  2302. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2303. * days, to years.
  2304. *
  2305. * Version: 1.2
  2306. *
  2307. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2308. * or new Date(2010, 9, 21, 23, 45, 00)
  2309. * @param {Date} [end] The end date
  2310. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2311. */
  2312. function TimeStep(start, end, minimumStep) {
  2313. // variables
  2314. this.current = new Date();
  2315. this._start = new Date();
  2316. this._end = new Date();
  2317. this.autoScale = true;
  2318. this.scale = TimeStep.SCALE.DAY;
  2319. this.step = 1;
  2320. // initialize the range
  2321. this.setRange(start, end, minimumStep);
  2322. }
  2323. /// enum scale
  2324. TimeStep.SCALE = {
  2325. MILLISECOND: 1,
  2326. SECOND: 2,
  2327. MINUTE: 3,
  2328. HOUR: 4,
  2329. DAY: 5,
  2330. WEEKDAY: 6,
  2331. MONTH: 7,
  2332. YEAR: 8
  2333. };
  2334. /**
  2335. * Set a new range
  2336. * If minimumStep is provided, the step size is chosen as close as possible
  2337. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2338. * provided, the scale is set to 1 DAY.
  2339. * The minimumStep should correspond with the onscreen size of about 6 characters
  2340. * @param {Date} [start] The start date and time.
  2341. * @param {Date} [end] The end date and time.
  2342. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2343. */
  2344. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2345. if (!(start instanceof Date) || !(end instanceof Date)) {
  2346. throw "No legal start or end date in method setRange";
  2347. }
  2348. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2349. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2350. if (this.autoScale) {
  2351. this.setMinimumStep(minimumStep);
  2352. }
  2353. };
  2354. /**
  2355. * Set the range iterator to the start date.
  2356. */
  2357. TimeStep.prototype.first = function() {
  2358. this.current = new Date(this._start.valueOf());
  2359. this.roundToMinor();
  2360. };
  2361. /**
  2362. * Round the current date to the first minor date value
  2363. * This must be executed once when the current date is set to start Date
  2364. */
  2365. TimeStep.prototype.roundToMinor = function() {
  2366. // round to floor
  2367. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2368. //noinspection FallthroughInSwitchStatementJS
  2369. switch (this.scale) {
  2370. case TimeStep.SCALE.YEAR:
  2371. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2372. this.current.setMonth(0);
  2373. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2374. case TimeStep.SCALE.DAY: // intentional fall through
  2375. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2376. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2377. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2378. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2379. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2380. }
  2381. if (this.step != 1) {
  2382. // round down to the first minor value that is a multiple of the current step size
  2383. switch (this.scale) {
  2384. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2385. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2386. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2387. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2388. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2389. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2390. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2391. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2392. default: break;
  2393. }
  2394. }
  2395. };
  2396. /**
  2397. * Check if the there is a next step
  2398. * @return {boolean} true if the current date has not passed the end date
  2399. */
  2400. TimeStep.prototype.hasNext = function () {
  2401. return (this.current.valueOf() <= this._end.valueOf());
  2402. };
  2403. /**
  2404. * Do the next step
  2405. */
  2406. TimeStep.prototype.next = function() {
  2407. var prev = this.current.valueOf();
  2408. // Two cases, needed to prevent issues with switching daylight savings
  2409. // (end of March and end of October)
  2410. if (this.current.getMonth() < 6) {
  2411. switch (this.scale) {
  2412. case TimeStep.SCALE.MILLISECOND:
  2413. this.current = new Date(this.current.valueOf() + this.step); break;
  2414. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2415. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2416. case TimeStep.SCALE.HOUR:
  2417. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2418. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2419. var h = this.current.getHours();
  2420. this.current.setHours(h - (h % this.step));
  2421. break;
  2422. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2423. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2424. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2425. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2426. default: break;
  2427. }
  2428. }
  2429. else {
  2430. switch (this.scale) {
  2431. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2432. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2433. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2434. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2435. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2436. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2437. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2438. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2439. default: break;
  2440. }
  2441. }
  2442. if (this.step != 1) {
  2443. // round down to the correct major value
  2444. switch (this.scale) {
  2445. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2446. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2447. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2448. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2449. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2450. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2451. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2452. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2453. default: break;
  2454. }
  2455. }
  2456. // safety mechanism: if current time is still unchanged, move to the end
  2457. if (this.current.valueOf() == prev) {
  2458. this.current = new Date(this._end.valueOf());
  2459. }
  2460. };
  2461. /**
  2462. * Get the current datetime
  2463. * @return {Date} current The current date
  2464. */
  2465. TimeStep.prototype.getCurrent = function() {
  2466. return this.current;
  2467. };
  2468. /**
  2469. * Set a custom scale. Autoscaling will be disabled.
  2470. * For example setScale(SCALE.MINUTES, 5) will result
  2471. * in minor steps of 5 minutes, and major steps of an hour.
  2472. *
  2473. * @param {TimeStep.SCALE} newScale
  2474. * A scale. Choose from SCALE.MILLISECOND,
  2475. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2476. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2477. * SCALE.YEAR.
  2478. * @param {Number} newStep A step size, by default 1. Choose for
  2479. * example 1, 2, 5, or 10.
  2480. */
  2481. TimeStep.prototype.setScale = function(newScale, newStep) {
  2482. this.scale = newScale;
  2483. if (newStep > 0) {
  2484. this.step = newStep;
  2485. }
  2486. this.autoScale = false;
  2487. };
  2488. /**
  2489. * Enable or disable autoscaling
  2490. * @param {boolean} enable If true, autoascaling is set true
  2491. */
  2492. TimeStep.prototype.setAutoScale = function (enable) {
  2493. this.autoScale = enable;
  2494. };
  2495. /**
  2496. * Automatically determine the scale that bests fits the provided minimum step
  2497. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2498. */
  2499. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2500. if (minimumStep == undefined) {
  2501. return;
  2502. }
  2503. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2504. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2505. var stepDay = (1000 * 60 * 60 * 24);
  2506. var stepHour = (1000 * 60 * 60);
  2507. var stepMinute = (1000 * 60);
  2508. var stepSecond = (1000);
  2509. var stepMillisecond= (1);
  2510. // find the smallest step that is larger than the provided minimumStep
  2511. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2512. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2513. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2514. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2515. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2516. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2517. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2518. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2519. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2520. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2521. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2522. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2523. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2524. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2525. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2526. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2527. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2528. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2529. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2530. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2531. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2532. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2533. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2534. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2535. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2536. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2537. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2538. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2539. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2540. };
  2541. /**
  2542. * Snap a date to a rounded value.
  2543. * The snap intervals are dependent on the current scale and step.
  2544. * @param {Date} date the date to be snapped.
  2545. * @return {Date} snappedDate
  2546. */
  2547. TimeStep.prototype.snap = function(date) {
  2548. var clone = new Date(date.valueOf());
  2549. if (this.scale == TimeStep.SCALE.YEAR) {
  2550. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2551. clone.setFullYear(Math.round(year / this.step) * this.step);
  2552. clone.setMonth(0);
  2553. clone.setDate(0);
  2554. clone.setHours(0);
  2555. clone.setMinutes(0);
  2556. clone.setSeconds(0);
  2557. clone.setMilliseconds(0);
  2558. }
  2559. else if (this.scale == TimeStep.SCALE.MONTH) {
  2560. if (clone.getDate() > 15) {
  2561. clone.setDate(1);
  2562. clone.setMonth(clone.getMonth() + 1);
  2563. // important: first set Date to 1, after that change the month.
  2564. }
  2565. else {
  2566. clone.setDate(1);
  2567. }
  2568. clone.setHours(0);
  2569. clone.setMinutes(0);
  2570. clone.setSeconds(0);
  2571. clone.setMilliseconds(0);
  2572. }
  2573. else if (this.scale == TimeStep.SCALE.DAY) {
  2574. //noinspection FallthroughInSwitchStatementJS
  2575. switch (this.step) {
  2576. case 5:
  2577. case 2:
  2578. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2579. default:
  2580. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2581. }
  2582. clone.setMinutes(0);
  2583. clone.setSeconds(0);
  2584. clone.setMilliseconds(0);
  2585. }
  2586. else if (this.scale == TimeStep.SCALE.WEEKDAY) {
  2587. //noinspection FallthroughInSwitchStatementJS
  2588. switch (this.step) {
  2589. case 5:
  2590. case 2:
  2591. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2592. default:
  2593. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  2594. }
  2595. clone.setMinutes(0);
  2596. clone.setSeconds(0);
  2597. clone.setMilliseconds(0);
  2598. }
  2599. else if (this.scale == TimeStep.SCALE.HOUR) {
  2600. switch (this.step) {
  2601. case 4:
  2602. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2603. default:
  2604. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2605. }
  2606. clone.setSeconds(0);
  2607. clone.setMilliseconds(0);
  2608. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2609. //noinspection FallthroughInSwitchStatementJS
  2610. switch (this.step) {
  2611. case 15:
  2612. case 10:
  2613. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2614. clone.setSeconds(0);
  2615. break;
  2616. case 5:
  2617. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2618. default:
  2619. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2620. }
  2621. clone.setMilliseconds(0);
  2622. }
  2623. else if (this.scale == TimeStep.SCALE.SECOND) {
  2624. //noinspection FallthroughInSwitchStatementJS
  2625. switch (this.step) {
  2626. case 15:
  2627. case 10:
  2628. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2629. clone.setMilliseconds(0);
  2630. break;
  2631. case 5:
  2632. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2633. default:
  2634. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2635. }
  2636. }
  2637. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2638. var step = this.step > 5 ? this.step / 2 : 1;
  2639. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2640. }
  2641. return clone;
  2642. };
  2643. /**
  2644. * Check if the current value is a major value (for example when the step
  2645. * is DAY, a major value is each first day of the MONTH)
  2646. * @return {boolean} true if current date is major, else false.
  2647. */
  2648. TimeStep.prototype.isMajor = function() {
  2649. switch (this.scale) {
  2650. case TimeStep.SCALE.MILLISECOND:
  2651. return (this.current.getMilliseconds() == 0);
  2652. case TimeStep.SCALE.SECOND:
  2653. return (this.current.getSeconds() == 0);
  2654. case TimeStep.SCALE.MINUTE:
  2655. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2656. // Note: this is no bug. Major label is equal for both minute and hour scale
  2657. case TimeStep.SCALE.HOUR:
  2658. return (this.current.getHours() == 0);
  2659. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2660. case TimeStep.SCALE.DAY:
  2661. return (this.current.getDate() == 1);
  2662. case TimeStep.SCALE.MONTH:
  2663. return (this.current.getMonth() == 0);
  2664. case TimeStep.SCALE.YEAR:
  2665. return false;
  2666. default:
  2667. return false;
  2668. }
  2669. };
  2670. /**
  2671. * Returns formatted text for the minor axislabel, depending on the current
  2672. * date and the scale. For example when scale is MINUTE, the current time is
  2673. * formatted as "hh:mm".
  2674. * @param {Date} [date] custom date. if not provided, current date is taken
  2675. */
  2676. TimeStep.prototype.getLabelMinor = function(date) {
  2677. if (date == undefined) {
  2678. date = this.current;
  2679. }
  2680. switch (this.scale) {
  2681. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2682. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2683. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2684. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2685. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2686. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2687. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2688. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2689. default: return '';
  2690. }
  2691. };
  2692. /**
  2693. * Returns formatted text for the major axis label, depending on the current
  2694. * date and the scale. For example when scale is MINUTE, the major scale is
  2695. * hours, and the hour will be formatted as "hh".
  2696. * @param {Date} [date] custom date. if not provided, current date is taken
  2697. */
  2698. TimeStep.prototype.getLabelMajor = function(date) {
  2699. if (date == undefined) {
  2700. date = this.current;
  2701. }
  2702. //noinspection FallthroughInSwitchStatementJS
  2703. switch (this.scale) {
  2704. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2705. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2706. case TimeStep.SCALE.MINUTE:
  2707. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2708. case TimeStep.SCALE.WEEKDAY:
  2709. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2710. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2711. case TimeStep.SCALE.YEAR: return '';
  2712. default: return '';
  2713. }
  2714. };
  2715. /**
  2716. * @constructor Range
  2717. * A Range controls a numeric range with a start and end value.
  2718. * The Range adjusts the range based on mouse events or programmatic changes,
  2719. * and triggers events when the range is changing or has been changed.
  2720. * @param {RootPanel} root Root panel, used to subscribe to events
  2721. * @param {Panel} parent Parent panel, used to attach to the DOM
  2722. * @param {Object} [options] See description at Range.setOptions
  2723. */
  2724. function Range(root, parent, options) {
  2725. this.id = util.randomUUID();
  2726. this.start = null; // Number
  2727. this.end = null; // Number
  2728. this.root = root;
  2729. this.parent = parent;
  2730. this.options = options || {};
  2731. // drag listeners for dragging
  2732. this.root.on('dragstart', this._onDragStart.bind(this));
  2733. this.root.on('drag', this._onDrag.bind(this));
  2734. this.root.on('dragend', this._onDragEnd.bind(this));
  2735. // ignore dragging when holding
  2736. this.root.on('hold', this._onHold.bind(this));
  2737. // mouse wheel for zooming
  2738. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2739. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2740. // pinch to zoom
  2741. this.root.on('touch', this._onTouch.bind(this));
  2742. this.root.on('pinch', this._onPinch.bind(this));
  2743. this.setOptions(options);
  2744. }
  2745. // turn Range into an event emitter
  2746. Emitter(Range.prototype);
  2747. /**
  2748. * Set options for the range controller
  2749. * @param {Object} options Available options:
  2750. * {Number} min Minimum value for start
  2751. * {Number} max Maximum value for end
  2752. * {Number} zoomMin Set a minimum value for
  2753. * (end - start).
  2754. * {Number} zoomMax Set a maximum value for
  2755. * (end - start).
  2756. */
  2757. Range.prototype.setOptions = function (options) {
  2758. util.extend(this.options, options);
  2759. // re-apply range with new limitations
  2760. if (this.start !== null && this.end !== null) {
  2761. this.setRange(this.start, this.end);
  2762. }
  2763. };
  2764. /**
  2765. * Test whether direction has a valid value
  2766. * @param {String} direction 'horizontal' or 'vertical'
  2767. */
  2768. function validateDirection (direction) {
  2769. if (direction != 'horizontal' && direction != 'vertical') {
  2770. throw new TypeError('Unknown direction "' + direction + '". ' +
  2771. 'Choose "horizontal" or "vertical".');
  2772. }
  2773. }
  2774. /**
  2775. * Set a new start and end range
  2776. * @param {Number} [start]
  2777. * @param {Number} [end]
  2778. */
  2779. Range.prototype.setRange = function(start, end) {
  2780. var changed = this._applyRange(start, end);
  2781. if (changed) {
  2782. var params = {
  2783. start: new Date(this.start),
  2784. end: new Date(this.end)
  2785. };
  2786. this.emit('rangechange', params);
  2787. this.emit('rangechanged', params);
  2788. }
  2789. };
  2790. /**
  2791. * Set a new start and end range. This method is the same as setRange, but
  2792. * does not trigger a range change and range changed event, and it returns
  2793. * true when the range is changed
  2794. * @param {Number} [start]
  2795. * @param {Number} [end]
  2796. * @return {Boolean} changed
  2797. * @private
  2798. */
  2799. Range.prototype._applyRange = function(start, end) {
  2800. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2801. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2802. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2803. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2804. diff;
  2805. // check for valid number
  2806. if (isNaN(newStart) || newStart === null) {
  2807. throw new Error('Invalid start "' + start + '"');
  2808. }
  2809. if (isNaN(newEnd) || newEnd === null) {
  2810. throw new Error('Invalid end "' + end + '"');
  2811. }
  2812. // prevent start < end
  2813. if (newEnd < newStart) {
  2814. newEnd = newStart;
  2815. }
  2816. // prevent start < min
  2817. if (min !== null) {
  2818. if (newStart < min) {
  2819. diff = (min - newStart);
  2820. newStart += diff;
  2821. newEnd += diff;
  2822. // prevent end > max
  2823. if (max != null) {
  2824. if (newEnd > max) {
  2825. newEnd = max;
  2826. }
  2827. }
  2828. }
  2829. }
  2830. // prevent end > max
  2831. if (max !== null) {
  2832. if (newEnd > max) {
  2833. diff = (newEnd - max);
  2834. newStart -= diff;
  2835. newEnd -= diff;
  2836. // prevent start < min
  2837. if (min != null) {
  2838. if (newStart < min) {
  2839. newStart = min;
  2840. }
  2841. }
  2842. }
  2843. }
  2844. // prevent (end-start) < zoomMin
  2845. if (this.options.zoomMin !== null) {
  2846. var zoomMin = parseFloat(this.options.zoomMin);
  2847. if (zoomMin < 0) {
  2848. zoomMin = 0;
  2849. }
  2850. if ((newEnd - newStart) < zoomMin) {
  2851. if ((this.end - this.start) === zoomMin) {
  2852. // ignore this action, we are already zoomed to the minimum
  2853. newStart = this.start;
  2854. newEnd = this.end;
  2855. }
  2856. else {
  2857. // zoom to the minimum
  2858. diff = (zoomMin - (newEnd - newStart));
  2859. newStart -= diff / 2;
  2860. newEnd += diff / 2;
  2861. }
  2862. }
  2863. }
  2864. // prevent (end-start) > zoomMax
  2865. if (this.options.zoomMax !== null) {
  2866. var zoomMax = parseFloat(this.options.zoomMax);
  2867. if (zoomMax < 0) {
  2868. zoomMax = 0;
  2869. }
  2870. if ((newEnd - newStart) > zoomMax) {
  2871. if ((this.end - this.start) === zoomMax) {
  2872. // ignore this action, we are already zoomed to the maximum
  2873. newStart = this.start;
  2874. newEnd = this.end;
  2875. }
  2876. else {
  2877. // zoom to the maximum
  2878. diff = ((newEnd - newStart) - zoomMax);
  2879. newStart += diff / 2;
  2880. newEnd -= diff / 2;
  2881. }
  2882. }
  2883. }
  2884. var changed = (this.start != newStart || this.end != newEnd);
  2885. this.start = newStart;
  2886. this.end = newEnd;
  2887. return changed;
  2888. };
  2889. /**
  2890. * Retrieve the current range.
  2891. * @return {Object} An object with start and end properties
  2892. */
  2893. Range.prototype.getRange = function() {
  2894. return {
  2895. start: this.start,
  2896. end: this.end
  2897. };
  2898. };
  2899. /**
  2900. * Calculate the conversion offset and scale for current range, based on
  2901. * the provided width
  2902. * @param {Number} width
  2903. * @returns {{offset: number, scale: number}} conversion
  2904. */
  2905. Range.prototype.conversion = function (width) {
  2906. return Range.conversion(this.start, this.end, width);
  2907. };
  2908. /**
  2909. * Static method to calculate the conversion offset and scale for a range,
  2910. * based on the provided start, end, and width
  2911. * @param {Number} start
  2912. * @param {Number} end
  2913. * @param {Number} width
  2914. * @returns {{offset: number, scale: number}} conversion
  2915. */
  2916. Range.conversion = function (start, end, width) {
  2917. if (width != 0 && (end - start != 0)) {
  2918. return {
  2919. offset: start,
  2920. scale: width / (end - start)
  2921. }
  2922. }
  2923. else {
  2924. return {
  2925. offset: 0,
  2926. scale: 1
  2927. };
  2928. }
  2929. };
  2930. // global (private) object to store drag params
  2931. var touchParams = {};
  2932. /**
  2933. * Start dragging horizontally or vertically
  2934. * @param {Event} event
  2935. * @private
  2936. */
  2937. Range.prototype._onDragStart = function(event) {
  2938. // refuse to drag when we where pinching to prevent the timeline make a jump
  2939. // when releasing the fingers in opposite order from the touch screen
  2940. if (touchParams.ignore) return;
  2941. // TODO: reckon with option movable
  2942. touchParams.start = this.start;
  2943. touchParams.end = this.end;
  2944. var frame = this.parent.frame;
  2945. if (frame) {
  2946. frame.style.cursor = 'move';
  2947. }
  2948. };
  2949. /**
  2950. * Perform dragging operating.
  2951. * @param {Event} event
  2952. * @private
  2953. */
  2954. Range.prototype._onDrag = function (event) {
  2955. var direction = this.options.direction;
  2956. validateDirection(direction);
  2957. // TODO: reckon with option movable
  2958. // refuse to drag when we where pinching to prevent the timeline make a jump
  2959. // when releasing the fingers in opposite order from the touch screen
  2960. if (touchParams.ignore) return;
  2961. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2962. interval = (touchParams.end - touchParams.start),
  2963. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  2964. diffRange = -delta / width * interval;
  2965. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2966. this.emit('rangechange', {
  2967. start: new Date(this.start),
  2968. end: new Date(this.end)
  2969. });
  2970. };
  2971. /**
  2972. * Stop dragging operating.
  2973. * @param {event} event
  2974. * @private
  2975. */
  2976. Range.prototype._onDragEnd = function (event) {
  2977. // refuse to drag when we where pinching to prevent the timeline make a jump
  2978. // when releasing the fingers in opposite order from the touch screen
  2979. if (touchParams.ignore) return;
  2980. // TODO: reckon with option movable
  2981. if (this.parent.frame) {
  2982. this.parent.frame.style.cursor = 'auto';
  2983. }
  2984. // fire a rangechanged event
  2985. this.emit('rangechanged', {
  2986. start: new Date(this.start),
  2987. end: new Date(this.end)
  2988. });
  2989. };
  2990. /**
  2991. * Event handler for mouse wheel event, used to zoom
  2992. * Code from http://adomas.org/javascript-mouse-wheel/
  2993. * @param {Event} event
  2994. * @private
  2995. */
  2996. Range.prototype._onMouseWheel = function(event) {
  2997. // TODO: reckon with option zoomable
  2998. // retrieve delta
  2999. var delta = 0;
  3000. if (event.wheelDelta) { /* IE/Opera. */
  3001. delta = event.wheelDelta / 120;
  3002. } else if (event.detail) { /* Mozilla case. */
  3003. // In Mozilla, sign of delta is different than in IE.
  3004. // Also, delta is multiple of 3.
  3005. delta = -event.detail / 3;
  3006. }
  3007. // If delta is nonzero, handle it.
  3008. // Basically, delta is now positive if wheel was scrolled up,
  3009. // and negative, if wheel was scrolled down.
  3010. if (delta) {
  3011. // perform the zoom action. Delta is normally 1 or -1
  3012. // adjust a negative delta such that zooming in with delta 0.1
  3013. // equals zooming out with a delta -0.1
  3014. var scale;
  3015. if (delta < 0) {
  3016. scale = 1 - (delta / 5);
  3017. }
  3018. else {
  3019. scale = 1 / (1 + (delta / 5)) ;
  3020. }
  3021. // calculate center, the date to zoom around
  3022. var gesture = util.fakeGesture(this, event),
  3023. pointer = getPointer(gesture.center, this.parent.frame),
  3024. pointerDate = this._pointerToDate(pointer);
  3025. this.zoom(scale, pointerDate);
  3026. }
  3027. // Prevent default actions caused by mouse wheel
  3028. // (else the page and timeline both zoom and scroll)
  3029. event.preventDefault();
  3030. };
  3031. /**
  3032. * Start of a touch gesture
  3033. * @private
  3034. */
  3035. Range.prototype._onTouch = function (event) {
  3036. touchParams.start = this.start;
  3037. touchParams.end = this.end;
  3038. touchParams.ignore = false;
  3039. touchParams.center = null;
  3040. // don't move the range when dragging a selected event
  3041. // TODO: it's not so neat to have to know about the state of the ItemSet
  3042. var item = ItemSet.itemFromTarget(event);
  3043. if (item && item.selected && this.options.editable) {
  3044. touchParams.ignore = true;
  3045. }
  3046. };
  3047. /**
  3048. * On start of a hold gesture
  3049. * @private
  3050. */
  3051. Range.prototype._onHold = function () {
  3052. touchParams.ignore = true;
  3053. };
  3054. /**
  3055. * Handle pinch event
  3056. * @param {Event} event
  3057. * @private
  3058. */
  3059. Range.prototype._onPinch = function (event) {
  3060. var direction = this.options.direction;
  3061. touchParams.ignore = true;
  3062. // TODO: reckon with option zoomable
  3063. if (event.gesture.touches.length > 1) {
  3064. if (!touchParams.center) {
  3065. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3066. }
  3067. var scale = 1 / event.gesture.scale,
  3068. initDate = this._pointerToDate(touchParams.center),
  3069. center = getPointer(event.gesture.center, this.parent.frame),
  3070. date = this._pointerToDate(this.parent, center),
  3071. delta = date - initDate; // TODO: utilize delta
  3072. // calculate new start and end
  3073. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3074. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3075. // apply new range
  3076. this.setRange(newStart, newEnd);
  3077. }
  3078. };
  3079. /**
  3080. * Helper function to calculate the center date for zooming
  3081. * @param {{x: Number, y: Number}} pointer
  3082. * @return {number} date
  3083. * @private
  3084. */
  3085. Range.prototype._pointerToDate = function (pointer) {
  3086. var conversion;
  3087. var direction = this.options.direction;
  3088. validateDirection(direction);
  3089. if (direction == 'horizontal') {
  3090. var width = this.parent.width;
  3091. conversion = this.conversion(width);
  3092. return pointer.x / conversion.scale + conversion.offset;
  3093. }
  3094. else {
  3095. var height = this.parent.height;
  3096. conversion = this.conversion(height);
  3097. return pointer.y / conversion.scale + conversion.offset;
  3098. }
  3099. };
  3100. /**
  3101. * Get the pointer location relative to the location of the dom element
  3102. * @param {{pageX: Number, pageY: Number}} touch
  3103. * @param {Element} element HTML DOM element
  3104. * @return {{x: Number, y: Number}} pointer
  3105. * @private
  3106. */
  3107. function getPointer (touch, element) {
  3108. return {
  3109. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3110. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3111. };
  3112. }
  3113. /**
  3114. * Zoom the range the given scale in or out. Start and end date will
  3115. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3116. * date around which to zoom.
  3117. * For example, try scale = 0.9 or 1.1
  3118. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3119. * values below 1 will zoom in.
  3120. * @param {Number} [center] Value representing a date around which will
  3121. * be zoomed.
  3122. */
  3123. Range.prototype.zoom = function(scale, center) {
  3124. // if centerDate is not provided, take it half between start Date and end Date
  3125. if (center == null) {
  3126. center = (this.start + this.end) / 2;
  3127. }
  3128. // calculate new start and end
  3129. var newStart = center + (this.start - center) * scale;
  3130. var newEnd = center + (this.end - center) * scale;
  3131. this.setRange(newStart, newEnd);
  3132. };
  3133. /**
  3134. * Move the range with a given delta to the left or right. Start and end
  3135. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3136. * @param {Number} delta Moving amount. Positive value will move right,
  3137. * negative value will move left
  3138. */
  3139. Range.prototype.move = function(delta) {
  3140. // zoom start Date and end Date relative to the centerDate
  3141. var diff = (this.end - this.start);
  3142. // apply new values
  3143. var newStart = this.start + diff * delta;
  3144. var newEnd = this.end + diff * delta;
  3145. // TODO: reckon with min and max range
  3146. this.start = newStart;
  3147. this.end = newEnd;
  3148. };
  3149. /**
  3150. * Move the range to a new center point
  3151. * @param {Number} moveTo New center point of the range
  3152. */
  3153. Range.prototype.moveTo = function(moveTo) {
  3154. var center = (this.start + this.end) / 2;
  3155. var diff = center - moveTo;
  3156. // calculate new start and end
  3157. var newStart = this.start - diff;
  3158. var newEnd = this.end - diff;
  3159. this.setRange(newStart, newEnd);
  3160. };
  3161. /**
  3162. * Prototype for visual components
  3163. */
  3164. function Component () {
  3165. this.id = null;
  3166. this.parent = null;
  3167. this.childs = null;
  3168. this.options = null;
  3169. this.top = 0;
  3170. this.left = 0;
  3171. this.width = 0;
  3172. this.height = 0;
  3173. }
  3174. // Turn the Component into an event emitter
  3175. Emitter(Component.prototype);
  3176. /**
  3177. * Set parameters for the frame. Parameters will be merged in current parameter
  3178. * set.
  3179. * @param {Object} options Available parameters:
  3180. * {String | function} [className]
  3181. * {String | Number | function} [left]
  3182. * {String | Number | function} [top]
  3183. * {String | Number | function} [width]
  3184. * {String | Number | function} [height]
  3185. */
  3186. Component.prototype.setOptions = function setOptions(options) {
  3187. if (options) {
  3188. util.extend(this.options, options);
  3189. this.repaint();
  3190. }
  3191. };
  3192. /**
  3193. * Get an option value by name
  3194. * The function will first check this.options object, and else will check
  3195. * this.defaultOptions.
  3196. * @param {String} name
  3197. * @return {*} value
  3198. */
  3199. Component.prototype.getOption = function getOption(name) {
  3200. var value;
  3201. if (this.options) {
  3202. value = this.options[name];
  3203. }
  3204. if (value === undefined && this.defaultOptions) {
  3205. value = this.defaultOptions[name];
  3206. }
  3207. return value;
  3208. };
  3209. /**
  3210. * Get the frame element of the component, the outer HTML DOM element.
  3211. * @returns {HTMLElement | null} frame
  3212. */
  3213. Component.prototype.getFrame = function getFrame() {
  3214. // should be implemented by the component
  3215. return null;
  3216. };
  3217. /**
  3218. * Repaint the component
  3219. * @return {boolean} Returns true if the component is resized
  3220. */
  3221. Component.prototype.repaint = function repaint() {
  3222. // should be implemented by the component
  3223. return false;
  3224. };
  3225. /**
  3226. * Test whether the component is resized since the last time _isResized() was
  3227. * called.
  3228. * @return {Boolean} Returns true if the component is resized
  3229. * @protected
  3230. */
  3231. Component.prototype._isResized = function _isResized() {
  3232. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3233. this._previousWidth = this.width;
  3234. this._previousHeight = this.height;
  3235. return resized;
  3236. };
  3237. /**
  3238. * A panel can contain components
  3239. * @param {Object} [options] Available parameters:
  3240. * {String | Number | function} [left]
  3241. * {String | Number | function} [top]
  3242. * {String | Number | function} [width]
  3243. * {String | Number | function} [height]
  3244. * {String | function} [className]
  3245. * @constructor Panel
  3246. * @extends Component
  3247. */
  3248. function Panel(options) {
  3249. this.id = util.randomUUID();
  3250. this.parent = null;
  3251. this.childs = [];
  3252. this.options = options || {};
  3253. // create frame
  3254. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3255. }
  3256. Panel.prototype = new Component();
  3257. /**
  3258. * Set options. Will extend the current options.
  3259. * @param {Object} [options] Available parameters:
  3260. * {String | function} [className]
  3261. * {String | Number | function} [left]
  3262. * {String | Number | function} [top]
  3263. * {String | Number | function} [width]
  3264. * {String | Number | function} [height]
  3265. */
  3266. Panel.prototype.setOptions = Component.prototype.setOptions;
  3267. /**
  3268. * Get the outer frame of the panel
  3269. * @returns {HTMLElement} frame
  3270. */
  3271. Panel.prototype.getFrame = function () {
  3272. return this.frame;
  3273. };
  3274. /**
  3275. * Append a child to the panel
  3276. * @param {Component} child
  3277. */
  3278. Panel.prototype.appendChild = function (child) {
  3279. this.childs.push(child);
  3280. child.parent = this;
  3281. // attach to the DOM
  3282. var frame = child.getFrame();
  3283. if (frame) {
  3284. if (frame.parentNode) {
  3285. frame.parentNode.removeChild(frame);
  3286. }
  3287. this.frame.appendChild(frame);
  3288. }
  3289. };
  3290. /**
  3291. * Insert a child to the panel
  3292. * @param {Component} child
  3293. * @param {Component} beforeChild
  3294. */
  3295. Panel.prototype.insertBefore = function (child, beforeChild) {
  3296. var index = this.childs.indexOf(beforeChild);
  3297. if (index != -1) {
  3298. this.childs.splice(index, 0, child);
  3299. child.parent = this;
  3300. // attach to the DOM
  3301. var frame = child.getFrame();
  3302. if (frame) {
  3303. if (frame.parentNode) {
  3304. frame.parentNode.removeChild(frame);
  3305. }
  3306. var beforeFrame = beforeChild.getFrame();
  3307. if (beforeFrame) {
  3308. this.frame.insertBefore(frame, beforeFrame);
  3309. }
  3310. else {
  3311. this.frame.appendChild(frame);
  3312. }
  3313. }
  3314. }
  3315. };
  3316. /**
  3317. * Remove a child from the panel
  3318. * @param {Component} child
  3319. */
  3320. Panel.prototype.removeChild = function (child) {
  3321. var index = this.childs.indexOf(child);
  3322. if (index != -1) {
  3323. this.childs.splice(index, 1);
  3324. child.parent = null;
  3325. // remove from the DOM
  3326. var frame = child.getFrame();
  3327. if (frame && frame.parentNode) {
  3328. this.frame.removeChild(frame);
  3329. }
  3330. }
  3331. };
  3332. /**
  3333. * Test whether the panel contains given child
  3334. * @param {Component} child
  3335. */
  3336. Panel.prototype.hasChild = function (child) {
  3337. var index = this.childs.indexOf(child);
  3338. return (index != -1);
  3339. };
  3340. /**
  3341. * Repaint the component
  3342. * @return {boolean} Returns true if the component was resized since previous repaint
  3343. */
  3344. Panel.prototype.repaint = function () {
  3345. var asString = util.option.asString,
  3346. options = this.options,
  3347. frame = this.getFrame();
  3348. // update className
  3349. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3350. // repaint the child components
  3351. var childsResized = this._repaintChilds();
  3352. // update frame size
  3353. this._updateSize();
  3354. return this._isResized() || childsResized;
  3355. };
  3356. /**
  3357. * Repaint all childs of the panel
  3358. * @return {boolean} Returns true if the component is resized
  3359. * @private
  3360. */
  3361. Panel.prototype._repaintChilds = function () {
  3362. var resized = false;
  3363. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3364. resized = this.childs[i].repaint() || resized;
  3365. }
  3366. return resized;
  3367. };
  3368. /**
  3369. * Apply the size from options to the panel, and recalculate it's actual size.
  3370. * @private
  3371. */
  3372. Panel.prototype._updateSize = function () {
  3373. // apply size
  3374. this.frame.style.top = util.option.asSize(this.options.top);
  3375. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3376. this.frame.style.left = util.option.asSize(this.options.left);
  3377. this.frame.style.right = util.option.asSize(this.options.right);
  3378. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3379. this.frame.style.height = util.option.asSize(this.options.height, '');
  3380. // get actual size
  3381. this.top = this.frame.offsetTop;
  3382. this.left = this.frame.offsetLeft;
  3383. this.width = this.frame.offsetWidth;
  3384. this.height = this.frame.offsetHeight;
  3385. };
  3386. /**
  3387. * A root panel can hold components. The root panel must be initialized with
  3388. * a DOM element as container.
  3389. * @param {HTMLElement} container
  3390. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3391. * @constructor RootPanel
  3392. * @extends Panel
  3393. */
  3394. function RootPanel(container, options) {
  3395. this.id = util.randomUUID();
  3396. this.container = container;
  3397. this.options = options || {};
  3398. this.defaultOptions = {
  3399. autoResize: true
  3400. };
  3401. // create the HTML DOM
  3402. this._create();
  3403. // attach the root panel to the provided container
  3404. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3405. this.container.appendChild(this.getFrame());
  3406. this._initWatch();
  3407. }
  3408. RootPanel.prototype = new Panel();
  3409. /**
  3410. * Create the HTML DOM for the root panel
  3411. */
  3412. RootPanel.prototype._create = function _create() {
  3413. // create frame
  3414. this.frame = document.createElement('div');
  3415. // create event listeners for all interesting events, these events will be
  3416. // emitted via emitter
  3417. this.hammer = Hammer(this.frame, {
  3418. prevent_default: true
  3419. });
  3420. this.listeners = {};
  3421. var me = this;
  3422. var events = [
  3423. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3424. 'dragstart', 'drag', 'dragend',
  3425. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3426. ];
  3427. events.forEach(function (event) {
  3428. var listener = function () {
  3429. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3430. me.emit.apply(me, args);
  3431. };
  3432. me.hammer.on(event, listener);
  3433. me.listeners[event] = listener;
  3434. });
  3435. };
  3436. /**
  3437. * Set options. Will extend the current options.
  3438. * @param {Object} [options] Available parameters:
  3439. * {String | function} [className]
  3440. * {String | Number | function} [left]
  3441. * {String | Number | function} [top]
  3442. * {String | Number | function} [width]
  3443. * {String | Number | function} [height]
  3444. * {Boolean | function} [autoResize]
  3445. */
  3446. RootPanel.prototype.setOptions = function setOptions(options) {
  3447. if (options) {
  3448. util.extend(this.options, options);
  3449. this.repaint();
  3450. this._initWatch();
  3451. }
  3452. };
  3453. /**
  3454. * Get the frame of the root panel
  3455. */
  3456. RootPanel.prototype.getFrame = function getFrame() {
  3457. return this.frame;
  3458. };
  3459. /**
  3460. * Repaint the root panel
  3461. */
  3462. RootPanel.prototype.repaint = function repaint() {
  3463. // update class name
  3464. var options = this.options;
  3465. var editable = options.editable.updateTime || options.editable.updateGroup;
  3466. var className = 'vis timeline rootpanel ' + options.orientation + (editable ? ' editable' : '');
  3467. if (options.className) className += ' ' + util.option.asString(className);
  3468. this.frame.className = className;
  3469. // repaint the child components
  3470. var childsResized = this._repaintChilds();
  3471. // update frame size
  3472. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3473. this._updateSize();
  3474. // if the root panel or any of its childs is resized, repaint again,
  3475. // as other components may need to be resized accordingly
  3476. var resized = this._isResized() || childsResized;
  3477. if (resized) {
  3478. setTimeout(this.repaint.bind(this), 0);
  3479. }
  3480. };
  3481. /**
  3482. * Initialize watching when option autoResize is true
  3483. * @private
  3484. */
  3485. RootPanel.prototype._initWatch = function _initWatch() {
  3486. var autoResize = this.getOption('autoResize');
  3487. if (autoResize) {
  3488. this._watch();
  3489. }
  3490. else {
  3491. this._unwatch();
  3492. }
  3493. };
  3494. /**
  3495. * Watch for changes in the size of the frame. On resize, the Panel will
  3496. * automatically redraw itself.
  3497. * @private
  3498. */
  3499. RootPanel.prototype._watch = function _watch() {
  3500. var me = this;
  3501. this._unwatch();
  3502. var checkSize = function checkSize() {
  3503. var autoResize = me.getOption('autoResize');
  3504. if (!autoResize) {
  3505. // stop watching when the option autoResize is changed to false
  3506. me._unwatch();
  3507. return;
  3508. }
  3509. if (me.frame) {
  3510. // check whether the frame is resized
  3511. if ((me.frame.clientWidth != me.lastWidth) ||
  3512. (me.frame.clientHeight != me.lastHeight)) {
  3513. me.lastWidth = me.frame.clientWidth;
  3514. me.lastHeight = me.frame.clientHeight;
  3515. me.repaint();
  3516. // TODO: emit a resize event instead?
  3517. }
  3518. }
  3519. };
  3520. // TODO: automatically cleanup the event listener when the frame is deleted
  3521. util.addEventListener(window, 'resize', checkSize);
  3522. this.watchTimer = setInterval(checkSize, 1000);
  3523. };
  3524. /**
  3525. * Stop watching for a resize of the frame.
  3526. * @private
  3527. */
  3528. RootPanel.prototype._unwatch = function _unwatch() {
  3529. if (this.watchTimer) {
  3530. clearInterval(this.watchTimer);
  3531. this.watchTimer = undefined;
  3532. }
  3533. // TODO: remove event listener on window.resize
  3534. };
  3535. /**
  3536. * A horizontal time axis
  3537. * @param {Object} [options] See TimeAxis.setOptions for the available
  3538. * options.
  3539. * @constructor TimeAxis
  3540. * @extends Component
  3541. */
  3542. function TimeAxis (options) {
  3543. this.id = util.randomUUID();
  3544. this.dom = {
  3545. majorLines: [],
  3546. majorTexts: [],
  3547. minorLines: [],
  3548. minorTexts: [],
  3549. redundant: {
  3550. majorLines: [],
  3551. majorTexts: [],
  3552. minorLines: [],
  3553. minorTexts: []
  3554. }
  3555. };
  3556. this.props = {
  3557. range: {
  3558. start: 0,
  3559. end: 0,
  3560. minimumStep: 0
  3561. },
  3562. lineTop: 0
  3563. };
  3564. this.options = options || {};
  3565. this.defaultOptions = {
  3566. orientation: 'bottom', // supported: 'top', 'bottom'
  3567. // TODO: implement timeaxis orientations 'left' and 'right'
  3568. showMinorLabels: true,
  3569. showMajorLabels: true
  3570. };
  3571. this.range = null;
  3572. // create the HTML DOM
  3573. this._create();
  3574. }
  3575. TimeAxis.prototype = new Component();
  3576. // TODO: comment options
  3577. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3578. /**
  3579. * Create the HTML DOM for the TimeAxis
  3580. */
  3581. TimeAxis.prototype._create = function _create() {
  3582. this.frame = document.createElement('div');
  3583. };
  3584. /**
  3585. * Set a range (start and end)
  3586. * @param {Range | Object} range A Range or an object containing start and end.
  3587. */
  3588. TimeAxis.prototype.setRange = function (range) {
  3589. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3590. throw new TypeError('Range must be an instance of Range, ' +
  3591. 'or an object containing start and end.');
  3592. }
  3593. this.range = range;
  3594. };
  3595. /**
  3596. * Get the outer frame of the time axis
  3597. * @return {HTMLElement} frame
  3598. */
  3599. TimeAxis.prototype.getFrame = function getFrame() {
  3600. return this.frame;
  3601. };
  3602. /**
  3603. * Repaint the component
  3604. * @return {boolean} Returns true if the component is resized
  3605. */
  3606. TimeAxis.prototype.repaint = function () {
  3607. var asSize = util.option.asSize,
  3608. options = this.options,
  3609. props = this.props,
  3610. frame = this.frame;
  3611. // update classname
  3612. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3613. var parent = frame.parentNode;
  3614. if (parent) {
  3615. // calculate character width and height
  3616. this._calculateCharSize();
  3617. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3618. var orientation = this.getOption('orientation'),
  3619. showMinorLabels = this.getOption('showMinorLabels'),
  3620. showMajorLabels = this.getOption('showMajorLabels');
  3621. // determine the width and height of the elemens for the axis
  3622. var parentHeight = this.parent.height;
  3623. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3624. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3625. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3626. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3627. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3628. props.minorLineWidth = 1; // TODO: really calculate width
  3629. props.majorLineHeight = parentHeight + this.height;
  3630. props.majorLineWidth = 1; // TODO: really calculate width
  3631. // take frame offline while updating (is almost twice as fast)
  3632. var beforeChild = frame.nextSibling;
  3633. parent.removeChild(frame);
  3634. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3635. if (orientation == 'top') {
  3636. frame.style.top = '0';
  3637. frame.style.left = '0';
  3638. frame.style.bottom = '';
  3639. frame.style.width = asSize(options.width, '100%');
  3640. frame.style.height = this.height + 'px';
  3641. }
  3642. else { // bottom
  3643. frame.style.top = '';
  3644. frame.style.bottom = '0';
  3645. frame.style.left = '0';
  3646. frame.style.width = asSize(options.width, '100%');
  3647. frame.style.height = this.height + 'px';
  3648. }
  3649. this._repaintLabels();
  3650. this._repaintLine();
  3651. // put frame online again
  3652. if (beforeChild) {
  3653. parent.insertBefore(frame, beforeChild);
  3654. }
  3655. else {
  3656. parent.appendChild(frame)
  3657. }
  3658. }
  3659. return this._isResized();
  3660. };
  3661. /**
  3662. * Repaint major and minor text labels and vertical grid lines
  3663. * @private
  3664. */
  3665. TimeAxis.prototype._repaintLabels = function () {
  3666. var orientation = this.getOption('orientation');
  3667. // calculate range and step (step such that we have space for 7 characters per label)
  3668. var start = util.convert(this.range.start, 'Number'),
  3669. end = util.convert(this.range.end, 'Number'),
  3670. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  3671. -this.options.toTime(0).valueOf();
  3672. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3673. this.step = step;
  3674. // Move all DOM elements to a "redundant" list, where they
  3675. // can be picked for re-use, and clear the lists with lines and texts.
  3676. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3677. var dom = this.dom;
  3678. dom.redundant.majorLines = dom.majorLines;
  3679. dom.redundant.majorTexts = dom.majorTexts;
  3680. dom.redundant.minorLines = dom.minorLines;
  3681. dom.redundant.minorTexts = dom.minorTexts;
  3682. dom.majorLines = [];
  3683. dom.majorTexts = [];
  3684. dom.minorLines = [];
  3685. dom.minorTexts = [];
  3686. step.first();
  3687. var xFirstMajorLabel = undefined;
  3688. var max = 0;
  3689. while (step.hasNext() && max < 1000) {
  3690. max++;
  3691. var cur = step.getCurrent(),
  3692. x = this.options.toScreen(cur),
  3693. isMajor = step.isMajor();
  3694. // TODO: lines must have a width, such that we can create css backgrounds
  3695. if (this.getOption('showMinorLabels')) {
  3696. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3697. }
  3698. if (isMajor && this.getOption('showMajorLabels')) {
  3699. if (x > 0) {
  3700. if (xFirstMajorLabel == undefined) {
  3701. xFirstMajorLabel = x;
  3702. }
  3703. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3704. }
  3705. this._repaintMajorLine(x, orientation);
  3706. }
  3707. else {
  3708. this._repaintMinorLine(x, orientation);
  3709. }
  3710. step.next();
  3711. }
  3712. // create a major label on the left when needed
  3713. if (this.getOption('showMajorLabels')) {
  3714. var leftTime = this.options.toTime(0),
  3715. leftText = step.getLabelMajor(leftTime),
  3716. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3717. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3718. this._repaintMajorText(0, leftText, orientation);
  3719. }
  3720. }
  3721. // Cleanup leftover DOM elements from the redundant list
  3722. util.forEach(this.dom.redundant, function (arr) {
  3723. while (arr.length) {
  3724. var elem = arr.pop();
  3725. if (elem && elem.parentNode) {
  3726. elem.parentNode.removeChild(elem);
  3727. }
  3728. }
  3729. });
  3730. };
  3731. /**
  3732. * Create a minor label for the axis at position x
  3733. * @param {Number} x
  3734. * @param {String} text
  3735. * @param {String} orientation "top" or "bottom" (default)
  3736. * @private
  3737. */
  3738. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3739. // reuse redundant label
  3740. var label = this.dom.redundant.minorTexts.shift();
  3741. if (!label) {
  3742. // create new label
  3743. var content = document.createTextNode('');
  3744. label = document.createElement('div');
  3745. label.appendChild(content);
  3746. label.className = 'text minor';
  3747. this.frame.appendChild(label);
  3748. }
  3749. this.dom.minorTexts.push(label);
  3750. label.childNodes[0].nodeValue = text;
  3751. if (orientation == 'top') {
  3752. label.style.top = this.props.majorLabelHeight + 'px';
  3753. label.style.bottom = '';
  3754. }
  3755. else {
  3756. label.style.top = '';
  3757. label.style.bottom = this.props.majorLabelHeight + 'px';
  3758. }
  3759. label.style.left = x + 'px';
  3760. //label.title = title; // TODO: this is a heavy operation
  3761. };
  3762. /**
  3763. * Create a Major label for the axis at position x
  3764. * @param {Number} x
  3765. * @param {String} text
  3766. * @param {String} orientation "top" or "bottom" (default)
  3767. * @private
  3768. */
  3769. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3770. // reuse redundant label
  3771. var label = this.dom.redundant.majorTexts.shift();
  3772. if (!label) {
  3773. // create label
  3774. var content = document.createTextNode(text);
  3775. label = document.createElement('div');
  3776. label.className = 'text major';
  3777. label.appendChild(content);
  3778. this.frame.appendChild(label);
  3779. }
  3780. this.dom.majorTexts.push(label);
  3781. label.childNodes[0].nodeValue = text;
  3782. //label.title = title; // TODO: this is a heavy operation
  3783. if (orientation == 'top') {
  3784. label.style.top = '0px';
  3785. label.style.bottom = '';
  3786. }
  3787. else {
  3788. label.style.top = '';
  3789. label.style.bottom = '0px';
  3790. }
  3791. label.style.left = x + 'px';
  3792. };
  3793. /**
  3794. * Create a minor line for the axis at position x
  3795. * @param {Number} x
  3796. * @param {String} orientation "top" or "bottom" (default)
  3797. * @private
  3798. */
  3799. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3800. // reuse redundant line
  3801. var line = this.dom.redundant.minorLines.shift();
  3802. if (!line) {
  3803. // create vertical line
  3804. line = document.createElement('div');
  3805. line.className = 'grid vertical minor';
  3806. this.frame.appendChild(line);
  3807. }
  3808. this.dom.minorLines.push(line);
  3809. var props = this.props;
  3810. if (orientation == 'top') {
  3811. line.style.top = this.props.majorLabelHeight + 'px';
  3812. line.style.bottom = '';
  3813. }
  3814. else {
  3815. line.style.top = '';
  3816. line.style.bottom = this.props.majorLabelHeight + 'px';
  3817. }
  3818. line.style.height = props.minorLineHeight + 'px';
  3819. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3820. };
  3821. /**
  3822. * Create a Major line for the axis at position x
  3823. * @param {Number} x
  3824. * @param {String} orientation "top" or "bottom" (default)
  3825. * @private
  3826. */
  3827. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3828. // reuse redundant line
  3829. var line = this.dom.redundant.majorLines.shift();
  3830. if (!line) {
  3831. // create vertical line
  3832. line = document.createElement('DIV');
  3833. line.className = 'grid vertical major';
  3834. this.frame.appendChild(line);
  3835. }
  3836. this.dom.majorLines.push(line);
  3837. var props = this.props;
  3838. if (orientation == 'top') {
  3839. line.style.top = '0px';
  3840. line.style.bottom = '';
  3841. }
  3842. else {
  3843. line.style.top = '';
  3844. line.style.bottom = '0px';
  3845. }
  3846. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3847. line.style.height = props.majorLineHeight + 'px';
  3848. };
  3849. /**
  3850. * Repaint the horizontal line for the axis
  3851. * @private
  3852. */
  3853. TimeAxis.prototype._repaintLine = function() {
  3854. var line = this.dom.line,
  3855. frame = this.frame,
  3856. orientation = this.getOption('orientation');
  3857. // line before all axis elements
  3858. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3859. if (line) {
  3860. // put this line at the end of all childs
  3861. frame.removeChild(line);
  3862. frame.appendChild(line);
  3863. }
  3864. else {
  3865. // create the axis line
  3866. line = document.createElement('div');
  3867. line.className = 'grid horizontal major';
  3868. frame.appendChild(line);
  3869. this.dom.line = line;
  3870. }
  3871. if (orientation == 'top') {
  3872. line.style.top = this.height + 'px';
  3873. line.style.bottom = '';
  3874. }
  3875. else {
  3876. line.style.top = '';
  3877. line.style.bottom = this.height + 'px';
  3878. }
  3879. }
  3880. else {
  3881. if (line && line.parentNode) {
  3882. line.parentNode.removeChild(line);
  3883. delete this.dom.line;
  3884. }
  3885. }
  3886. };
  3887. /**
  3888. * Determine the size of text on the axis (both major and minor axis).
  3889. * The size is calculated only once and then cached in this.props.
  3890. * @private
  3891. */
  3892. TimeAxis.prototype._calculateCharSize = function () {
  3893. // determine the char width and height on the minor axis
  3894. if (!('minorCharHeight' in this.props)) {
  3895. var textMinor = document.createTextNode('0');
  3896. var measureCharMinor = document.createElement('DIV');
  3897. measureCharMinor.className = 'text minor measure';
  3898. measureCharMinor.appendChild(textMinor);
  3899. this.frame.appendChild(measureCharMinor);
  3900. this.props.minorCharHeight = measureCharMinor.clientHeight;
  3901. this.props.minorCharWidth = measureCharMinor.clientWidth;
  3902. this.frame.removeChild(measureCharMinor);
  3903. }
  3904. if (!('majorCharHeight' in this.props)) {
  3905. var textMajor = document.createTextNode('0');
  3906. var measureCharMajor = document.createElement('DIV');
  3907. measureCharMajor.className = 'text major measure';
  3908. measureCharMajor.appendChild(textMajor);
  3909. this.frame.appendChild(measureCharMajor);
  3910. this.props.majorCharHeight = measureCharMajor.clientHeight;
  3911. this.props.majorCharWidth = measureCharMajor.clientWidth;
  3912. this.frame.removeChild(measureCharMajor);
  3913. }
  3914. };
  3915. /**
  3916. * Snap a date to a rounded value.
  3917. * The snap intervals are dependent on the current scale and step.
  3918. * @param {Date} date the date to be snapped.
  3919. * @return {Date} snappedDate
  3920. */
  3921. TimeAxis.prototype.snap = function snap (date) {
  3922. return this.step.snap(date);
  3923. };
  3924. /**
  3925. * A current time bar
  3926. * @param {Range} range
  3927. * @param {Object} [options] Available parameters:
  3928. * {Boolean} [showCurrentTime]
  3929. * @constructor CurrentTime
  3930. * @extends Component
  3931. */
  3932. function CurrentTime (range, options) {
  3933. this.id = util.randomUUID();
  3934. this.range = range;
  3935. this.options = options || {};
  3936. this.defaultOptions = {
  3937. showCurrentTime: false
  3938. };
  3939. this._create();
  3940. }
  3941. CurrentTime.prototype = new Component();
  3942. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3943. /**
  3944. * Create the HTML DOM for the current time bar
  3945. * @private
  3946. */
  3947. CurrentTime.prototype._create = function _create () {
  3948. var bar = document.createElement('div');
  3949. bar.className = 'currenttime';
  3950. bar.style.position = 'absolute';
  3951. bar.style.top = '0px';
  3952. bar.style.height = '100%';
  3953. this.bar = bar;
  3954. };
  3955. /**
  3956. * Get the frame element of the current time bar
  3957. * @returns {HTMLElement} frame
  3958. */
  3959. CurrentTime.prototype.getFrame = function getFrame() {
  3960. return this.bar;
  3961. };
  3962. /**
  3963. * Repaint the component
  3964. * @return {boolean} Returns true if the component is resized
  3965. */
  3966. CurrentTime.prototype.repaint = function repaint() {
  3967. var parent = this.parent;
  3968. var now = new Date();
  3969. var x = this.options.toScreen(now);
  3970. this.bar.style.left = x + 'px';
  3971. this.bar.title = 'Current time: ' + now;
  3972. return false;
  3973. };
  3974. /**
  3975. * Start auto refreshing the current time bar
  3976. */
  3977. CurrentTime.prototype.start = function start() {
  3978. var me = this;
  3979. function update () {
  3980. me.stop();
  3981. // determine interval to refresh
  3982. var scale = me.range.conversion(me.parent.width).scale;
  3983. var interval = 1 / scale / 10;
  3984. if (interval < 30) interval = 30;
  3985. if (interval > 1000) interval = 1000;
  3986. me.repaint();
  3987. // start a timer to adjust for the new time
  3988. me.currentTimeTimer = setTimeout(update, interval);
  3989. }
  3990. update();
  3991. };
  3992. /**
  3993. * Stop auto refreshing the current time bar
  3994. */
  3995. CurrentTime.prototype.stop = function stop() {
  3996. if (this.currentTimeTimer !== undefined) {
  3997. clearTimeout(this.currentTimeTimer);
  3998. delete this.currentTimeTimer;
  3999. }
  4000. };
  4001. /**
  4002. * A custom time bar
  4003. * @param {Object} [options] Available parameters:
  4004. * {Boolean} [showCustomTime]
  4005. * @constructor CustomTime
  4006. * @extends Component
  4007. */
  4008. function CustomTime (options) {
  4009. this.id = util.randomUUID();
  4010. this.options = options || {};
  4011. this.defaultOptions = {
  4012. showCustomTime: false
  4013. };
  4014. this.customTime = new Date();
  4015. this.eventParams = {}; // stores state parameters while dragging the bar
  4016. // create the DOM
  4017. this._create();
  4018. }
  4019. CustomTime.prototype = new Component();
  4020. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4021. /**
  4022. * Create the DOM for the custom time
  4023. * @private
  4024. */
  4025. CustomTime.prototype._create = function _create () {
  4026. var bar = document.createElement('div');
  4027. bar.className = 'customtime';
  4028. bar.style.position = 'absolute';
  4029. bar.style.top = '0px';
  4030. bar.style.height = '100%';
  4031. this.bar = bar;
  4032. var drag = document.createElement('div');
  4033. drag.style.position = 'relative';
  4034. drag.style.top = '0px';
  4035. drag.style.left = '-10px';
  4036. drag.style.height = '100%';
  4037. drag.style.width = '20px';
  4038. bar.appendChild(drag);
  4039. // attach event listeners
  4040. this.hammer = Hammer(bar, {
  4041. prevent_default: true
  4042. });
  4043. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4044. this.hammer.on('drag', this._onDrag.bind(this));
  4045. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4046. };
  4047. /**
  4048. * Get the frame element of the custom time bar
  4049. * @returns {HTMLElement} frame
  4050. */
  4051. CustomTime.prototype.getFrame = function getFrame() {
  4052. return this.bar;
  4053. };
  4054. /**
  4055. * Repaint the component
  4056. * @return {boolean} Returns true if the component is resized
  4057. */
  4058. CustomTime.prototype.repaint = function () {
  4059. var x = this.options.toScreen(this.customTime);
  4060. this.bar.style.left = x + 'px';
  4061. this.bar.title = 'Time: ' + this.customTime;
  4062. return false;
  4063. };
  4064. /**
  4065. * Set custom time.
  4066. * @param {Date} time
  4067. */
  4068. CustomTime.prototype.setCustomTime = function(time) {
  4069. this.customTime = new Date(time.valueOf());
  4070. this.repaint();
  4071. };
  4072. /**
  4073. * Retrieve the current custom time.
  4074. * @return {Date} customTime
  4075. */
  4076. CustomTime.prototype.getCustomTime = function() {
  4077. return new Date(this.customTime.valueOf());
  4078. };
  4079. /**
  4080. * Start moving horizontally
  4081. * @param {Event} event
  4082. * @private
  4083. */
  4084. CustomTime.prototype._onDragStart = function(event) {
  4085. this.eventParams.dragging = true;
  4086. this.eventParams.customTime = this.customTime;
  4087. event.stopPropagation();
  4088. event.preventDefault();
  4089. };
  4090. /**
  4091. * Perform moving operating.
  4092. * @param {Event} event
  4093. * @private
  4094. */
  4095. CustomTime.prototype._onDrag = function (event) {
  4096. if (!this.eventParams.dragging) return;
  4097. var deltaX = event.gesture.deltaX,
  4098. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4099. time = this.options.toTime(x);
  4100. this.setCustomTime(time);
  4101. // fire a timechange event
  4102. this.emit('timechange', {
  4103. time: new Date(this.customTime.valueOf())
  4104. });
  4105. event.stopPropagation();
  4106. event.preventDefault();
  4107. };
  4108. /**
  4109. * Stop moving operating.
  4110. * @param {event} event
  4111. * @private
  4112. */
  4113. CustomTime.prototype._onDragEnd = function (event) {
  4114. if (!this.eventParams.dragging) return;
  4115. // fire a timechanged event
  4116. this.emit('timechanged', {
  4117. time: new Date(this.customTime.valueOf())
  4118. });
  4119. event.stopPropagation();
  4120. event.preventDefault();
  4121. };
  4122. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4123. /**
  4124. * An ItemSet holds a set of items and ranges which can be displayed in a
  4125. * range. The width is determined by the parent of the ItemSet, and the height
  4126. * is determined by the size of the items.
  4127. * @param {Panel} backgroundPanel Panel which can be used to display the
  4128. * vertical lines of box items.
  4129. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4130. * can be displayed.
  4131. * @param {Panel} sidePanel Left side panel holding labels
  4132. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4133. * @constructor ItemSet
  4134. * @extends Panel
  4135. */
  4136. function ItemSet(backgroundPanel, axisPanel, sidePanel, options) {
  4137. this.id = util.randomUUID();
  4138. // one options object is shared by this itemset and all its items
  4139. this.options = options || {};
  4140. this.backgroundPanel = backgroundPanel;
  4141. this.axisPanel = axisPanel;
  4142. this.sidePanel = sidePanel;
  4143. this.itemOptions = Object.create(this.options);
  4144. this.dom = {};
  4145. this.hammer = null;
  4146. var me = this;
  4147. this.itemsData = null; // DataSet
  4148. this.groupsData = null; // DataSet
  4149. this.range = null; // Range or Object {start: number, end: number}
  4150. // listeners for the DataSet of the items
  4151. this.itemListeners = {
  4152. 'add': function (event, params, senderId) {
  4153. if (senderId != me.id) me._onAdd(params.items);
  4154. },
  4155. 'update': function (event, params, senderId) {
  4156. if (senderId != me.id) me._onUpdate(params.items);
  4157. },
  4158. 'remove': function (event, params, senderId) {
  4159. if (senderId != me.id) me._onRemove(params.items);
  4160. }
  4161. };
  4162. // listeners for the DataSet of the groups
  4163. this.groupListeners = {
  4164. 'add': function (event, params, senderId) {
  4165. if (senderId != me.id) me._onAddGroups(params.items);
  4166. },
  4167. 'update': function (event, params, senderId) {
  4168. if (senderId != me.id) me._onUpdateGroups(params.items);
  4169. },
  4170. 'remove': function (event, params, senderId) {
  4171. if (senderId != me.id) me._onRemoveGroups(params.items);
  4172. }
  4173. };
  4174. this.items = {}; // object with an Item for every data item
  4175. this.groups = {}; // Group object for every group
  4176. this.groupIds = [];
  4177. this.selection = []; // list with the ids of all selected nodes
  4178. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4179. this.touchParams = {}; // stores properties while dragging
  4180. // create the HTML DOM
  4181. this._create();
  4182. }
  4183. ItemSet.prototype = new Panel();
  4184. // available item types will be registered here
  4185. ItemSet.types = {
  4186. box: ItemBox,
  4187. range: ItemRange,
  4188. rangeoverflow: ItemRangeOverflow,
  4189. point: ItemPoint
  4190. };
  4191. /**
  4192. * Create the HTML DOM for the ItemSet
  4193. */
  4194. ItemSet.prototype._create = function _create(){
  4195. var frame = document.createElement('div');
  4196. frame['timeline-itemset'] = this;
  4197. this.frame = frame;
  4198. // create background panel
  4199. var background = document.createElement('div');
  4200. background.className = 'background';
  4201. this.backgroundPanel.frame.appendChild(background);
  4202. this.dom.background = background;
  4203. // create foreground panel
  4204. var foreground = document.createElement('div');
  4205. foreground.className = 'foreground';
  4206. frame.appendChild(foreground);
  4207. this.dom.foreground = foreground;
  4208. // create axis panel
  4209. var axis = document.createElement('div');
  4210. axis.className = 'axis';
  4211. this.dom.axis = axis;
  4212. this.axisPanel.frame.appendChild(axis);
  4213. // create labelset
  4214. var labelSet = document.createElement('div');
  4215. labelSet.className = 'labelset';
  4216. this.dom.labelSet = labelSet;
  4217. this.sidePanel.frame.appendChild(labelSet);
  4218. // create ungrouped Group
  4219. this._updateUngrouped();
  4220. // attach event listeners
  4221. // TODO: use event listeners from the rootpanel to improve performance?
  4222. this.hammer = Hammer(frame, {
  4223. prevent_default: true
  4224. });
  4225. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4226. this.hammer.on('drag', this._onDrag.bind(this));
  4227. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4228. };
  4229. /**
  4230. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4231. * @param {Object} [options] The following options are available:
  4232. * {String | function} [className]
  4233. * class name for the itemset
  4234. * {String} [type]
  4235. * Default type for the items. Choose from 'box'
  4236. * (default), 'point', or 'range'. The default
  4237. * Style can be overwritten by individual items.
  4238. * {String} align
  4239. * Alignment for the items, only applicable for
  4240. * ItemBox. Choose 'center' (default), 'left', or
  4241. * 'right'.
  4242. * {String} orientation
  4243. * Orientation of the item set. Choose 'top' or
  4244. * 'bottom' (default).
  4245. * {Number} margin.axis
  4246. * Margin between the axis and the items in pixels.
  4247. * Default is 20.
  4248. * {Number} margin.item
  4249. * Margin between items in pixels. Default is 10.
  4250. * {Number} padding
  4251. * Padding of the contents of an item in pixels.
  4252. * Must correspond with the items css. Default is 5.
  4253. * {Function} snap
  4254. * Function to let items snap to nice dates when
  4255. * dragging items.
  4256. */
  4257. ItemSet.prototype.setOptions = function setOptions(options) {
  4258. Component.prototype.setOptions.call(this, options);
  4259. };
  4260. /**
  4261. * Mark the ItemSet dirty so it will refresh everything with next repaint
  4262. */
  4263. ItemSet.prototype.markDirty = function markDirty() {
  4264. this.groupIds = [];
  4265. this.stackDirty = true;
  4266. };
  4267. /**
  4268. * Hide the component from the DOM
  4269. */
  4270. ItemSet.prototype.hide = function hide() {
  4271. // remove the axis with dots
  4272. if (this.dom.axis.parentNode) {
  4273. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4274. }
  4275. // remove the background with vertical lines
  4276. if (this.dom.background.parentNode) {
  4277. this.dom.background.parentNode.removeChild(this.dom.background);
  4278. }
  4279. // remove the labelset containing all group labels
  4280. if (this.dom.labelSet.parentNode) {
  4281. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  4282. }
  4283. };
  4284. /**
  4285. * Show the component in the DOM (when not already visible).
  4286. * @return {Boolean} changed
  4287. */
  4288. ItemSet.prototype.show = function show() {
  4289. // show axis with dots
  4290. if (!this.dom.axis.parentNode) {
  4291. this.axisPanel.frame.appendChild(this.dom.axis);
  4292. }
  4293. // show background with vertical lines
  4294. if (!this.dom.background.parentNode) {
  4295. this.backgroundPanel.frame.appendChild(this.dom.background);
  4296. }
  4297. // show labelset containing labels
  4298. if (!this.dom.labelSet.parentNode) {
  4299. this.sidePanel.frame.appendChild(this.dom.labelSet);
  4300. }
  4301. };
  4302. /**
  4303. * Set range (start and end).
  4304. * @param {Range | Object} range A Range or an object containing start and end.
  4305. */
  4306. ItemSet.prototype.setRange = function setRange(range) {
  4307. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4308. throw new TypeError('Range must be an instance of Range, ' +
  4309. 'or an object containing start and end.');
  4310. }
  4311. this.range = range;
  4312. };
  4313. /**
  4314. * Set selected items by their id. Replaces the current selection
  4315. * Unknown id's are silently ignored.
  4316. * @param {Array} [ids] An array with zero or more id's of the items to be
  4317. * selected. If ids is an empty array, all items will be
  4318. * unselected.
  4319. */
  4320. ItemSet.prototype.setSelection = function setSelection(ids) {
  4321. var i, ii, id, item;
  4322. if (ids) {
  4323. if (!Array.isArray(ids)) {
  4324. throw new TypeError('Array expected');
  4325. }
  4326. // unselect currently selected items
  4327. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4328. id = this.selection[i];
  4329. item = this.items[id];
  4330. if (item) item.unselect();
  4331. }
  4332. // select items
  4333. this.selection = [];
  4334. for (i = 0, ii = ids.length; i < ii; i++) {
  4335. id = ids[i];
  4336. item = this.items[id];
  4337. if (item) {
  4338. this.selection.push(id);
  4339. item.select();
  4340. }
  4341. }
  4342. }
  4343. };
  4344. /**
  4345. * Get the selected items by their id
  4346. * @return {Array} ids The ids of the selected items
  4347. */
  4348. ItemSet.prototype.getSelection = function getSelection() {
  4349. return this.selection.concat([]);
  4350. };
  4351. /**
  4352. * Deselect a selected item
  4353. * @param {String | Number} id
  4354. * @private
  4355. */
  4356. ItemSet.prototype._deselect = function _deselect(id) {
  4357. var selection = this.selection;
  4358. for (var i = 0, ii = selection.length; i < ii; i++) {
  4359. if (selection[i] == id) { // non-strict comparison!
  4360. selection.splice(i, 1);
  4361. break;
  4362. }
  4363. }
  4364. };
  4365. /**
  4366. * Return the item sets frame
  4367. * @returns {HTMLElement} frame
  4368. */
  4369. ItemSet.prototype.getFrame = function getFrame() {
  4370. return this.frame;
  4371. };
  4372. /**
  4373. * Repaint the component
  4374. * @return {boolean} Returns true if the component is resized
  4375. */
  4376. ItemSet.prototype.repaint = function repaint() {
  4377. var margin = this.options.margin,
  4378. range = this.range,
  4379. asSize = util.option.asSize,
  4380. asString = util.option.asString,
  4381. options = this.options,
  4382. orientation = this.getOption('orientation'),
  4383. resized = false,
  4384. frame = this.frame;
  4385. // TODO: document this feature to specify one margin for both item and axis distance
  4386. if (typeof margin === 'number') {
  4387. margin = {
  4388. item: margin,
  4389. axis: margin
  4390. };
  4391. }
  4392. // update className
  4393. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4394. // reorder the groups (if needed)
  4395. resized = this._orderGroups() || resized;
  4396. // check whether zoomed (in that case we need to re-stack everything)
  4397. // TODO: would be nicer to get this as a trigger from Range
  4398. var visibleInterval = this.range.end - this.range.start;
  4399. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4400. if (zoomed) this.stackDirty = true;
  4401. this.lastVisibleInterval = visibleInterval;
  4402. this.lastWidth = this.width;
  4403. // repaint all groups
  4404. var restack = this.stackDirty,
  4405. firstGroup = this._firstGroup(),
  4406. firstMargin = {
  4407. item: margin.item,
  4408. axis: margin.axis
  4409. },
  4410. nonFirstMargin = {
  4411. item: margin.item,
  4412. axis: margin.item / 2
  4413. },
  4414. height = 0,
  4415. minHeight = margin.axis + margin.item;
  4416. util.forEach(this.groups, function (group) {
  4417. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  4418. resized = group.repaint(range, groupMargin, restack) || resized;
  4419. height += group.height;
  4420. });
  4421. height = Math.max(height, minHeight);
  4422. this.stackDirty = false;
  4423. // reposition frame
  4424. frame.style.left = asSize(options.left, '');
  4425. frame.style.right = asSize(options.right, '');
  4426. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4427. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4428. frame.style.width = asSize(options.width, '100%');
  4429. frame.style.height = asSize(height);
  4430. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4431. // calculate actual size and position
  4432. this.top = frame.offsetTop;
  4433. this.left = frame.offsetLeft;
  4434. this.width = frame.offsetWidth;
  4435. this.height = height;
  4436. // reposition axis
  4437. this.dom.axis.style.left = asSize(options.left, '0');
  4438. this.dom.axis.style.right = asSize(options.right, '');
  4439. this.dom.axis.style.width = asSize(options.width, '100%');
  4440. this.dom.axis.style.height = asSize(0);
  4441. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4442. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4443. // check if this component is resized
  4444. resized = this._isResized() || resized;
  4445. return resized;
  4446. };
  4447. /**
  4448. * Get the first group, aligned with the axis
  4449. * @return {Group | null} firstGroup
  4450. * @private
  4451. */
  4452. ItemSet.prototype._firstGroup = function _firstGroup() {
  4453. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  4454. var firstGroupId = this.groupIds[firstGroupIndex];
  4455. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  4456. return firstGroup || null;
  4457. };
  4458. /**
  4459. * Create or delete the group holding all ungrouped items. This group is used when
  4460. * there are no groups specified.
  4461. * @protected
  4462. */
  4463. ItemSet.prototype._updateUngrouped = function _updateUngrouped() {
  4464. var ungrouped = this.groups[UNGROUPED];
  4465. if (this.groupsData) {
  4466. // remove the group holding all ungrouped items
  4467. if (ungrouped) {
  4468. ungrouped.hide();
  4469. delete this.groups[UNGROUPED];
  4470. }
  4471. }
  4472. else {
  4473. // create a group holding all (unfiltered) items
  4474. if (!ungrouped) {
  4475. var id = null;
  4476. var data = null;
  4477. ungrouped = new Group(id, data, this);
  4478. this.groups[UNGROUPED] = ungrouped;
  4479. for (var itemId in this.items) {
  4480. if (this.items.hasOwnProperty(itemId)) {
  4481. ungrouped.add(this.items[itemId]);
  4482. }
  4483. }
  4484. ungrouped.show();
  4485. }
  4486. }
  4487. };
  4488. /**
  4489. * Get the foreground container element
  4490. * @return {HTMLElement} foreground
  4491. */
  4492. ItemSet.prototype.getForeground = function getForeground() {
  4493. return this.dom.foreground;
  4494. };
  4495. /**
  4496. * Get the background container element
  4497. * @return {HTMLElement} background
  4498. */
  4499. ItemSet.prototype.getBackground = function getBackground() {
  4500. return this.dom.background;
  4501. };
  4502. /**
  4503. * Get the axis container element
  4504. * @return {HTMLElement} axis
  4505. */
  4506. ItemSet.prototype.getAxis = function getAxis() {
  4507. return this.dom.axis;
  4508. };
  4509. /**
  4510. * Get the element for the labelset
  4511. * @return {HTMLElement} labelSet
  4512. */
  4513. ItemSet.prototype.getLabelSet = function getLabelSet() {
  4514. return this.dom.labelSet;
  4515. };
  4516. /**
  4517. * Set items
  4518. * @param {vis.DataSet | null} items
  4519. */
  4520. ItemSet.prototype.setItems = function setItems(items) {
  4521. var me = this,
  4522. ids,
  4523. oldItemsData = this.itemsData;
  4524. // replace the dataset
  4525. if (!items) {
  4526. this.itemsData = null;
  4527. }
  4528. else if (items instanceof DataSet || items instanceof DataView) {
  4529. this.itemsData = items;
  4530. }
  4531. else {
  4532. throw new TypeError('Data must be an instance of DataSet or DataView');
  4533. }
  4534. if (oldItemsData) {
  4535. // unsubscribe from old dataset
  4536. util.forEach(this.itemListeners, function (callback, event) {
  4537. oldItemsData.unsubscribe(event, callback);
  4538. });
  4539. // remove all drawn items
  4540. ids = oldItemsData.getIds();
  4541. this._onRemove(ids);
  4542. }
  4543. if (this.itemsData) {
  4544. // subscribe to new dataset
  4545. var id = this.id;
  4546. util.forEach(this.itemListeners, function (callback, event) {
  4547. me.itemsData.on(event, callback, id);
  4548. });
  4549. // add all new items
  4550. ids = this.itemsData.getIds();
  4551. this._onAdd(ids);
  4552. // update the group holding all ungrouped items
  4553. this._updateUngrouped();
  4554. }
  4555. };
  4556. /**
  4557. * Get the current items
  4558. * @returns {vis.DataSet | null}
  4559. */
  4560. ItemSet.prototype.getItems = function getItems() {
  4561. return this.itemsData;
  4562. };
  4563. /**
  4564. * Set groups
  4565. * @param {vis.DataSet} groups
  4566. */
  4567. ItemSet.prototype.setGroups = function setGroups(groups) {
  4568. var me = this,
  4569. ids;
  4570. // unsubscribe from current dataset
  4571. if (this.groupsData) {
  4572. util.forEach(this.groupListeners, function (callback, event) {
  4573. me.groupsData.unsubscribe(event, callback);
  4574. });
  4575. // remove all drawn groups
  4576. ids = this.groupsData.getIds();
  4577. this.groupsData = null;
  4578. this._onRemoveGroups(ids); // note: this will cause a repaint
  4579. }
  4580. // replace the dataset
  4581. if (!groups) {
  4582. this.groupsData = null;
  4583. }
  4584. else if (groups instanceof DataSet || groups instanceof DataView) {
  4585. this.groupsData = groups;
  4586. }
  4587. else {
  4588. throw new TypeError('Data must be an instance of DataSet or DataView');
  4589. }
  4590. if (this.groupsData) {
  4591. // subscribe to new dataset
  4592. var id = this.id;
  4593. util.forEach(this.groupListeners, function (callback, event) {
  4594. me.groupsData.on(event, callback, id);
  4595. });
  4596. // draw all ms
  4597. ids = this.groupsData.getIds();
  4598. this._onAddGroups(ids);
  4599. }
  4600. // update the group holding all ungrouped items
  4601. this._updateUngrouped();
  4602. // update the order of all items in each group
  4603. this._order();
  4604. this.emit('change');
  4605. };
  4606. /**
  4607. * Get the current groups
  4608. * @returns {vis.DataSet | null} groups
  4609. */
  4610. ItemSet.prototype.getGroups = function getGroups() {
  4611. return this.groupsData;
  4612. };
  4613. /**
  4614. * Remove an item by its id
  4615. * @param {String | Number} id
  4616. */
  4617. ItemSet.prototype.removeItem = function removeItem (id) {
  4618. var item = this.itemsData.get(id),
  4619. dataset = this._myDataSet();
  4620. if (item) {
  4621. // confirm deletion
  4622. this.options.onRemove(item, function (item) {
  4623. if (item) {
  4624. // remove by id here, it is possible that an item has no id defined
  4625. // itself, so better not delete by the item itself
  4626. dataset.remove(id);
  4627. }
  4628. });
  4629. }
  4630. };
  4631. /**
  4632. * Handle updated items
  4633. * @param {Number[]} ids
  4634. * @protected
  4635. */
  4636. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4637. var me = this,
  4638. items = this.items,
  4639. itemOptions = this.itemOptions;
  4640. ids.forEach(function (id) {
  4641. var itemData = me.itemsData.get(id),
  4642. item = items[id],
  4643. type = itemData.type ||
  4644. (itemData.start && itemData.end && 'range') ||
  4645. me.options.type ||
  4646. 'box';
  4647. var constructor = ItemSet.types[type];
  4648. if (item) {
  4649. // update item
  4650. if (!constructor || !(item instanceof constructor)) {
  4651. // item type has changed, delete the item and recreate it
  4652. me._removeItem(item);
  4653. item = null;
  4654. }
  4655. else {
  4656. me._updateItem(item, itemData);
  4657. }
  4658. }
  4659. if (!item) {
  4660. // create item
  4661. if (constructor) {
  4662. item = new constructor(itemData, me.options, itemOptions);
  4663. item.id = id; // TODO: not so nice setting id afterwards
  4664. me._addItem(item);
  4665. }
  4666. else {
  4667. throw new TypeError('Unknown item type "' + type + '"');
  4668. }
  4669. }
  4670. });
  4671. this._order();
  4672. this.stackDirty = true; // force re-stacking of all items next repaint
  4673. this.emit('change');
  4674. };
  4675. /**
  4676. * Handle added items
  4677. * @param {Number[]} ids
  4678. * @protected
  4679. */
  4680. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4681. /**
  4682. * Handle removed items
  4683. * @param {Number[]} ids
  4684. * @protected
  4685. */
  4686. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4687. var count = 0;
  4688. var me = this;
  4689. ids.forEach(function (id) {
  4690. var item = me.items[id];
  4691. if (item) {
  4692. count++;
  4693. me._removeItem(item);
  4694. }
  4695. });
  4696. if (count) {
  4697. // update order
  4698. this._order();
  4699. this.stackDirty = true; // force re-stacking of all items next repaint
  4700. this.emit('change');
  4701. }
  4702. };
  4703. /**
  4704. * Update the order of item in all groups
  4705. * @private
  4706. */
  4707. ItemSet.prototype._order = function _order() {
  4708. // reorder the items in all groups
  4709. // TODO: optimization: only reorder groups affected by the changed items
  4710. util.forEach(this.groups, function (group) {
  4711. group.order();
  4712. });
  4713. };
  4714. /**
  4715. * Handle updated groups
  4716. * @param {Number[]} ids
  4717. * @private
  4718. */
  4719. ItemSet.prototype._onUpdateGroups = function _onUpdateGroups(ids) {
  4720. this._onAddGroups(ids);
  4721. };
  4722. /**
  4723. * Handle changed groups
  4724. * @param {Number[]} ids
  4725. * @private
  4726. */
  4727. ItemSet.prototype._onAddGroups = function _onAddGroups(ids) {
  4728. var me = this;
  4729. ids.forEach(function (id) {
  4730. var groupData = me.groupsData.get(id);
  4731. var group = me.groups[id];
  4732. if (!group) {
  4733. // check for reserved ids
  4734. if (id == UNGROUPED) {
  4735. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  4736. }
  4737. var groupOptions = Object.create(me.options);
  4738. util.extend(groupOptions, {
  4739. height: null
  4740. });
  4741. group = new Group(id, groupData, me);
  4742. me.groups[id] = group;
  4743. // add items with this groupId to the new group
  4744. for (var itemId in me.items) {
  4745. if (me.items.hasOwnProperty(itemId)) {
  4746. var item = me.items[itemId];
  4747. if (item.data.group == id) {
  4748. group.add(item);
  4749. }
  4750. }
  4751. }
  4752. group.order();
  4753. group.show();
  4754. }
  4755. else {
  4756. // update group
  4757. group.setData(groupData);
  4758. }
  4759. });
  4760. this.emit('change');
  4761. };
  4762. /**
  4763. * Handle removed groups
  4764. * @param {Number[]} ids
  4765. * @private
  4766. */
  4767. ItemSet.prototype._onRemoveGroups = function _onRemoveGroups(ids) {
  4768. var groups = this.groups;
  4769. ids.forEach(function (id) {
  4770. var group = groups[id];
  4771. if (group) {
  4772. group.hide();
  4773. delete groups[id];
  4774. }
  4775. });
  4776. this.markDirty();
  4777. this.emit('change');
  4778. };
  4779. /**
  4780. * Reorder the groups if needed
  4781. * @return {boolean} changed
  4782. * @private
  4783. */
  4784. ItemSet.prototype._orderGroups = function () {
  4785. if (this.groupsData) {
  4786. // reorder the groups
  4787. var groupIds = this.groupsData.getIds({
  4788. order: this.options.groupOrder
  4789. });
  4790. var changed = !util.equalArray(groupIds, this.groupIds);
  4791. if (changed) {
  4792. // hide all groups, removes them from the DOM
  4793. var groups = this.groups;
  4794. groupIds.forEach(function (groupId) {
  4795. groups[groupId].hide();
  4796. });
  4797. // show the groups again, attach them to the DOM in correct order
  4798. groupIds.forEach(function (groupId) {
  4799. groups[groupId].show();
  4800. });
  4801. this.groupIds = groupIds;
  4802. }
  4803. return changed;
  4804. }
  4805. else {
  4806. return false;
  4807. }
  4808. };
  4809. /**
  4810. * Add a new item
  4811. * @param {Item} item
  4812. * @private
  4813. */
  4814. ItemSet.prototype._addItem = function _addItem(item) {
  4815. this.items[item.id] = item;
  4816. // add to group
  4817. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4818. var group = this.groups[groupId];
  4819. if (group) group.add(item);
  4820. };
  4821. /**
  4822. * Update an existing item
  4823. * @param {Item} item
  4824. * @param {Object} itemData
  4825. * @private
  4826. */
  4827. ItemSet.prototype._updateItem = function _updateItem(item, itemData) {
  4828. var oldGroupId = item.data.group;
  4829. item.data = itemData;
  4830. if (item.displayed) {
  4831. item.repaint();
  4832. }
  4833. // update group
  4834. if (oldGroupId != item.data.group) {
  4835. var oldGroup = this.groups[oldGroupId];
  4836. if (oldGroup) oldGroup.remove(item);
  4837. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4838. var group = this.groups[groupId];
  4839. if (group) group.add(item);
  4840. }
  4841. };
  4842. /**
  4843. * Delete an item from the ItemSet: remove it from the DOM, from the map
  4844. * with items, and from the map with visible items, and from the selection
  4845. * @param {Item} item
  4846. * @private
  4847. */
  4848. ItemSet.prototype._removeItem = function _removeItem(item) {
  4849. // remove from DOM
  4850. item.hide();
  4851. // remove from items
  4852. delete this.items[item.id];
  4853. // remove from selection
  4854. var index = this.selection.indexOf(item.id);
  4855. if (index != -1) this.selection.splice(index, 1);
  4856. // remove from group
  4857. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4858. var group = this.groups[groupId];
  4859. if (group) group.remove(item);
  4860. };
  4861. /**
  4862. * Create an array containing all items being a range (having an end date)
  4863. * @param array
  4864. * @returns {Array}
  4865. * @private
  4866. */
  4867. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  4868. var endArray = [];
  4869. for (var i = 0; i < array.length; i++) {
  4870. if (array[i] instanceof ItemRange) {
  4871. endArray.push(array[i]);
  4872. }
  4873. }
  4874. return endArray;
  4875. };
  4876. /**
  4877. * Get the width of the group labels
  4878. * @return {Number} width
  4879. */
  4880. ItemSet.prototype.getLabelsWidth = function getLabelsWidth() {
  4881. var width = 0;
  4882. util.forEach(this.groups, function (group) {
  4883. width = Math.max(width, group.getLabelWidth());
  4884. });
  4885. return width;
  4886. };
  4887. /**
  4888. * Get the height of the itemsets background
  4889. * @return {Number} height
  4890. */
  4891. ItemSet.prototype.getBackgroundHeight = function getBackgroundHeight() {
  4892. return this.height;
  4893. };
  4894. /**
  4895. * Start dragging the selected events
  4896. * @param {Event} event
  4897. * @private
  4898. */
  4899. ItemSet.prototype._onDragStart = function (event) {
  4900. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  4901. return;
  4902. }
  4903. var item = ItemSet.itemFromTarget(event),
  4904. me = this,
  4905. props;
  4906. if (item && item.selected) {
  4907. var dragLeftItem = event.target.dragLeftItem;
  4908. var dragRightItem = event.target.dragRightItem;
  4909. if (dragLeftItem) {
  4910. props = {
  4911. item: dragLeftItem
  4912. };
  4913. if (me.options.editable.updateTime) {
  4914. props.start = item.data.start.valueOf();
  4915. }
  4916. if (me.options.editable.updateGroup) {
  4917. if ('group' in item.data) props.group = item.data.group;
  4918. }
  4919. this.touchParams.itemProps = [props];
  4920. }
  4921. else if (dragRightItem) {
  4922. props = {
  4923. item: dragRightItem
  4924. };
  4925. if (me.options.editable.updateTime) {
  4926. props.end = item.data.end.valueOf();
  4927. }
  4928. if (me.options.editable.updateGroup) {
  4929. if ('group' in item.data) props.group = item.data.group;
  4930. }
  4931. this.touchParams.itemProps = [props];
  4932. }
  4933. else {
  4934. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4935. var item = me.items[id];
  4936. var props = {
  4937. item: item
  4938. };
  4939. if (me.options.editable.updateTime) {
  4940. if ('start' in item.data) props.start = item.data.start.valueOf();
  4941. if ('end' in item.data) props.end = item.data.end.valueOf();
  4942. }
  4943. if (me.options.editable.updateGroup) {
  4944. if ('group' in item.data) props.group = item.data.group;
  4945. }
  4946. return props;
  4947. });
  4948. }
  4949. event.stopPropagation();
  4950. }
  4951. };
  4952. /**
  4953. * Drag selected items
  4954. * @param {Event} event
  4955. * @private
  4956. */
  4957. ItemSet.prototype._onDrag = function (event) {
  4958. if (this.touchParams.itemProps) {
  4959. var snap = this.options.snap || null,
  4960. deltaX = event.gesture.deltaX,
  4961. scale = (this.width / (this.range.end - this.range.start)),
  4962. offset = deltaX / scale;
  4963. // move
  4964. this.touchParams.itemProps.forEach(function (props) {
  4965. if ('start' in props) {
  4966. var start = new Date(props.start + offset);
  4967. props.item.data.start = snap ? snap(start) : start;
  4968. }
  4969. if ('end' in props) {
  4970. var end = new Date(props.end + offset);
  4971. props.item.data.end = snap ? snap(end) : end;
  4972. }
  4973. if ('group' in props) {
  4974. // drag from one group to another
  4975. var group = ItemSet.groupFromTarget(event);
  4976. if (group && group.groupId != props.item.data.group) {
  4977. var oldGroup = props.item.parent;
  4978. oldGroup.remove(props.item);
  4979. oldGroup.order();
  4980. group.add(props.item);
  4981. group.order();
  4982. props.item.data.group = group.groupId;
  4983. }
  4984. }
  4985. });
  4986. // TODO: implement onMoving handler
  4987. this.stackDirty = true; // force re-stacking of all items next repaint
  4988. this.emit('change');
  4989. event.stopPropagation();
  4990. }
  4991. };
  4992. /**
  4993. * End of dragging selected items
  4994. * @param {Event} event
  4995. * @private
  4996. */
  4997. ItemSet.prototype._onDragEnd = function (event) {
  4998. if (this.touchParams.itemProps) {
  4999. // prepare a change set for the changed items
  5000. var changes = [],
  5001. me = this,
  5002. dataset = this._myDataSet();
  5003. this.touchParams.itemProps.forEach(function (props) {
  5004. var id = props.item.id,
  5005. itemData = me.itemsData.get(id);
  5006. var changed = false;
  5007. if ('start' in props.item.data) {
  5008. changed = (props.start != props.item.data.start.valueOf());
  5009. itemData.start = util.convert(props.item.data.start, dataset.convert['start']);
  5010. }
  5011. if ('end' in props.item.data) {
  5012. changed = changed || (props.end != props.item.data.end.valueOf());
  5013. itemData.end = util.convert(props.item.data.end, dataset.convert['end']);
  5014. }
  5015. if ('group' in props.item.data) {
  5016. changed = changed || (props.group != props.item.data.group);
  5017. itemData.group = props.item.data.group;
  5018. }
  5019. // only apply changes when start or end is actually changed
  5020. if (changed) {
  5021. me.options.onMove(itemData, function (itemData) {
  5022. if (itemData) {
  5023. // apply changes
  5024. itemData[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  5025. changes.push(itemData);
  5026. }
  5027. else {
  5028. // restore original values
  5029. if ('start' in props) props.item.data.start = props.start;
  5030. if ('end' in props) props.item.data.end = props.end;
  5031. me.stackDirty = true; // force re-stacking of all items next repaint
  5032. me.emit('change');
  5033. }
  5034. });
  5035. }
  5036. });
  5037. this.touchParams.itemProps = null;
  5038. // apply the changes to the data (if there are changes)
  5039. if (changes.length) {
  5040. dataset.update(changes);
  5041. }
  5042. event.stopPropagation();
  5043. }
  5044. };
  5045. /**
  5046. * Find an item from an event target:
  5047. * searches for the attribute 'timeline-item' in the event target's element tree
  5048. * @param {Event} event
  5049. * @return {Item | null} item
  5050. */
  5051. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5052. var target = event.target;
  5053. while (target) {
  5054. if (target.hasOwnProperty('timeline-item')) {
  5055. return target['timeline-item'];
  5056. }
  5057. target = target.parentNode;
  5058. }
  5059. return null;
  5060. };
  5061. /**
  5062. * Find the Group from an event target:
  5063. * searches for the attribute 'timeline-group' in the event target's element tree
  5064. * @param {Event} event
  5065. * @return {Group | null} group
  5066. */
  5067. ItemSet.groupFromTarget = function groupFromTarget (event) {
  5068. var target = event.target;
  5069. while (target) {
  5070. if (target.hasOwnProperty('timeline-group')) {
  5071. return target['timeline-group'];
  5072. }
  5073. target = target.parentNode;
  5074. }
  5075. return null;
  5076. };
  5077. /**
  5078. * Find the ItemSet from an event target:
  5079. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5080. * @param {Event} event
  5081. * @return {ItemSet | null} item
  5082. */
  5083. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5084. var target = event.target;
  5085. while (target) {
  5086. if (target.hasOwnProperty('timeline-itemset')) {
  5087. return target['timeline-itemset'];
  5088. }
  5089. target = target.parentNode;
  5090. }
  5091. return null;
  5092. };
  5093. /**
  5094. * Find the DataSet to which this ItemSet is connected
  5095. * @returns {null | DataSet} dataset
  5096. * @private
  5097. */
  5098. ItemSet.prototype._myDataSet = function _myDataSet() {
  5099. // find the root DataSet
  5100. var dataset = this.itemsData;
  5101. while (dataset instanceof DataView) {
  5102. dataset = dataset.data;
  5103. }
  5104. return dataset;
  5105. };
  5106. /**
  5107. * @constructor Item
  5108. * @param {Object} data Object containing (optional) parameters type,
  5109. * start, end, content, group, className.
  5110. * @param {Object} [options] Options to set initial property values
  5111. * @param {Object} [defaultOptions] default options
  5112. * // TODO: describe available options
  5113. */
  5114. function Item (data, options, defaultOptions) {
  5115. this.id = null;
  5116. this.parent = null;
  5117. this.data = data;
  5118. this.dom = null;
  5119. this.options = options || {};
  5120. this.defaultOptions = defaultOptions || {};
  5121. this.selected = false;
  5122. this.displayed = false;
  5123. this.dirty = true;
  5124. this.top = null;
  5125. this.left = null;
  5126. this.width = null;
  5127. this.height = null;
  5128. }
  5129. /**
  5130. * Select current item
  5131. */
  5132. Item.prototype.select = function select() {
  5133. this.selected = true;
  5134. if (this.displayed) this.repaint();
  5135. };
  5136. /**
  5137. * Unselect current item
  5138. */
  5139. Item.prototype.unselect = function unselect() {
  5140. this.selected = false;
  5141. if (this.displayed) this.repaint();
  5142. };
  5143. /**
  5144. * Set a parent for the item
  5145. * @param {ItemSet | Group} parent
  5146. */
  5147. Item.prototype.setParent = function setParent(parent) {
  5148. if (this.displayed) {
  5149. this.hide();
  5150. this.parent = parent;
  5151. if (this.parent) {
  5152. this.show();
  5153. }
  5154. }
  5155. else {
  5156. this.parent = parent;
  5157. }
  5158. };
  5159. /**
  5160. * Check whether this item is visible inside given range
  5161. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5162. * @returns {boolean} True if visible
  5163. */
  5164. Item.prototype.isVisible = function isVisible (range) {
  5165. // Should be implemented by Item implementations
  5166. return false;
  5167. };
  5168. /**
  5169. * Show the Item in the DOM (when not already visible)
  5170. * @return {Boolean} changed
  5171. */
  5172. Item.prototype.show = function show() {
  5173. return false;
  5174. };
  5175. /**
  5176. * Hide the Item from the DOM (when visible)
  5177. * @return {Boolean} changed
  5178. */
  5179. Item.prototype.hide = function hide() {
  5180. return false;
  5181. };
  5182. /**
  5183. * Repaint the item
  5184. */
  5185. Item.prototype.repaint = function repaint() {
  5186. // should be implemented by the item
  5187. };
  5188. /**
  5189. * Reposition the Item horizontally
  5190. */
  5191. Item.prototype.repositionX = function repositionX() {
  5192. // should be implemented by the item
  5193. };
  5194. /**
  5195. * Reposition the Item vertically
  5196. */
  5197. Item.prototype.repositionY = function repositionY() {
  5198. // should be implemented by the item
  5199. };
  5200. /**
  5201. * Repaint a delete button on the top right of the item when the item is selected
  5202. * @param {HTMLElement} anchor
  5203. * @protected
  5204. */
  5205. Item.prototype._repaintDeleteButton = function (anchor) {
  5206. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  5207. // create and show button
  5208. var me = this;
  5209. var deleteButton = document.createElement('div');
  5210. deleteButton.className = 'delete';
  5211. deleteButton.title = 'Delete this item';
  5212. Hammer(deleteButton, {
  5213. preventDefault: true
  5214. }).on('tap', function (event) {
  5215. me.parent.removeFromDataSet(me);
  5216. event.stopPropagation();
  5217. });
  5218. anchor.appendChild(deleteButton);
  5219. this.dom.deleteButton = deleteButton;
  5220. }
  5221. else if (!this.selected && this.dom.deleteButton) {
  5222. // remove button
  5223. if (this.dom.deleteButton.parentNode) {
  5224. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5225. }
  5226. this.dom.deleteButton = null;
  5227. }
  5228. };
  5229. /**
  5230. * @constructor ItemBox
  5231. * @extends Item
  5232. * @param {Object} data Object containing parameters start
  5233. * content, className.
  5234. * @param {Object} [options] Options to set initial property values
  5235. * @param {Object} [defaultOptions] default options
  5236. * // TODO: describe available options
  5237. */
  5238. function ItemBox (data, options, defaultOptions) {
  5239. this.props = {
  5240. dot: {
  5241. width: 0,
  5242. height: 0
  5243. },
  5244. line: {
  5245. width: 0,
  5246. height: 0
  5247. }
  5248. };
  5249. // validate data
  5250. if (data) {
  5251. if (data.start == undefined) {
  5252. throw new Error('Property "start" missing in item ' + data);
  5253. }
  5254. }
  5255. Item.call(this, data, options, defaultOptions);
  5256. }
  5257. ItemBox.prototype = new Item (null);
  5258. /**
  5259. * Check whether this item is visible inside given range
  5260. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5261. * @returns {boolean} True if visible
  5262. */
  5263. ItemBox.prototype.isVisible = function isVisible (range) {
  5264. // determine visibility
  5265. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5266. var interval = (range.end - range.start) / 4;
  5267. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5268. };
  5269. /**
  5270. * Repaint the item
  5271. */
  5272. ItemBox.prototype.repaint = function repaint() {
  5273. var dom = this.dom;
  5274. if (!dom) {
  5275. // create DOM
  5276. this.dom = {};
  5277. dom = this.dom;
  5278. // create main box
  5279. dom.box = document.createElement('DIV');
  5280. // contents box (inside the background box). used for making margins
  5281. dom.content = document.createElement('DIV');
  5282. dom.content.className = 'content';
  5283. dom.box.appendChild(dom.content);
  5284. // line to axis
  5285. dom.line = document.createElement('DIV');
  5286. dom.line.className = 'line';
  5287. // dot on axis
  5288. dom.dot = document.createElement('DIV');
  5289. dom.dot.className = 'dot';
  5290. // attach this item as attribute
  5291. dom.box['timeline-item'] = this;
  5292. }
  5293. // append DOM to parent DOM
  5294. if (!this.parent) {
  5295. throw new Error('Cannot repaint item: no parent attached');
  5296. }
  5297. if (!dom.box.parentNode) {
  5298. var foreground = this.parent.getForeground();
  5299. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5300. foreground.appendChild(dom.box);
  5301. }
  5302. if (!dom.line.parentNode) {
  5303. var background = this.parent.getBackground();
  5304. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5305. background.appendChild(dom.line);
  5306. }
  5307. if (!dom.dot.parentNode) {
  5308. var axis = this.parent.getAxis();
  5309. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5310. axis.appendChild(dom.dot);
  5311. }
  5312. this.displayed = true;
  5313. // update contents
  5314. if (this.data.content != this.content) {
  5315. this.content = this.data.content;
  5316. if (this.content instanceof Element) {
  5317. dom.content.innerHTML = '';
  5318. dom.content.appendChild(this.content);
  5319. }
  5320. else if (this.data.content != undefined) {
  5321. dom.content.innerHTML = this.content;
  5322. }
  5323. else {
  5324. throw new Error('Property "content" missing in item ' + this.data.id);
  5325. }
  5326. this.dirty = true;
  5327. }
  5328. // update class
  5329. var className = (this.data.className? ' ' + this.data.className : '') +
  5330. (this.selected ? ' selected' : '');
  5331. if (this.className != className) {
  5332. this.className = className;
  5333. dom.box.className = 'item box' + className;
  5334. dom.line.className = 'item line' + className;
  5335. dom.dot.className = 'item dot' + className;
  5336. this.dirty = true;
  5337. }
  5338. // recalculate size
  5339. if (this.dirty) {
  5340. this.props.dot.height = dom.dot.offsetHeight;
  5341. this.props.dot.width = dom.dot.offsetWidth;
  5342. this.props.line.width = dom.line.offsetWidth;
  5343. this.width = dom.box.offsetWidth;
  5344. this.height = dom.box.offsetHeight;
  5345. this.dirty = false;
  5346. }
  5347. this._repaintDeleteButton(dom.box);
  5348. };
  5349. /**
  5350. * Show the item in the DOM (when not already displayed). The items DOM will
  5351. * be created when needed.
  5352. */
  5353. ItemBox.prototype.show = function show() {
  5354. if (!this.displayed) {
  5355. this.repaint();
  5356. }
  5357. };
  5358. /**
  5359. * Hide the item from the DOM (when visible)
  5360. */
  5361. ItemBox.prototype.hide = function hide() {
  5362. if (this.displayed) {
  5363. var dom = this.dom;
  5364. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5365. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5366. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5367. this.top = null;
  5368. this.left = null;
  5369. this.displayed = false;
  5370. }
  5371. };
  5372. /**
  5373. * Reposition the item horizontally
  5374. * @Override
  5375. */
  5376. ItemBox.prototype.repositionX = function repositionX() {
  5377. var start = this.defaultOptions.toScreen(this.data.start),
  5378. align = this.options.align || this.defaultOptions.align,
  5379. left,
  5380. box = this.dom.box,
  5381. line = this.dom.line,
  5382. dot = this.dom.dot;
  5383. // calculate left position of the box
  5384. if (align == 'right') {
  5385. this.left = start - this.width;
  5386. }
  5387. else if (align == 'left') {
  5388. this.left = start;
  5389. }
  5390. else {
  5391. // default or 'center'
  5392. this.left = start - this.width / 2;
  5393. }
  5394. // reposition box
  5395. box.style.left = this.left + 'px';
  5396. // reposition line
  5397. line.style.left = (start - this.props.line.width / 2) + 'px';
  5398. // reposition dot
  5399. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5400. };
  5401. /**
  5402. * Reposition the item vertically
  5403. * @Override
  5404. */
  5405. ItemBox.prototype.repositionY = function repositionY () {
  5406. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5407. box = this.dom.box,
  5408. line = this.dom.line,
  5409. dot = this.dom.dot;
  5410. if (orientation == 'top') {
  5411. box.style.top = (this.top || 0) + 'px';
  5412. box.style.bottom = '';
  5413. line.style.top = '0';
  5414. line.style.bottom = '';
  5415. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5416. }
  5417. else { // orientation 'bottom'
  5418. box.style.top = '';
  5419. box.style.bottom = (this.top || 0) + 'px';
  5420. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5421. line.style.bottom = '0';
  5422. line.style.height = '';
  5423. }
  5424. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5425. };
  5426. /**
  5427. * @constructor ItemPoint
  5428. * @extends Item
  5429. * @param {Object} data Object containing parameters start
  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 ItemPoint (data, options, defaultOptions) {
  5436. this.props = {
  5437. dot: {
  5438. top: 0,
  5439. width: 0,
  5440. height: 0
  5441. },
  5442. content: {
  5443. height: 0,
  5444. marginLeft: 0
  5445. }
  5446. };
  5447. // validate data
  5448. if (data) {
  5449. if (data.start == undefined) {
  5450. throw new Error('Property "start" missing in item ' + data);
  5451. }
  5452. }
  5453. Item.call(this, data, options, defaultOptions);
  5454. }
  5455. ItemPoint.prototype = new Item (null);
  5456. /**
  5457. * Check whether this item is visible inside given range
  5458. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5459. * @returns {boolean} True if visible
  5460. */
  5461. ItemPoint.prototype.isVisible = function isVisible (range) {
  5462. // determine visibility
  5463. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5464. var interval = (range.end - range.start) / 4;
  5465. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5466. };
  5467. /**
  5468. * Repaint the item
  5469. */
  5470. ItemPoint.prototype.repaint = function repaint() {
  5471. var dom = this.dom;
  5472. if (!dom) {
  5473. // create DOM
  5474. this.dom = {};
  5475. dom = this.dom;
  5476. // background box
  5477. dom.point = document.createElement('div');
  5478. // className is updated in repaint()
  5479. // contents box, right from the dot
  5480. dom.content = document.createElement('div');
  5481. dom.content.className = 'content';
  5482. dom.point.appendChild(dom.content);
  5483. // dot at start
  5484. dom.dot = document.createElement('div');
  5485. dom.point.appendChild(dom.dot);
  5486. // attach this item as attribute
  5487. dom.point['timeline-item'] = this;
  5488. }
  5489. // append DOM to parent DOM
  5490. if (!this.parent) {
  5491. throw new Error('Cannot repaint item: no parent attached');
  5492. }
  5493. if (!dom.point.parentNode) {
  5494. var foreground = this.parent.getForeground();
  5495. if (!foreground) {
  5496. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5497. }
  5498. foreground.appendChild(dom.point);
  5499. }
  5500. this.displayed = true;
  5501. // update contents
  5502. if (this.data.content != this.content) {
  5503. this.content = this.data.content;
  5504. if (this.content instanceof Element) {
  5505. dom.content.innerHTML = '';
  5506. dom.content.appendChild(this.content);
  5507. }
  5508. else if (this.data.content != undefined) {
  5509. dom.content.innerHTML = this.content;
  5510. }
  5511. else {
  5512. throw new Error('Property "content" missing in item ' + this.data.id);
  5513. }
  5514. this.dirty = true;
  5515. }
  5516. // update class
  5517. var className = (this.data.className? ' ' + this.data.className : '') +
  5518. (this.selected ? ' selected' : '');
  5519. if (this.className != className) {
  5520. this.className = className;
  5521. dom.point.className = 'item point' + className;
  5522. dom.dot.className = 'item dot' + className;
  5523. this.dirty = true;
  5524. }
  5525. // recalculate size
  5526. if (this.dirty) {
  5527. this.width = dom.point.offsetWidth;
  5528. this.height = dom.point.offsetHeight;
  5529. this.props.dot.width = dom.dot.offsetWidth;
  5530. this.props.dot.height = dom.dot.offsetHeight;
  5531. this.props.content.height = dom.content.offsetHeight;
  5532. // resize contents
  5533. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  5534. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5535. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5536. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  5537. this.dirty = false;
  5538. }
  5539. this._repaintDeleteButton(dom.point);
  5540. };
  5541. /**
  5542. * Show the item in the DOM (when not already visible). The items DOM will
  5543. * be created when needed.
  5544. */
  5545. ItemPoint.prototype.show = function show() {
  5546. if (!this.displayed) {
  5547. this.repaint();
  5548. }
  5549. };
  5550. /**
  5551. * Hide the item from the DOM (when visible)
  5552. */
  5553. ItemPoint.prototype.hide = function hide() {
  5554. if (this.displayed) {
  5555. if (this.dom.point.parentNode) {
  5556. this.dom.point.parentNode.removeChild(this.dom.point);
  5557. }
  5558. this.top = null;
  5559. this.left = null;
  5560. this.displayed = false;
  5561. }
  5562. };
  5563. /**
  5564. * Reposition the item horizontally
  5565. * @Override
  5566. */
  5567. ItemPoint.prototype.repositionX = function repositionX() {
  5568. var start = this.defaultOptions.toScreen(this.data.start);
  5569. this.left = start - this.props.dot.width;
  5570. // reposition point
  5571. this.dom.point.style.left = this.left + 'px';
  5572. };
  5573. /**
  5574. * Reposition the item vertically
  5575. * @Override
  5576. */
  5577. ItemPoint.prototype.repositionY = function repositionY () {
  5578. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5579. point = this.dom.point;
  5580. if (orientation == 'top') {
  5581. point.style.top = this.top + 'px';
  5582. point.style.bottom = '';
  5583. }
  5584. else {
  5585. point.style.top = '';
  5586. point.style.bottom = this.top + 'px';
  5587. }
  5588. };
  5589. /**
  5590. * @constructor ItemRange
  5591. * @extends Item
  5592. * @param {Object} data Object containing parameters start, end
  5593. * content, className.
  5594. * @param {Object} [options] Options to set initial property values
  5595. * @param {Object} [defaultOptions] default options
  5596. * // TODO: describe available options
  5597. */
  5598. function ItemRange (data, options, defaultOptions) {
  5599. this.props = {
  5600. content: {
  5601. width: 0
  5602. }
  5603. };
  5604. // validate data
  5605. if (data) {
  5606. if (data.start == undefined) {
  5607. throw new Error('Property "start" missing in item ' + data.id);
  5608. }
  5609. if (data.end == undefined) {
  5610. throw new Error('Property "end" missing in item ' + data.id);
  5611. }
  5612. }
  5613. Item.call(this, data, options, defaultOptions);
  5614. }
  5615. ItemRange.prototype = new Item (null);
  5616. ItemRange.prototype.baseClassName = 'item range';
  5617. /**
  5618. * Check whether this item is visible inside given range
  5619. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5620. * @returns {boolean} True if visible
  5621. */
  5622. ItemRange.prototype.isVisible = function isVisible (range) {
  5623. // determine visibility
  5624. return (this.data.start < range.end) && (this.data.end > range.start);
  5625. };
  5626. /**
  5627. * Repaint the item
  5628. */
  5629. ItemRange.prototype.repaint = function repaint() {
  5630. var dom = this.dom;
  5631. if (!dom) {
  5632. // create DOM
  5633. this.dom = {};
  5634. dom = this.dom;
  5635. // background box
  5636. dom.box = document.createElement('div');
  5637. // className is updated in repaint()
  5638. // contents box
  5639. dom.content = document.createElement('div');
  5640. dom.content.className = 'content';
  5641. dom.box.appendChild(dom.content);
  5642. // attach this item as attribute
  5643. dom.box['timeline-item'] = this;
  5644. }
  5645. // append DOM to parent DOM
  5646. if (!this.parent) {
  5647. throw new Error('Cannot repaint item: no parent attached');
  5648. }
  5649. if (!dom.box.parentNode) {
  5650. var foreground = this.parent.getForeground();
  5651. if (!foreground) {
  5652. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5653. }
  5654. foreground.appendChild(dom.box);
  5655. }
  5656. this.displayed = true;
  5657. // update contents
  5658. if (this.data.content != this.content) {
  5659. this.content = this.data.content;
  5660. if (this.content instanceof Element) {
  5661. dom.content.innerHTML = '';
  5662. dom.content.appendChild(this.content);
  5663. }
  5664. else if (this.data.content != undefined) {
  5665. dom.content.innerHTML = this.content;
  5666. }
  5667. else {
  5668. throw new Error('Property "content" missing in item ' + this.data.id);
  5669. }
  5670. this.dirty = true;
  5671. }
  5672. // update class
  5673. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5674. (this.selected ? ' selected' : '');
  5675. if (this.className != className) {
  5676. this.className = className;
  5677. dom.box.className = this.baseClassName + className;
  5678. this.dirty = true;
  5679. }
  5680. // recalculate size
  5681. if (this.dirty) {
  5682. this.props.content.width = this.dom.content.offsetWidth;
  5683. this.height = this.dom.box.offsetHeight;
  5684. this.dirty = false;
  5685. }
  5686. this._repaintDeleteButton(dom.box);
  5687. this._repaintDragLeft();
  5688. this._repaintDragRight();
  5689. };
  5690. /**
  5691. * Show the item in the DOM (when not already visible). The items DOM will
  5692. * be created when needed.
  5693. */
  5694. ItemRange.prototype.show = function show() {
  5695. if (!this.displayed) {
  5696. this.repaint();
  5697. }
  5698. };
  5699. /**
  5700. * Hide the item from the DOM (when visible)
  5701. * @return {Boolean} changed
  5702. */
  5703. ItemRange.prototype.hide = function hide() {
  5704. if (this.displayed) {
  5705. var box = this.dom.box;
  5706. if (box.parentNode) {
  5707. box.parentNode.removeChild(box);
  5708. }
  5709. this.top = null;
  5710. this.left = null;
  5711. this.displayed = false;
  5712. }
  5713. };
  5714. /**
  5715. * Reposition the item horizontally
  5716. * @Override
  5717. */
  5718. ItemRange.prototype.repositionX = function repositionX() {
  5719. var props = this.props,
  5720. parentWidth = this.parent.width,
  5721. start = this.defaultOptions.toScreen(this.data.start),
  5722. end = this.defaultOptions.toScreen(this.data.end),
  5723. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5724. contentLeft;
  5725. // limit the width of the this, as browsers cannot draw very wide divs
  5726. if (start < -parentWidth) {
  5727. start = -parentWidth;
  5728. }
  5729. if (end > 2 * parentWidth) {
  5730. end = 2 * parentWidth;
  5731. }
  5732. // when range exceeds left of the window, position the contents at the left of the visible area
  5733. if (start < 0) {
  5734. contentLeft = Math.min(-start,
  5735. (end - start - props.content.width - 2 * padding));
  5736. // TODO: remove the need for options.padding. it's terrible.
  5737. }
  5738. else {
  5739. contentLeft = 0;
  5740. }
  5741. this.left = start;
  5742. this.width = Math.max(end - start, 1);
  5743. this.dom.box.style.left = this.left + 'px';
  5744. this.dom.box.style.width = this.width + 'px';
  5745. this.dom.content.style.left = contentLeft + 'px';
  5746. };
  5747. /**
  5748. * Reposition the item vertically
  5749. * @Override
  5750. */
  5751. ItemRange.prototype.repositionY = function repositionY() {
  5752. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5753. box = this.dom.box;
  5754. if (orientation == 'top') {
  5755. box.style.top = this.top + 'px';
  5756. box.style.bottom = '';
  5757. }
  5758. else {
  5759. box.style.top = '';
  5760. box.style.bottom = this.top + 'px';
  5761. }
  5762. };
  5763. /**
  5764. * Repaint a drag area on the left side of the range when the range is selected
  5765. * @protected
  5766. */
  5767. ItemRange.prototype._repaintDragLeft = function () {
  5768. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  5769. // create and show drag area
  5770. var dragLeft = document.createElement('div');
  5771. dragLeft.className = 'drag-left';
  5772. dragLeft.dragLeftItem = this;
  5773. // TODO: this should be redundant?
  5774. Hammer(dragLeft, {
  5775. preventDefault: true
  5776. }).on('drag', function () {
  5777. //console.log('drag left')
  5778. });
  5779. this.dom.box.appendChild(dragLeft);
  5780. this.dom.dragLeft = dragLeft;
  5781. }
  5782. else if (!this.selected && this.dom.dragLeft) {
  5783. // delete drag area
  5784. if (this.dom.dragLeft.parentNode) {
  5785. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5786. }
  5787. this.dom.dragLeft = null;
  5788. }
  5789. };
  5790. /**
  5791. * Repaint a drag area on the right side of the range when the range is selected
  5792. * @protected
  5793. */
  5794. ItemRange.prototype._repaintDragRight = function () {
  5795. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  5796. // create and show drag area
  5797. var dragRight = document.createElement('div');
  5798. dragRight.className = 'drag-right';
  5799. dragRight.dragRightItem = this;
  5800. // TODO: this should be redundant?
  5801. Hammer(dragRight, {
  5802. preventDefault: true
  5803. }).on('drag', function () {
  5804. //console.log('drag right')
  5805. });
  5806. this.dom.box.appendChild(dragRight);
  5807. this.dom.dragRight = dragRight;
  5808. }
  5809. else if (!this.selected && this.dom.dragRight) {
  5810. // delete drag area
  5811. if (this.dom.dragRight.parentNode) {
  5812. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5813. }
  5814. this.dom.dragRight = null;
  5815. }
  5816. };
  5817. /**
  5818. * @constructor ItemRangeOverflow
  5819. * @extends ItemRange
  5820. * @param {Object} data Object containing parameters start, end
  5821. * content, className.
  5822. * @param {Object} [options] Options to set initial property values
  5823. * @param {Object} [defaultOptions] default options
  5824. * // TODO: describe available options
  5825. */
  5826. function ItemRangeOverflow (data, options, defaultOptions) {
  5827. this.props = {
  5828. content: {
  5829. left: 0,
  5830. width: 0
  5831. }
  5832. };
  5833. ItemRange.call(this, data, options, defaultOptions);
  5834. }
  5835. ItemRangeOverflow.prototype = new ItemRange (null);
  5836. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5837. /**
  5838. * Reposition the item horizontally
  5839. * @Override
  5840. */
  5841. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5842. var parentWidth = this.parent.width,
  5843. start = this.defaultOptions.toScreen(this.data.start),
  5844. end = this.defaultOptions.toScreen(this.data.end),
  5845. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5846. contentLeft;
  5847. // limit the width of the this, as browsers cannot draw very wide divs
  5848. if (start < -parentWidth) {
  5849. start = -parentWidth;
  5850. }
  5851. if (end > 2 * parentWidth) {
  5852. end = 2 * parentWidth;
  5853. }
  5854. // when range exceeds left of the window, position the contents at the left of the visible area
  5855. contentLeft = Math.max(-start, 0);
  5856. this.left = start;
  5857. var boxWidth = Math.max(end - start, 1);
  5858. this.width = boxWidth + this.props.content.width;
  5859. // Note: The calculation of width is an optimistic calculation, giving
  5860. // a width which will not change when moving the Timeline
  5861. // So no restacking needed, which is nicer for the eye
  5862. this.dom.box.style.left = this.left + 'px';
  5863. this.dom.box.style.width = boxWidth + 'px';
  5864. this.dom.content.style.left = contentLeft + 'px';
  5865. };
  5866. /**
  5867. * @constructor Group
  5868. * @param {Number | String} groupId
  5869. * @param {Object} data
  5870. * @param {ItemSet} itemSet
  5871. */
  5872. function Group (groupId, data, itemSet) {
  5873. this.groupId = groupId;
  5874. this.itemSet = itemSet;
  5875. this.dom = {};
  5876. this.props = {
  5877. label: {
  5878. width: 0,
  5879. height: 0
  5880. }
  5881. };
  5882. this.items = {}; // items filtered by groupId of this group
  5883. this.visibleItems = []; // items currently visible in window
  5884. this.orderedItems = { // items sorted by start and by end
  5885. byStart: [],
  5886. byEnd: []
  5887. };
  5888. this._create();
  5889. this.setData(data);
  5890. }
  5891. /**
  5892. * Create DOM elements for the group
  5893. * @private
  5894. */
  5895. Group.prototype._create = function() {
  5896. var label = document.createElement('div');
  5897. label.className = 'vlabel';
  5898. this.dom.label = label;
  5899. var inner = document.createElement('div');
  5900. inner.className = 'inner';
  5901. label.appendChild(inner);
  5902. this.dom.inner = inner;
  5903. var foreground = document.createElement('div');
  5904. foreground.className = 'group';
  5905. foreground['timeline-group'] = this;
  5906. this.dom.foreground = foreground;
  5907. this.dom.background = document.createElement('div');
  5908. this.dom.axis = document.createElement('div');
  5909. };
  5910. /**
  5911. * Set the group data for this group
  5912. * @param {Object} data Group data, can contain properties content and className
  5913. */
  5914. Group.prototype.setData = function setData(data) {
  5915. // update contents
  5916. var content = data && data.content;
  5917. if (content instanceof Element) {
  5918. this.dom.inner.appendChild(content);
  5919. }
  5920. else if (content != undefined) {
  5921. this.dom.inner.innerHTML = content;
  5922. }
  5923. else {
  5924. this.dom.inner.innerHTML = this.groupId;
  5925. }
  5926. // update className
  5927. var className = data && data.className;
  5928. if (className) {
  5929. util.addClassName(this.dom.label, className);
  5930. }
  5931. };
  5932. /**
  5933. * Get the foreground container element
  5934. * @return {HTMLElement} foreground
  5935. */
  5936. Group.prototype.getForeground = function getForeground() {
  5937. return this.dom.foreground;
  5938. };
  5939. /**
  5940. * Get the background container element
  5941. * @return {HTMLElement} background
  5942. */
  5943. Group.prototype.getBackground = function getBackground() {
  5944. return this.dom.background;
  5945. };
  5946. /**
  5947. * Get the axis container element
  5948. * @return {HTMLElement} axis
  5949. */
  5950. Group.prototype.getAxis = function getAxis() {
  5951. return this.dom.axis;
  5952. };
  5953. /**
  5954. * Get the width of the group label
  5955. * @return {number} width
  5956. */
  5957. Group.prototype.getLabelWidth = function getLabelWidth() {
  5958. return this.props.label.width;
  5959. };
  5960. /**
  5961. * Repaint this group
  5962. * @param {{start: number, end: number}} range
  5963. * @param {{item: number, axis: number}} margin
  5964. * @param {boolean} [restack=false] Force restacking of all items
  5965. * @return {boolean} Returns true if the group is resized
  5966. */
  5967. Group.prototype.repaint = function repaint(range, margin, restack) {
  5968. var resized = false;
  5969. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  5970. // reposition visible items vertically
  5971. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  5972. stack.stack(this.visibleItems, margin, restack);
  5973. }
  5974. else { // no stacking
  5975. stack.nostack(this.visibleItems, margin);
  5976. }
  5977. this.stackDirty = false;
  5978. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  5979. var item = this.visibleItems[i];
  5980. item.repositionY();
  5981. }
  5982. // recalculate the height of the group
  5983. var height;
  5984. var visibleItems = this.visibleItems;
  5985. if (visibleItems.length) {
  5986. var min = visibleItems[0].top;
  5987. var max = visibleItems[0].top + visibleItems[0].height;
  5988. util.forEach(visibleItems, function (item) {
  5989. min = Math.min(min, item.top);
  5990. max = Math.max(max, (item.top + item.height));
  5991. });
  5992. height = (max - min) + margin.axis + margin.item;
  5993. }
  5994. else {
  5995. height = margin.axis + margin.item;
  5996. }
  5997. height = Math.max(height, this.props.label.height);
  5998. // calculate actual size and position
  5999. var foreground = this.dom.foreground;
  6000. this.top = foreground.offsetTop;
  6001. this.left = foreground.offsetLeft;
  6002. this.width = foreground.offsetWidth;
  6003. resized = util.updateProperty(this, 'height', height) || resized;
  6004. // recalculate size of label
  6005. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  6006. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  6007. // apply new height
  6008. foreground.style.height = height + 'px';
  6009. this.dom.label.style.height = height + 'px';
  6010. return resized;
  6011. };
  6012. /**
  6013. * Show this group: attach to the DOM
  6014. */
  6015. Group.prototype.show = function show() {
  6016. if (!this.dom.label.parentNode) {
  6017. this.itemSet.getLabelSet().appendChild(this.dom.label);
  6018. }
  6019. if (!this.dom.foreground.parentNode) {
  6020. this.itemSet.getForeground().appendChild(this.dom.foreground);
  6021. }
  6022. if (!this.dom.background.parentNode) {
  6023. this.itemSet.getBackground().appendChild(this.dom.background);
  6024. }
  6025. if (!this.dom.axis.parentNode) {
  6026. this.itemSet.getAxis().appendChild(this.dom.axis);
  6027. }
  6028. };
  6029. /**
  6030. * Hide this group: remove from the DOM
  6031. */
  6032. Group.prototype.hide = function hide() {
  6033. var label = this.dom.label;
  6034. if (label.parentNode) {
  6035. label.parentNode.removeChild(label);
  6036. }
  6037. var foreground = this.dom.foreground;
  6038. if (foreground.parentNode) {
  6039. foreground.parentNode.removeChild(foreground);
  6040. }
  6041. var background = this.dom.background;
  6042. if (background.parentNode) {
  6043. background.parentNode.removeChild(background);
  6044. }
  6045. var axis = this.dom.axis;
  6046. if (axis.parentNode) {
  6047. axis.parentNode.removeChild(axis);
  6048. }
  6049. };
  6050. /**
  6051. * Add an item to the group
  6052. * @param {Item} item
  6053. */
  6054. Group.prototype.add = function add(item) {
  6055. this.items[item.id] = item;
  6056. item.setParent(this);
  6057. if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) {
  6058. var range = this.itemSet.range; // TODO: not nice accessing the range like this
  6059. this._checkIfVisible(item, this.visibleItems, range);
  6060. }
  6061. };
  6062. /**
  6063. * Remove an item from the group
  6064. * @param {Item} item
  6065. */
  6066. Group.prototype.remove = function remove(item) {
  6067. delete this.items[item.id];
  6068. item.setParent(this.itemSet);
  6069. // remove from visible items
  6070. var index = this.visibleItems.indexOf(item);
  6071. if (index != -1) this.visibleItems.splice(index, 1);
  6072. // TODO: also remove from ordered items?
  6073. };
  6074. /**
  6075. * Remove an item from the corresponding DataSet
  6076. * @param {Item} item
  6077. */
  6078. Group.prototype.removeFromDataSet = function removeFromDataSet(item) {
  6079. this.itemSet.removeItem(item.id);
  6080. };
  6081. /**
  6082. * Reorder the items
  6083. */
  6084. Group.prototype.order = function order() {
  6085. var array = util.toArray(this.items);
  6086. this.orderedItems.byStart = array;
  6087. this.orderedItems.byEnd = this._constructByEndArray(array);
  6088. stack.orderByStart(this.orderedItems.byStart);
  6089. stack.orderByEnd(this.orderedItems.byEnd);
  6090. };
  6091. /**
  6092. * Create an array containing all items being a range (having an end date)
  6093. * @param {Item[]} array
  6094. * @returns {ItemRange[]}
  6095. * @private
  6096. */
  6097. Group.prototype._constructByEndArray = function _constructByEndArray(array) {
  6098. var endArray = [];
  6099. for (var i = 0; i < array.length; i++) {
  6100. if (array[i] instanceof ItemRange) {
  6101. endArray.push(array[i]);
  6102. }
  6103. }
  6104. return endArray;
  6105. };
  6106. /**
  6107. * Update the visible items
  6108. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  6109. * @param {Item[]} visibleItems The previously visible items.
  6110. * @param {{start: number, end: number}} range Visible range
  6111. * @return {Item[]} visibleItems The new visible items.
  6112. * @private
  6113. */
  6114. Group.prototype._updateVisibleItems = function _updateVisibleItems(orderedItems, visibleItems, range) {
  6115. var initialPosByStart,
  6116. newVisibleItems = [],
  6117. i;
  6118. // first check if the items that were in view previously are still in view.
  6119. // this handles the case for the ItemRange that is both before and after the current one.
  6120. if (visibleItems.length > 0) {
  6121. for (i = 0; i < visibleItems.length; i++) {
  6122. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  6123. }
  6124. }
  6125. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  6126. if (newVisibleItems.length == 0) {
  6127. initialPosByStart = this._binarySearch(orderedItems, range, false);
  6128. }
  6129. else {
  6130. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  6131. }
  6132. // use visible search to find a visible ItemRange (only based on endTime)
  6133. var initialPosByEnd = this._binarySearch(orderedItems, range, true);
  6134. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6135. if (initialPosByStart != -1) {
  6136. for (i = initialPosByStart; i >= 0; i--) {
  6137. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6138. }
  6139. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  6140. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6141. }
  6142. }
  6143. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6144. if (initialPosByEnd != -1) {
  6145. for (i = initialPosByEnd; i >= 0; i--) {
  6146. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6147. }
  6148. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  6149. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6150. }
  6151. }
  6152. return newVisibleItems;
  6153. };
  6154. /**
  6155. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  6156. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  6157. * 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
  6158. * if the time we selected (start or end) is within the current range).
  6159. *
  6160. * 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
  6161. * 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,
  6162. * either the start OR end time has to be in the range.
  6163. *
  6164. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems
  6165. * @param {{start: number, end: number}} range
  6166. * @param {Boolean} byEnd
  6167. * @returns {number}
  6168. * @private
  6169. */
  6170. Group.prototype._binarySearch = function _binarySearch(orderedItems, range, byEnd) {
  6171. var array = [];
  6172. var byTime = byEnd ? 'end' : 'start';
  6173. if (byEnd == true) {array = orderedItems.byEnd; }
  6174. else {array = orderedItems.byStart;}
  6175. var interval = range.end - range.start;
  6176. var found = false;
  6177. var low = 0;
  6178. var high = array.length;
  6179. var guess = Math.floor(0.5*(high+low));
  6180. var newGuess;
  6181. if (high == 0) {guess = -1;}
  6182. else if (high == 1) {
  6183. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6184. guess = 0;
  6185. }
  6186. else {
  6187. guess = -1;
  6188. }
  6189. }
  6190. else {
  6191. high -= 1;
  6192. while (found == false) {
  6193. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6194. found = true;
  6195. }
  6196. else {
  6197. if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low
  6198. low = Math.floor(0.5*(high+low));
  6199. }
  6200. else { // it is too big --> decrease high
  6201. high = Math.floor(0.5*(high+low));
  6202. }
  6203. newGuess = Math.floor(0.5*(high+low));
  6204. // not in list;
  6205. if (guess == newGuess) {
  6206. guess = -1;
  6207. found = true;
  6208. }
  6209. else {
  6210. guess = newGuess;
  6211. }
  6212. }
  6213. }
  6214. }
  6215. return guess;
  6216. };
  6217. /**
  6218. * this function checks if an item is invisible. If it is NOT we make it visible
  6219. * and add it to the global visible items. If it is, return true.
  6220. *
  6221. * @param {Item} item
  6222. * @param {Item[]} visibleItems
  6223. * @param {{start:number, end:number}} range
  6224. * @returns {boolean}
  6225. * @private
  6226. */
  6227. Group.prototype._checkIfInvisible = function _checkIfInvisible(item, visibleItems, range) {
  6228. if (item.isVisible(range)) {
  6229. if (!item.displayed) item.show();
  6230. item.repositionX();
  6231. if (visibleItems.indexOf(item) == -1) {
  6232. visibleItems.push(item);
  6233. }
  6234. return false;
  6235. }
  6236. else {
  6237. return true;
  6238. }
  6239. };
  6240. /**
  6241. * this function is very similar to the _checkIfInvisible() but it does not
  6242. * return booleans, hides the item if it should not be seen and always adds to
  6243. * the visibleItems.
  6244. * this one is for brute forcing and hiding.
  6245. *
  6246. * @param {Item} item
  6247. * @param {Array} visibleItems
  6248. * @param {{start:number, end:number}} range
  6249. * @private
  6250. */
  6251. Group.prototype._checkIfVisible = function _checkIfVisible(item, visibleItems, range) {
  6252. if (item.isVisible(range)) {
  6253. if (!item.displayed) item.show();
  6254. // reposition item horizontally
  6255. item.repositionX();
  6256. visibleItems.push(item);
  6257. }
  6258. else {
  6259. if (item.displayed) item.hide();
  6260. }
  6261. };
  6262. /**
  6263. * Create a timeline visualization
  6264. * @param {HTMLElement} container
  6265. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6266. * @param {Object} [options] See Timeline.setOptions for the available options.
  6267. * @constructor
  6268. */
  6269. function Timeline (container, items, options) {
  6270. // validate arguments
  6271. if (!container) throw new Error('No container element provided');
  6272. var me = this;
  6273. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6274. this.options = {
  6275. orientation: 'bottom',
  6276. direction: 'horizontal', // 'horizontal' or 'vertical'
  6277. autoResize: true,
  6278. stack: true,
  6279. editable: {
  6280. updateTime: false,
  6281. updateGroup: false,
  6282. add: false,
  6283. remove: false
  6284. },
  6285. selectable: true,
  6286. snap: null, // will be specified after timeaxis is created
  6287. min: null,
  6288. max: null,
  6289. zoomMin: 10, // milliseconds
  6290. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6291. // moveable: true, // TODO: option moveable
  6292. // zoomable: true, // TODO: option zoomable
  6293. showMinorLabels: true,
  6294. showMajorLabels: true,
  6295. showCurrentTime: false,
  6296. showCustomTime: false,
  6297. type: 'box',
  6298. align: 'center',
  6299. margin: {
  6300. axis: 20,
  6301. item: 10
  6302. },
  6303. padding: 5,
  6304. onAdd: function (item, callback) {
  6305. callback(item);
  6306. },
  6307. onUpdate: function (item, callback) {
  6308. callback(item);
  6309. },
  6310. onMove: function (item, callback) {
  6311. callback(item);
  6312. },
  6313. onRemove: function (item, callback) {
  6314. callback(item);
  6315. },
  6316. toScreen: me._toScreen.bind(me),
  6317. toTime: me._toTime.bind(me)
  6318. };
  6319. // root panel
  6320. var rootOptions = util.extend(Object.create(this.options), {
  6321. height: function () {
  6322. if (me.options.height) {
  6323. // fixed height
  6324. return me.options.height;
  6325. }
  6326. else {
  6327. // auto height
  6328. // TODO: implement a css based solution to automatically have the right hight
  6329. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6330. }
  6331. }
  6332. });
  6333. this.rootPanel = new RootPanel(container, rootOptions);
  6334. // single select (or unselect) when tapping an item
  6335. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6336. // multi select when holding mouse/touch, or on ctrl+click
  6337. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6338. // add item on doubletap
  6339. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6340. // side panel
  6341. var sideOptions = util.extend(Object.create(this.options), {
  6342. top: function () {
  6343. return (sideOptions.orientation == 'top') ? '0' : '';
  6344. },
  6345. bottom: function () {
  6346. return (sideOptions.orientation == 'top') ? '' : '0';
  6347. },
  6348. left: '0',
  6349. right: null,
  6350. height: '100%',
  6351. width: function () {
  6352. if (me.itemSet) {
  6353. return me.itemSet.getLabelsWidth();
  6354. }
  6355. else {
  6356. return 0;
  6357. }
  6358. },
  6359. className: function () {
  6360. return 'side' + (me.groupsData ? '' : ' hidden');
  6361. }
  6362. });
  6363. this.sidePanel = new Panel(sideOptions);
  6364. this.rootPanel.appendChild(this.sidePanel);
  6365. // main panel (contains time axis and itemsets)
  6366. var mainOptions = util.extend(Object.create(this.options), {
  6367. left: function () {
  6368. // we align left to enable a smooth resizing of the window
  6369. return me.sidePanel.width;
  6370. },
  6371. right: null,
  6372. height: '100%',
  6373. width: function () {
  6374. return me.rootPanel.width - me.sidePanel.width;
  6375. },
  6376. className: 'main'
  6377. });
  6378. this.mainPanel = new Panel(mainOptions);
  6379. this.rootPanel.appendChild(this.mainPanel);
  6380. // range
  6381. // TODO: move range inside rootPanel?
  6382. var rangeOptions = Object.create(this.options);
  6383. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6384. this.range.setRange(
  6385. now.clone().add('days', -3).valueOf(),
  6386. now.clone().add('days', 4).valueOf()
  6387. );
  6388. this.range.on('rangechange', function (properties) {
  6389. me.rootPanel.repaint();
  6390. me.emit('rangechange', properties);
  6391. });
  6392. this.range.on('rangechanged', function (properties) {
  6393. me.rootPanel.repaint();
  6394. me.emit('rangechanged', properties);
  6395. });
  6396. // panel with time axis
  6397. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6398. range: this.range,
  6399. left: null,
  6400. top: null,
  6401. width: null,
  6402. height: null
  6403. });
  6404. this.timeAxis = new TimeAxis(timeAxisOptions);
  6405. this.timeAxis.setRange(this.range);
  6406. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6407. this.mainPanel.appendChild(this.timeAxis);
  6408. // content panel (contains itemset(s))
  6409. var contentOptions = util.extend(Object.create(this.options), {
  6410. top: function () {
  6411. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6412. },
  6413. bottom: function () {
  6414. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6415. },
  6416. left: null,
  6417. right: null,
  6418. height: null,
  6419. width: null,
  6420. className: 'content'
  6421. });
  6422. this.contentPanel = new Panel(contentOptions);
  6423. this.mainPanel.appendChild(this.contentPanel);
  6424. // content panel (contains the vertical lines of box items)
  6425. var backgroundOptions = 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: function () {
  6435. return me.contentPanel.height;
  6436. },
  6437. width: null,
  6438. className: 'background'
  6439. });
  6440. this.backgroundPanel = new Panel(backgroundOptions);
  6441. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6442. // panel with axis holding the dots of item boxes
  6443. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6444. left: 0,
  6445. top: function () {
  6446. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6447. },
  6448. bottom: function () {
  6449. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6450. },
  6451. width: '100%',
  6452. height: 0,
  6453. className: 'axis'
  6454. });
  6455. this.axisPanel = new Panel(axisPanelOptions);
  6456. this.mainPanel.appendChild(this.axisPanel);
  6457. // content panel (contains itemset(s))
  6458. var sideContentOptions = util.extend(Object.create(this.options), {
  6459. top: function () {
  6460. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6461. },
  6462. bottom: function () {
  6463. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6464. },
  6465. left: null,
  6466. right: null,
  6467. height: null,
  6468. width: null,
  6469. className: 'side-content'
  6470. });
  6471. this.sideContentPanel = new Panel(sideContentOptions);
  6472. this.sidePanel.appendChild(this.sideContentPanel);
  6473. // current time bar
  6474. // Note: time bar will be attached in this.setOptions when selected
  6475. this.currentTime = new CurrentTime(this.range, rootOptions);
  6476. // custom time bar
  6477. // Note: time bar will be attached in this.setOptions when selected
  6478. this.customTime = new CustomTime(rootOptions);
  6479. this.customTime.on('timechange', function (time) {
  6480. me.emit('timechange', time);
  6481. });
  6482. this.customTime.on('timechanged', function (time) {
  6483. me.emit('timechanged', time);
  6484. });
  6485. // itemset containing items and groups
  6486. var itemOptions = util.extend(Object.create(this.options), {
  6487. left: null,
  6488. right: null,
  6489. top: null,
  6490. bottom: null,
  6491. width: null,
  6492. height: null
  6493. });
  6494. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  6495. this.itemSet.setRange(this.range);
  6496. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6497. this.contentPanel.appendChild(this.itemSet);
  6498. this.itemsData = null; // DataSet
  6499. this.groupsData = null; // DataSet
  6500. // apply options
  6501. if (options) {
  6502. this.setOptions(options);
  6503. }
  6504. // create itemset
  6505. if (items) {
  6506. this.setItems(items);
  6507. }
  6508. }
  6509. // turn Timeline into an event emitter
  6510. Emitter(Timeline.prototype);
  6511. /**
  6512. * Set options
  6513. * @param {Object} options TODO: describe the available options
  6514. */
  6515. Timeline.prototype.setOptions = function (options) {
  6516. util.extend(this.options, options);
  6517. if ('editable' in options) {
  6518. var isBoolean = typeof options.editable === 'boolean';
  6519. this.options.editable = {
  6520. updateTime: isBoolean ? options.editable : (options.editable.updateTime || false),
  6521. updateGroup: isBoolean ? options.editable : (options.editable.updateGroup || false),
  6522. add: isBoolean ? options.editable : (options.editable.add || false),
  6523. remove: isBoolean ? options.editable : (options.editable.remove || false)
  6524. };
  6525. }
  6526. // force update of range (apply new min/max etc.)
  6527. // both start and end are optional
  6528. this.range.setRange(options.start, options.end);
  6529. if ('editable' in options || 'selectable' in options) {
  6530. if (this.options.selectable) {
  6531. // force update of selection
  6532. this.setSelection(this.getSelection());
  6533. }
  6534. else {
  6535. // remove selection
  6536. this.setSelection([]);
  6537. }
  6538. }
  6539. // force the itemSet to refresh: options like orientation and margins may be changed
  6540. this.itemSet.markDirty();
  6541. // validate the callback functions
  6542. var validateCallback = (function (fn) {
  6543. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6544. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6545. }
  6546. }).bind(this);
  6547. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6548. // add/remove the current time bar
  6549. if (this.options.showCurrentTime) {
  6550. if (!this.mainPanel.hasChild(this.currentTime)) {
  6551. this.mainPanel.appendChild(this.currentTime);
  6552. this.currentTime.start();
  6553. }
  6554. }
  6555. else {
  6556. if (this.mainPanel.hasChild(this.currentTime)) {
  6557. this.currentTime.stop();
  6558. this.mainPanel.removeChild(this.currentTime);
  6559. }
  6560. }
  6561. // add/remove the custom time bar
  6562. if (this.options.showCustomTime) {
  6563. if (!this.mainPanel.hasChild(this.customTime)) {
  6564. this.mainPanel.appendChild(this.customTime);
  6565. }
  6566. }
  6567. else {
  6568. if (this.mainPanel.hasChild(this.customTime)) {
  6569. this.mainPanel.removeChild(this.customTime);
  6570. }
  6571. }
  6572. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  6573. if (options && options.order) {
  6574. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  6575. }
  6576. // repaint everything
  6577. this.rootPanel.repaint();
  6578. };
  6579. /**
  6580. * Set a custom time bar
  6581. * @param {Date} time
  6582. */
  6583. Timeline.prototype.setCustomTime = function (time) {
  6584. if (!this.customTime) {
  6585. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6586. }
  6587. this.customTime.setCustomTime(time);
  6588. };
  6589. /**
  6590. * Retrieve the current custom time.
  6591. * @return {Date} customTime
  6592. */
  6593. Timeline.prototype.getCustomTime = function() {
  6594. if (!this.customTime) {
  6595. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6596. }
  6597. return this.customTime.getCustomTime();
  6598. };
  6599. /**
  6600. * Set items
  6601. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6602. */
  6603. Timeline.prototype.setItems = function(items) {
  6604. var initialLoad = (this.itemsData == null);
  6605. // convert to type DataSet when needed
  6606. var newDataSet;
  6607. if (!items) {
  6608. newDataSet = null;
  6609. }
  6610. else if (items instanceof DataSet || items instanceof DataView) {
  6611. newDataSet = items;
  6612. }
  6613. else {
  6614. // turn an array into a dataset
  6615. newDataSet = new DataSet(items, {
  6616. convert: {
  6617. start: 'Date',
  6618. end: 'Date'
  6619. }
  6620. });
  6621. }
  6622. // set items
  6623. this.itemsData = newDataSet;
  6624. this.itemSet.setItems(newDataSet);
  6625. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6626. this.fit();
  6627. var start = (this.options.start != undefined) ? util.convert(this.options.start, 'Date') : null;
  6628. var end = (this.options.end != undefined) ? util.convert(this.options.end, 'Date') : null;
  6629. this.setWindow(start, end);
  6630. }
  6631. };
  6632. /**
  6633. * Set groups
  6634. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6635. */
  6636. Timeline.prototype.setGroups = function setGroups(groups) {
  6637. // convert to type DataSet when needed
  6638. var newDataSet;
  6639. if (!groups) {
  6640. newDataSet = null;
  6641. }
  6642. else if (groups instanceof DataSet || groups instanceof DataView) {
  6643. newDataSet = groups;
  6644. }
  6645. else {
  6646. // turn an array into a dataset
  6647. newDataSet = new DataSet(groups);
  6648. }
  6649. this.groupsData = newDataSet;
  6650. this.itemSet.setGroups(newDataSet);
  6651. };
  6652. /**
  6653. * Set Timeline window such that it fits all items
  6654. */
  6655. Timeline.prototype.fit = function fit() {
  6656. // apply the data range as range
  6657. var dataRange = this.getItemRange();
  6658. // add 5% space on both sides
  6659. var start = dataRange.min;
  6660. var end = dataRange.max;
  6661. if (start != null && end != null) {
  6662. var interval = (end.valueOf() - start.valueOf());
  6663. if (interval <= 0) {
  6664. // prevent an empty interval
  6665. interval = 24 * 60 * 60 * 1000; // 1 day
  6666. }
  6667. start = new Date(start.valueOf() - interval * 0.05);
  6668. end = new Date(end.valueOf() + interval * 0.05);
  6669. }
  6670. // skip range set if there is no start and end date
  6671. if (start === null && end === null) {
  6672. return;
  6673. }
  6674. this.range.setRange(start, end);
  6675. };
  6676. /**
  6677. * Get the data range of the item set.
  6678. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6679. * When no minimum is found, min==null
  6680. * When no maximum is found, max==null
  6681. */
  6682. Timeline.prototype.getItemRange = function getItemRange() {
  6683. // calculate min from start filed
  6684. var itemsData = this.itemsData,
  6685. min = null,
  6686. max = null;
  6687. if (itemsData) {
  6688. // calculate the minimum value of the field 'start'
  6689. var minItem = itemsData.min('start');
  6690. min = minItem ? minItem.start.valueOf() : null;
  6691. // calculate maximum value of fields 'start' and 'end'
  6692. var maxStartItem = itemsData.max('start');
  6693. if (maxStartItem) {
  6694. max = maxStartItem.start.valueOf();
  6695. }
  6696. var maxEndItem = itemsData.max('end');
  6697. if (maxEndItem) {
  6698. if (max == null) {
  6699. max = maxEndItem.end.valueOf();
  6700. }
  6701. else {
  6702. max = Math.max(max, maxEndItem.end.valueOf());
  6703. }
  6704. }
  6705. }
  6706. return {
  6707. min: (min != null) ? new Date(min) : null,
  6708. max: (max != null) ? new Date(max) : null
  6709. };
  6710. };
  6711. /**
  6712. * Set selected items by their id. Replaces the current selection
  6713. * Unknown id's are silently ignored.
  6714. * @param {Array} [ids] An array with zero or more id's of the items to be
  6715. * selected. If ids is an empty array, all items will be
  6716. * unselected.
  6717. */
  6718. Timeline.prototype.setSelection = function setSelection (ids) {
  6719. this.itemSet.setSelection(ids);
  6720. };
  6721. /**
  6722. * Get the selected items by their id
  6723. * @return {Array} ids The ids of the selected items
  6724. */
  6725. Timeline.prototype.getSelection = function getSelection() {
  6726. return this.itemSet.getSelection();
  6727. };
  6728. /**
  6729. * Set the visible window. Both parameters are optional, you can change only
  6730. * start or only end. Syntax:
  6731. *
  6732. * TimeLine.setWindow(start, end)
  6733. * TimeLine.setWindow(range)
  6734. *
  6735. * Where start and end can be a Date, number, or string, and range is an
  6736. * object with properties start and end.
  6737. *
  6738. * @param {Date | Number | String} [start] Start date of visible window
  6739. * @param {Date | Number | String} [end] End date of visible window
  6740. */
  6741. Timeline.prototype.setWindow = function setWindow(start, end) {
  6742. if (arguments.length == 1) {
  6743. var range = arguments[0];
  6744. this.range.setRange(range.start, range.end);
  6745. }
  6746. else {
  6747. this.range.setRange(start, end);
  6748. }
  6749. };
  6750. /**
  6751. * Get the visible window
  6752. * @return {{start: Date, end: Date}} Visible range
  6753. */
  6754. Timeline.prototype.getWindow = function setWindow() {
  6755. var range = this.range.getRange();
  6756. return {
  6757. start: new Date(range.start),
  6758. end: new Date(range.end)
  6759. };
  6760. };
  6761. /**
  6762. * Handle selecting/deselecting an item when tapping it
  6763. * @param {Event} event
  6764. * @private
  6765. */
  6766. // TODO: move this function to ItemSet
  6767. Timeline.prototype._onSelectItem = function (event) {
  6768. if (!this.options.selectable) return;
  6769. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6770. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6771. if (ctrlKey || shiftKey) {
  6772. this._onMultiSelectItem(event);
  6773. return;
  6774. }
  6775. var oldSelection = this.getSelection();
  6776. var item = ItemSet.itemFromTarget(event);
  6777. var selection = item ? [item.id] : [];
  6778. this.setSelection(selection);
  6779. var newSelection = this.getSelection();
  6780. // if selection is changed, emit a select event
  6781. if (!util.equalArray(oldSelection, newSelection)) {
  6782. this.emit('select', {
  6783. items: this.getSelection()
  6784. });
  6785. }
  6786. event.stopPropagation();
  6787. };
  6788. /**
  6789. * Handle creation and updates of an item on double tap
  6790. * @param event
  6791. * @private
  6792. */
  6793. Timeline.prototype._onAddItem = function (event) {
  6794. if (!this.options.selectable) return;
  6795. if (!this.options.editable.add) return;
  6796. var me = this,
  6797. item = ItemSet.itemFromTarget(event);
  6798. if (item) {
  6799. // update item
  6800. // execute async handler to update the item (or cancel it)
  6801. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6802. this.options.onUpdate(itemData, function (itemData) {
  6803. if (itemData) {
  6804. me.itemsData.update(itemData);
  6805. }
  6806. });
  6807. }
  6808. else {
  6809. // add item
  6810. var xAbs = vis.util.getAbsoluteLeft(this.contentPanel.frame);
  6811. var x = event.gesture.center.pageX - xAbs;
  6812. var newItem = {
  6813. start: this.timeAxis.snap(this._toTime(x)),
  6814. content: 'new item'
  6815. };
  6816. var id = util.randomUUID();
  6817. newItem[this.itemsData.fieldId] = id;
  6818. var group = ItemSet.groupFromTarget(event);
  6819. if (group) {
  6820. newItem.group = group.groupId;
  6821. }
  6822. // execute async handler to customize (or cancel) adding an item
  6823. this.options.onAdd(newItem, function (item) {
  6824. if (item) {
  6825. me.itemsData.add(newItem);
  6826. // TODO: need to trigger a repaint?
  6827. }
  6828. });
  6829. }
  6830. };
  6831. /**
  6832. * Handle selecting/deselecting multiple items when holding an item
  6833. * @param {Event} event
  6834. * @private
  6835. */
  6836. // TODO: move this function to ItemSet
  6837. Timeline.prototype._onMultiSelectItem = function (event) {
  6838. if (!this.options.selectable) return;
  6839. var selection,
  6840. item = ItemSet.itemFromTarget(event);
  6841. if (item) {
  6842. // multi select items
  6843. selection = this.getSelection(); // current selection
  6844. var index = selection.indexOf(item.id);
  6845. if (index == -1) {
  6846. // item is not yet selected -> select it
  6847. selection.push(item.id);
  6848. }
  6849. else {
  6850. // item is already selected -> deselect it
  6851. selection.splice(index, 1);
  6852. }
  6853. this.setSelection(selection);
  6854. this.emit('select', {
  6855. items: this.getSelection()
  6856. });
  6857. event.stopPropagation();
  6858. }
  6859. };
  6860. /**
  6861. * Convert a position on screen (pixels) to a datetime
  6862. * @param {int} x Position on the screen in pixels
  6863. * @return {Date} time The datetime the corresponds with given position x
  6864. * @private
  6865. */
  6866. Timeline.prototype._toTime = function _toTime(x) {
  6867. var conversion = this.range.conversion(this.mainPanel.width);
  6868. return new Date(x / conversion.scale + conversion.offset);
  6869. };
  6870. /**
  6871. * Convert a datetime (Date object) into a position on the screen
  6872. * @param {Date} time A date
  6873. * @return {int} x The position on the screen in pixels which corresponds
  6874. * with the given date.
  6875. * @private
  6876. */
  6877. Timeline.prototype._toScreen = function _toScreen(time) {
  6878. var conversion = this.range.conversion(this.mainPanel.width);
  6879. return (time.valueOf() - conversion.offset) * conversion.scale;
  6880. };
  6881. (function(exports) {
  6882. /**
  6883. * Parse a text source containing data in DOT language into a JSON object.
  6884. * The object contains two lists: one with nodes and one with edges.
  6885. *
  6886. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6887. *
  6888. * @param {String} data Text containing a graph in DOT-notation
  6889. * @return {Object} graph An object containing two parameters:
  6890. * {Object[]} nodes
  6891. * {Object[]} edges
  6892. */
  6893. function parseDOT (data) {
  6894. dot = data;
  6895. return parseGraph();
  6896. }
  6897. // token types enumeration
  6898. var TOKENTYPE = {
  6899. NULL : 0,
  6900. DELIMITER : 1,
  6901. IDENTIFIER: 2,
  6902. UNKNOWN : 3
  6903. };
  6904. // map with all delimiters
  6905. var DELIMITERS = {
  6906. '{': true,
  6907. '}': true,
  6908. '[': true,
  6909. ']': true,
  6910. ';': true,
  6911. '=': true,
  6912. ',': true,
  6913. '->': true,
  6914. '--': true
  6915. };
  6916. var dot = ''; // current dot file
  6917. var index = 0; // current index in dot file
  6918. var c = ''; // current token character in expr
  6919. var token = ''; // current token
  6920. var tokenType = TOKENTYPE.NULL; // type of the token
  6921. /**
  6922. * Get the first character from the dot file.
  6923. * The character is stored into the char c. If the end of the dot file is
  6924. * reached, the function puts an empty string in c.
  6925. */
  6926. function first() {
  6927. index = 0;
  6928. c = dot.charAt(0);
  6929. }
  6930. /**
  6931. * Get the next character from the dot file.
  6932. * The character is stored into the char c. If the end of the dot file is
  6933. * reached, the function puts an empty string in c.
  6934. */
  6935. function next() {
  6936. index++;
  6937. c = dot.charAt(index);
  6938. }
  6939. /**
  6940. * Preview the next character from the dot file.
  6941. * @return {String} cNext
  6942. */
  6943. function nextPreview() {
  6944. return dot.charAt(index + 1);
  6945. }
  6946. /**
  6947. * Test whether given character is alphabetic or numeric
  6948. * @param {String} c
  6949. * @return {Boolean} isAlphaNumeric
  6950. */
  6951. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6952. function isAlphaNumeric(c) {
  6953. return regexAlphaNumeric.test(c);
  6954. }
  6955. /**
  6956. * Merge all properties of object b into object b
  6957. * @param {Object} a
  6958. * @param {Object} b
  6959. * @return {Object} a
  6960. */
  6961. function merge (a, b) {
  6962. if (!a) {
  6963. a = {};
  6964. }
  6965. if (b) {
  6966. for (var name in b) {
  6967. if (b.hasOwnProperty(name)) {
  6968. a[name] = b[name];
  6969. }
  6970. }
  6971. }
  6972. return a;
  6973. }
  6974. /**
  6975. * Set a value in an object, where the provided parameter name can be a
  6976. * path with nested parameters. For example:
  6977. *
  6978. * var obj = {a: 2};
  6979. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6980. *
  6981. * @param {Object} obj
  6982. * @param {String} path A parameter name or dot-separated parameter path,
  6983. * like "color.highlight.border".
  6984. * @param {*} value
  6985. */
  6986. function setValue(obj, path, value) {
  6987. var keys = path.split('.');
  6988. var o = obj;
  6989. while (keys.length) {
  6990. var key = keys.shift();
  6991. if (keys.length) {
  6992. // this isn't the end point
  6993. if (!o[key]) {
  6994. o[key] = {};
  6995. }
  6996. o = o[key];
  6997. }
  6998. else {
  6999. // this is the end point
  7000. o[key] = value;
  7001. }
  7002. }
  7003. }
  7004. /**
  7005. * Add a node to a graph object. If there is already a node with
  7006. * the same id, their attributes will be merged.
  7007. * @param {Object} graph
  7008. * @param {Object} node
  7009. */
  7010. function addNode(graph, node) {
  7011. var i, len;
  7012. var current = null;
  7013. // find root graph (in case of subgraph)
  7014. var graphs = [graph]; // list with all graphs from current graph to root graph
  7015. var root = graph;
  7016. while (root.parent) {
  7017. graphs.push(root.parent);
  7018. root = root.parent;
  7019. }
  7020. // find existing node (at root level) by its id
  7021. if (root.nodes) {
  7022. for (i = 0, len = root.nodes.length; i < len; i++) {
  7023. if (node.id === root.nodes[i].id) {
  7024. current = root.nodes[i];
  7025. break;
  7026. }
  7027. }
  7028. }
  7029. if (!current) {
  7030. // this is a new node
  7031. current = {
  7032. id: node.id
  7033. };
  7034. if (graph.node) {
  7035. // clone default attributes
  7036. current.attr = merge(current.attr, graph.node);
  7037. }
  7038. }
  7039. // add node to this (sub)graph and all its parent graphs
  7040. for (i = graphs.length - 1; i >= 0; i--) {
  7041. var g = graphs[i];
  7042. if (!g.nodes) {
  7043. g.nodes = [];
  7044. }
  7045. if (g.nodes.indexOf(current) == -1) {
  7046. g.nodes.push(current);
  7047. }
  7048. }
  7049. // merge attributes
  7050. if (node.attr) {
  7051. current.attr = merge(current.attr, node.attr);
  7052. }
  7053. }
  7054. /**
  7055. * Add an edge to a graph object
  7056. * @param {Object} graph
  7057. * @param {Object} edge
  7058. */
  7059. function addEdge(graph, edge) {
  7060. if (!graph.edges) {
  7061. graph.edges = [];
  7062. }
  7063. graph.edges.push(edge);
  7064. if (graph.edge) {
  7065. var attr = merge({}, graph.edge); // clone default attributes
  7066. edge.attr = merge(attr, edge.attr); // merge attributes
  7067. }
  7068. }
  7069. /**
  7070. * Create an edge to a graph object
  7071. * @param {Object} graph
  7072. * @param {String | Number | Object} from
  7073. * @param {String | Number | Object} to
  7074. * @param {String} type
  7075. * @param {Object | null} attr
  7076. * @return {Object} edge
  7077. */
  7078. function createEdge(graph, from, to, type, attr) {
  7079. var edge = {
  7080. from: from,
  7081. to: to,
  7082. type: type
  7083. };
  7084. if (graph.edge) {
  7085. edge.attr = merge({}, graph.edge); // clone default attributes
  7086. }
  7087. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7088. return edge;
  7089. }
  7090. /**
  7091. * Get next token in the current dot file.
  7092. * The token and token type are available as token and tokenType
  7093. */
  7094. function getToken() {
  7095. tokenType = TOKENTYPE.NULL;
  7096. token = '';
  7097. // skip over whitespaces
  7098. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7099. next();
  7100. }
  7101. do {
  7102. var isComment = false;
  7103. // skip comment
  7104. if (c == '#') {
  7105. // find the previous non-space character
  7106. var i = index - 1;
  7107. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7108. i--;
  7109. }
  7110. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7111. // the # is at the start of a line, this is indeed a line comment
  7112. while (c != '' && c != '\n') {
  7113. next();
  7114. }
  7115. isComment = true;
  7116. }
  7117. }
  7118. if (c == '/' && nextPreview() == '/') {
  7119. // skip line comment
  7120. while (c != '' && c != '\n') {
  7121. next();
  7122. }
  7123. isComment = true;
  7124. }
  7125. if (c == '/' && nextPreview() == '*') {
  7126. // skip block comment
  7127. while (c != '') {
  7128. if (c == '*' && nextPreview() == '/') {
  7129. // end of block comment found. skip these last two characters
  7130. next();
  7131. next();
  7132. break;
  7133. }
  7134. else {
  7135. next();
  7136. }
  7137. }
  7138. isComment = true;
  7139. }
  7140. // skip over whitespaces
  7141. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7142. next();
  7143. }
  7144. }
  7145. while (isComment);
  7146. // check for end of dot file
  7147. if (c == '') {
  7148. // token is still empty
  7149. tokenType = TOKENTYPE.DELIMITER;
  7150. return;
  7151. }
  7152. // check for delimiters consisting of 2 characters
  7153. var c2 = c + nextPreview();
  7154. if (DELIMITERS[c2]) {
  7155. tokenType = TOKENTYPE.DELIMITER;
  7156. token = c2;
  7157. next();
  7158. next();
  7159. return;
  7160. }
  7161. // check for delimiters consisting of 1 character
  7162. if (DELIMITERS[c]) {
  7163. tokenType = TOKENTYPE.DELIMITER;
  7164. token = c;
  7165. next();
  7166. return;
  7167. }
  7168. // check for an identifier (number or string)
  7169. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7170. if (isAlphaNumeric(c) || c == '-') {
  7171. token += c;
  7172. next();
  7173. while (isAlphaNumeric(c)) {
  7174. token += c;
  7175. next();
  7176. }
  7177. if (token == 'false') {
  7178. token = false; // convert to boolean
  7179. }
  7180. else if (token == 'true') {
  7181. token = true; // convert to boolean
  7182. }
  7183. else if (!isNaN(Number(token))) {
  7184. token = Number(token); // convert to number
  7185. }
  7186. tokenType = TOKENTYPE.IDENTIFIER;
  7187. return;
  7188. }
  7189. // check for a string enclosed by double quotes
  7190. if (c == '"') {
  7191. next();
  7192. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7193. token += c;
  7194. if (c == '"') { // skip the escape character
  7195. next();
  7196. }
  7197. next();
  7198. }
  7199. if (c != '"') {
  7200. throw newSyntaxError('End of string " expected');
  7201. }
  7202. next();
  7203. tokenType = TOKENTYPE.IDENTIFIER;
  7204. return;
  7205. }
  7206. // something unknown is found, wrong characters, a syntax error
  7207. tokenType = TOKENTYPE.UNKNOWN;
  7208. while (c != '') {
  7209. token += c;
  7210. next();
  7211. }
  7212. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7213. }
  7214. /**
  7215. * Parse a graph.
  7216. * @returns {Object} graph
  7217. */
  7218. function parseGraph() {
  7219. var graph = {};
  7220. first();
  7221. getToken();
  7222. // optional strict keyword
  7223. if (token == 'strict') {
  7224. graph.strict = true;
  7225. getToken();
  7226. }
  7227. // graph or digraph keyword
  7228. if (token == 'graph' || token == 'digraph') {
  7229. graph.type = token;
  7230. getToken();
  7231. }
  7232. // optional graph id
  7233. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7234. graph.id = token;
  7235. getToken();
  7236. }
  7237. // open angle bracket
  7238. if (token != '{') {
  7239. throw newSyntaxError('Angle bracket { expected');
  7240. }
  7241. getToken();
  7242. // statements
  7243. parseStatements(graph);
  7244. // close angle bracket
  7245. if (token != '}') {
  7246. throw newSyntaxError('Angle bracket } expected');
  7247. }
  7248. getToken();
  7249. // end of file
  7250. if (token !== '') {
  7251. throw newSyntaxError('End of file expected');
  7252. }
  7253. getToken();
  7254. // remove temporary default properties
  7255. delete graph.node;
  7256. delete graph.edge;
  7257. delete graph.graph;
  7258. return graph;
  7259. }
  7260. /**
  7261. * Parse a list with statements.
  7262. * @param {Object} graph
  7263. */
  7264. function parseStatements (graph) {
  7265. while (token !== '' && token != '}') {
  7266. parseStatement(graph);
  7267. if (token == ';') {
  7268. getToken();
  7269. }
  7270. }
  7271. }
  7272. /**
  7273. * Parse a single statement. Can be a an attribute statement, node
  7274. * statement, a series of node statements and edge statements, or a
  7275. * parameter.
  7276. * @param {Object} graph
  7277. */
  7278. function parseStatement(graph) {
  7279. // parse subgraph
  7280. var subgraph = parseSubgraph(graph);
  7281. if (subgraph) {
  7282. // edge statements
  7283. parseEdge(graph, subgraph);
  7284. return;
  7285. }
  7286. // parse an attribute statement
  7287. var attr = parseAttributeStatement(graph);
  7288. if (attr) {
  7289. return;
  7290. }
  7291. // parse node
  7292. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7293. throw newSyntaxError('Identifier expected');
  7294. }
  7295. var id = token; // id can be a string or a number
  7296. getToken();
  7297. if (token == '=') {
  7298. // id statement
  7299. getToken();
  7300. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7301. throw newSyntaxError('Identifier expected');
  7302. }
  7303. graph[id] = token;
  7304. getToken();
  7305. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7306. }
  7307. else {
  7308. parseNodeStatement(graph, id);
  7309. }
  7310. }
  7311. /**
  7312. * Parse a subgraph
  7313. * @param {Object} graph parent graph object
  7314. * @return {Object | null} subgraph
  7315. */
  7316. function parseSubgraph (graph) {
  7317. var subgraph = null;
  7318. // optional subgraph keyword
  7319. if (token == 'subgraph') {
  7320. subgraph = {};
  7321. subgraph.type = 'subgraph';
  7322. getToken();
  7323. // optional graph id
  7324. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7325. subgraph.id = token;
  7326. getToken();
  7327. }
  7328. }
  7329. // open angle bracket
  7330. if (token == '{') {
  7331. getToken();
  7332. if (!subgraph) {
  7333. subgraph = {};
  7334. }
  7335. subgraph.parent = graph;
  7336. subgraph.node = graph.node;
  7337. subgraph.edge = graph.edge;
  7338. subgraph.graph = graph.graph;
  7339. // statements
  7340. parseStatements(subgraph);
  7341. // close angle bracket
  7342. if (token != '}') {
  7343. throw newSyntaxError('Angle bracket } expected');
  7344. }
  7345. getToken();
  7346. // remove temporary default properties
  7347. delete subgraph.node;
  7348. delete subgraph.edge;
  7349. delete subgraph.graph;
  7350. delete subgraph.parent;
  7351. // register at the parent graph
  7352. if (!graph.subgraphs) {
  7353. graph.subgraphs = [];
  7354. }
  7355. graph.subgraphs.push(subgraph);
  7356. }
  7357. return subgraph;
  7358. }
  7359. /**
  7360. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7361. * Available keywords are 'node', 'edge', 'graph'.
  7362. * The previous list with default attributes will be replaced
  7363. * @param {Object} graph
  7364. * @returns {String | null} keyword Returns the name of the parsed attribute
  7365. * (node, edge, graph), or null if nothing
  7366. * is parsed.
  7367. */
  7368. function parseAttributeStatement (graph) {
  7369. // attribute statements
  7370. if (token == 'node') {
  7371. getToken();
  7372. // node attributes
  7373. graph.node = parseAttributeList();
  7374. return 'node';
  7375. }
  7376. else if (token == 'edge') {
  7377. getToken();
  7378. // edge attributes
  7379. graph.edge = parseAttributeList();
  7380. return 'edge';
  7381. }
  7382. else if (token == 'graph') {
  7383. getToken();
  7384. // graph attributes
  7385. graph.graph = parseAttributeList();
  7386. return 'graph';
  7387. }
  7388. return null;
  7389. }
  7390. /**
  7391. * parse a node statement
  7392. * @param {Object} graph
  7393. * @param {String | Number} id
  7394. */
  7395. function parseNodeStatement(graph, id) {
  7396. // node statement
  7397. var node = {
  7398. id: id
  7399. };
  7400. var attr = parseAttributeList();
  7401. if (attr) {
  7402. node.attr = attr;
  7403. }
  7404. addNode(graph, node);
  7405. // edge statements
  7406. parseEdge(graph, id);
  7407. }
  7408. /**
  7409. * Parse an edge or a series of edges
  7410. * @param {Object} graph
  7411. * @param {String | Number} from Id of the from node
  7412. */
  7413. function parseEdge(graph, from) {
  7414. while (token == '->' || token == '--') {
  7415. var to;
  7416. var type = token;
  7417. getToken();
  7418. var subgraph = parseSubgraph(graph);
  7419. if (subgraph) {
  7420. to = subgraph;
  7421. }
  7422. else {
  7423. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7424. throw newSyntaxError('Identifier or subgraph expected');
  7425. }
  7426. to = token;
  7427. addNode(graph, {
  7428. id: to
  7429. });
  7430. getToken();
  7431. }
  7432. // parse edge attributes
  7433. var attr = parseAttributeList();
  7434. // create edge
  7435. var edge = createEdge(graph, from, to, type, attr);
  7436. addEdge(graph, edge);
  7437. from = to;
  7438. }
  7439. }
  7440. /**
  7441. * Parse a set with attributes,
  7442. * for example [label="1.000", shape=solid]
  7443. * @return {Object | null} attr
  7444. */
  7445. function parseAttributeList() {
  7446. var attr = null;
  7447. while (token == '[') {
  7448. getToken();
  7449. attr = {};
  7450. while (token !== '' && token != ']') {
  7451. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7452. throw newSyntaxError('Attribute name expected');
  7453. }
  7454. var name = token;
  7455. getToken();
  7456. if (token != '=') {
  7457. throw newSyntaxError('Equal sign = expected');
  7458. }
  7459. getToken();
  7460. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7461. throw newSyntaxError('Attribute value expected');
  7462. }
  7463. var value = token;
  7464. setValue(attr, name, value); // name can be a path
  7465. getToken();
  7466. if (token ==',') {
  7467. getToken();
  7468. }
  7469. }
  7470. if (token != ']') {
  7471. throw newSyntaxError('Bracket ] expected');
  7472. }
  7473. getToken();
  7474. }
  7475. return attr;
  7476. }
  7477. /**
  7478. * Create a syntax error with extra information on current token and index.
  7479. * @param {String} message
  7480. * @returns {SyntaxError} err
  7481. */
  7482. function newSyntaxError(message) {
  7483. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7484. }
  7485. /**
  7486. * Chop off text after a maximum length
  7487. * @param {String} text
  7488. * @param {Number} maxLength
  7489. * @returns {String}
  7490. */
  7491. function chop (text, maxLength) {
  7492. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7493. }
  7494. /**
  7495. * Execute a function fn for each pair of elements in two arrays
  7496. * @param {Array | *} array1
  7497. * @param {Array | *} array2
  7498. * @param {function} fn
  7499. */
  7500. function forEach2(array1, array2, fn) {
  7501. if (array1 instanceof Array) {
  7502. array1.forEach(function (elem1) {
  7503. if (array2 instanceof Array) {
  7504. array2.forEach(function (elem2) {
  7505. fn(elem1, elem2);
  7506. });
  7507. }
  7508. else {
  7509. fn(elem1, array2);
  7510. }
  7511. });
  7512. }
  7513. else {
  7514. if (array2 instanceof Array) {
  7515. array2.forEach(function (elem2) {
  7516. fn(array1, elem2);
  7517. });
  7518. }
  7519. else {
  7520. fn(array1, array2);
  7521. }
  7522. }
  7523. }
  7524. /**
  7525. * Convert a string containing a graph in DOT language into a map containing
  7526. * with nodes and edges in the format of graph.
  7527. * @param {String} data Text containing a graph in DOT-notation
  7528. * @return {Object} graphData
  7529. */
  7530. function DOTToGraph (data) {
  7531. // parse the DOT file
  7532. var dotData = parseDOT(data);
  7533. var graphData = {
  7534. nodes: [],
  7535. edges: [],
  7536. options: {}
  7537. };
  7538. // copy the nodes
  7539. if (dotData.nodes) {
  7540. dotData.nodes.forEach(function (dotNode) {
  7541. var graphNode = {
  7542. id: dotNode.id,
  7543. label: String(dotNode.label || dotNode.id)
  7544. };
  7545. merge(graphNode, dotNode.attr);
  7546. if (graphNode.image) {
  7547. graphNode.shape = 'image';
  7548. }
  7549. graphData.nodes.push(graphNode);
  7550. });
  7551. }
  7552. // copy the edges
  7553. if (dotData.edges) {
  7554. /**
  7555. * Convert an edge in DOT format to an edge with VisGraph format
  7556. * @param {Object} dotEdge
  7557. * @returns {Object} graphEdge
  7558. */
  7559. function convertEdge(dotEdge) {
  7560. var graphEdge = {
  7561. from: dotEdge.from,
  7562. to: dotEdge.to
  7563. };
  7564. merge(graphEdge, dotEdge.attr);
  7565. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7566. return graphEdge;
  7567. }
  7568. dotData.edges.forEach(function (dotEdge) {
  7569. var from, to;
  7570. if (dotEdge.from instanceof Object) {
  7571. from = dotEdge.from.nodes;
  7572. }
  7573. else {
  7574. from = {
  7575. id: dotEdge.from
  7576. }
  7577. }
  7578. if (dotEdge.to instanceof Object) {
  7579. to = dotEdge.to.nodes;
  7580. }
  7581. else {
  7582. to = {
  7583. id: dotEdge.to
  7584. }
  7585. }
  7586. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7587. dotEdge.from.edges.forEach(function (subEdge) {
  7588. var graphEdge = convertEdge(subEdge);
  7589. graphData.edges.push(graphEdge);
  7590. });
  7591. }
  7592. forEach2(from, to, function (from, to) {
  7593. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7594. var graphEdge = convertEdge(subEdge);
  7595. graphData.edges.push(graphEdge);
  7596. });
  7597. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7598. dotEdge.to.edges.forEach(function (subEdge) {
  7599. var graphEdge = convertEdge(subEdge);
  7600. graphData.edges.push(graphEdge);
  7601. });
  7602. }
  7603. });
  7604. }
  7605. // copy the options
  7606. if (dotData.attr) {
  7607. graphData.options = dotData.attr;
  7608. }
  7609. return graphData;
  7610. }
  7611. // exports
  7612. exports.parseDOT = parseDOT;
  7613. exports.DOTToGraph = DOTToGraph;
  7614. })(typeof util !== 'undefined' ? util : exports);
  7615. /**
  7616. * Canvas shapes used by the Graph
  7617. */
  7618. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7619. /**
  7620. * Draw a circle shape
  7621. */
  7622. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7623. this.beginPath();
  7624. this.arc(x, y, r, 0, 2*Math.PI, false);
  7625. };
  7626. /**
  7627. * Draw a square shape
  7628. * @param {Number} x horizontal center
  7629. * @param {Number} y vertical center
  7630. * @param {Number} r size, width and height of the square
  7631. */
  7632. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7633. this.beginPath();
  7634. this.rect(x - r, y - r, r * 2, r * 2);
  7635. };
  7636. /**
  7637. * Draw a triangle shape
  7638. * @param {Number} x horizontal center
  7639. * @param {Number} y vertical center
  7640. * @param {Number} r radius, half the length of the sides of the triangle
  7641. */
  7642. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7643. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7644. this.beginPath();
  7645. var s = r * 2;
  7646. var s2 = s / 2;
  7647. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7648. var h = Math.sqrt(s * s - s2 * s2); // height
  7649. this.moveTo(x, y - (h - ir));
  7650. this.lineTo(x + s2, y + ir);
  7651. this.lineTo(x - s2, y + ir);
  7652. this.lineTo(x, y - (h - ir));
  7653. this.closePath();
  7654. };
  7655. /**
  7656. * Draw a triangle shape in downward orientation
  7657. * @param {Number} x horizontal center
  7658. * @param {Number} y vertical center
  7659. * @param {Number} r radius
  7660. */
  7661. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7662. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7663. this.beginPath();
  7664. var s = r * 2;
  7665. var s2 = s / 2;
  7666. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7667. var h = Math.sqrt(s * s - s2 * s2); // height
  7668. this.moveTo(x, y + (h - ir));
  7669. this.lineTo(x + s2, y - ir);
  7670. this.lineTo(x - s2, y - ir);
  7671. this.lineTo(x, y + (h - ir));
  7672. this.closePath();
  7673. };
  7674. /**
  7675. * Draw a star shape, a star with 5 points
  7676. * @param {Number} x horizontal center
  7677. * @param {Number} y vertical center
  7678. * @param {Number} r radius, half the length of the sides of the triangle
  7679. */
  7680. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7681. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7682. this.beginPath();
  7683. for (var n = 0; n < 10; n++) {
  7684. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7685. this.lineTo(
  7686. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7687. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7688. );
  7689. }
  7690. this.closePath();
  7691. };
  7692. /**
  7693. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7694. */
  7695. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7696. var r2d = Math.PI/180;
  7697. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7698. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7699. this.beginPath();
  7700. this.moveTo(x+r,y);
  7701. this.lineTo(x+w-r,y);
  7702. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7703. this.lineTo(x+w,y+h-r);
  7704. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7705. this.lineTo(x+r,y+h);
  7706. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7707. this.lineTo(x,y+r);
  7708. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7709. };
  7710. /**
  7711. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7712. */
  7713. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7714. var kappa = .5522848,
  7715. ox = (w / 2) * kappa, // control point offset horizontal
  7716. oy = (h / 2) * kappa, // control point offset vertical
  7717. xe = x + w, // x-end
  7718. ye = y + h, // y-end
  7719. xm = x + w / 2, // x-middle
  7720. ym = y + h / 2; // y-middle
  7721. this.beginPath();
  7722. this.moveTo(x, ym);
  7723. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7724. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7725. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7726. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7727. };
  7728. /**
  7729. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7730. */
  7731. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7732. var f = 1/3;
  7733. var wEllipse = w;
  7734. var hEllipse = h * f;
  7735. var kappa = .5522848,
  7736. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7737. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7738. xe = x + wEllipse, // x-end
  7739. ye = y + hEllipse, // y-end
  7740. xm = x + wEllipse / 2, // x-middle
  7741. ym = y + hEllipse / 2, // y-middle
  7742. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7743. yeb = y + h; // y-end, bottom ellipse
  7744. this.beginPath();
  7745. this.moveTo(xe, ym);
  7746. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7747. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7748. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7749. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7750. this.lineTo(xe, ymb);
  7751. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7752. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7753. this.lineTo(x, ym);
  7754. };
  7755. /**
  7756. * Draw an arrow point (no line)
  7757. */
  7758. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7759. // tail
  7760. var xt = x - length * Math.cos(angle);
  7761. var yt = y - length * Math.sin(angle);
  7762. // inner tail
  7763. // TODO: allow to customize different shapes
  7764. var xi = x - length * 0.9 * Math.cos(angle);
  7765. var yi = y - length * 0.9 * Math.sin(angle);
  7766. // left
  7767. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7768. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7769. // right
  7770. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7771. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7772. this.beginPath();
  7773. this.moveTo(x, y);
  7774. this.lineTo(xl, yl);
  7775. this.lineTo(xi, yi);
  7776. this.lineTo(xr, yr);
  7777. this.closePath();
  7778. };
  7779. /**
  7780. * Sets up the dashedLine functionality for drawing
  7781. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7782. * @author David Jordan
  7783. * @date 2012-08-08
  7784. */
  7785. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7786. if (!dashArray) dashArray=[10,5];
  7787. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7788. var dashCount = dashArray.length;
  7789. this.moveTo(x, y);
  7790. var dx = (x2-x), dy = (y2-y);
  7791. var slope = dy/dx;
  7792. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7793. var dashIndex=0, draw=true;
  7794. while (distRemaining>=0.1){
  7795. var dashLength = dashArray[dashIndex++%dashCount];
  7796. if (dashLength > distRemaining) dashLength = distRemaining;
  7797. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7798. if (dx<0) xStep = -xStep;
  7799. x += xStep;
  7800. y += slope*xStep;
  7801. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7802. distRemaining -= dashLength;
  7803. draw = !draw;
  7804. }
  7805. };
  7806. // TODO: add diamond shape
  7807. }
  7808. /**
  7809. * @class Node
  7810. * A node. A node can be connected to other nodes via one or multiple edges.
  7811. * @param {object} properties An object containing properties for the node. All
  7812. * properties are optional, except for the id.
  7813. * {number} id Id of the node. Required
  7814. * {string} label Text label for the node
  7815. * {number} x Horizontal position of the node
  7816. * {number} y Vertical position of the node
  7817. * {string} shape Node shape, available:
  7818. * "database", "circle", "ellipse",
  7819. * "box", "image", "text", "dot",
  7820. * "star", "triangle", "triangleDown",
  7821. * "square"
  7822. * {string} image An image url
  7823. * {string} title An title text, can be HTML
  7824. * {anytype} group A group name or number
  7825. * @param {Graph.Images} imagelist A list with images. Only needed
  7826. * when the node has an image
  7827. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7828. * retrieving group properties
  7829. * @param {Object} constants An object with default values for
  7830. * example for the color
  7831. *
  7832. */
  7833. function Node(properties, imagelist, grouplist, constants) {
  7834. this.selected = false;
  7835. this.edges = []; // all edges connected to this node
  7836. this.dynamicEdges = [];
  7837. this.reroutedEdges = {};
  7838. this.group = constants.nodes.group;
  7839. this.fontSize = constants.nodes.fontSize;
  7840. this.fontFace = constants.nodes.fontFace;
  7841. this.fontColor = constants.nodes.fontColor;
  7842. this.fontDrawThreshold = 3;
  7843. this.color = constants.nodes.color;
  7844. // set defaults for the properties
  7845. this.id = undefined;
  7846. this.shape = constants.nodes.shape;
  7847. this.image = constants.nodes.image;
  7848. this.x = null;
  7849. this.y = null;
  7850. this.xFixed = false;
  7851. this.yFixed = false;
  7852. this.horizontalAlignLeft = true; // these are for the navigation controls
  7853. this.verticalAlignTop = true; // these are for the navigation controls
  7854. this.radius = constants.nodes.radius;
  7855. this.baseRadiusValue = constants.nodes.radius;
  7856. this.radiusFixed = false;
  7857. this.radiusMin = constants.nodes.radiusMin;
  7858. this.radiusMax = constants.nodes.radiusMax;
  7859. this.level = -1;
  7860. this.preassignedLevel = false;
  7861. this.imagelist = imagelist;
  7862. this.grouplist = grouplist;
  7863. // physics properties
  7864. this.fx = 0.0; // external force x
  7865. this.fy = 0.0; // external force y
  7866. this.vx = 0.0; // velocity x
  7867. this.vy = 0.0; // velocity y
  7868. this.minForce = constants.minForce;
  7869. this.damping = constants.physics.damping;
  7870. this.mass = 1; // kg
  7871. this.fixedData = {x:null,y:null};
  7872. this.setProperties(properties, constants);
  7873. // creating the variables for clustering
  7874. this.resetCluster();
  7875. this.dynamicEdgesLength = 0;
  7876. this.clusterSession = 0;
  7877. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7878. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7879. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7880. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7881. this.growthIndicator = 0;
  7882. // variables to tell the node about the graph.
  7883. this.graphScaleInv = 1;
  7884. this.graphScale = 1;
  7885. this.canvasTopLeft = {"x": -300, "y": -300};
  7886. this.canvasBottomRight = {"x": 300, "y": 300};
  7887. this.parentEdgeId = null;
  7888. }
  7889. /**
  7890. * (re)setting the clustering variables and objects
  7891. */
  7892. Node.prototype.resetCluster = function() {
  7893. // clustering variables
  7894. this.formationScale = undefined; // this is used to determine when to open the cluster
  7895. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7896. this.containedNodes = {};
  7897. this.containedEdges = {};
  7898. this.clusterSessions = [];
  7899. };
  7900. /**
  7901. * Attach a edge to the node
  7902. * @param {Edge} edge
  7903. */
  7904. Node.prototype.attachEdge = function(edge) {
  7905. if (this.edges.indexOf(edge) == -1) {
  7906. this.edges.push(edge);
  7907. }
  7908. if (this.dynamicEdges.indexOf(edge) == -1) {
  7909. this.dynamicEdges.push(edge);
  7910. }
  7911. this.dynamicEdgesLength = this.dynamicEdges.length;
  7912. };
  7913. /**
  7914. * Detach a edge from the node
  7915. * @param {Edge} edge
  7916. */
  7917. Node.prototype.detachEdge = function(edge) {
  7918. var index = this.edges.indexOf(edge);
  7919. if (index != -1) {
  7920. this.edges.splice(index, 1);
  7921. this.dynamicEdges.splice(index, 1);
  7922. }
  7923. this.dynamicEdgesLength = this.dynamicEdges.length;
  7924. };
  7925. /**
  7926. * Set or overwrite properties for the node
  7927. * @param {Object} properties an object with properties
  7928. * @param {Object} constants and object with default, global properties
  7929. */
  7930. Node.prototype.setProperties = function(properties, constants) {
  7931. if (!properties) {
  7932. return;
  7933. }
  7934. this.originalLabel = undefined;
  7935. // basic properties
  7936. if (properties.id !== undefined) {this.id = properties.id;}
  7937. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7938. if (properties.title !== undefined) {this.title = properties.title;}
  7939. if (properties.group !== undefined) {this.group = properties.group;}
  7940. if (properties.x !== undefined) {this.x = properties.x;}
  7941. if (properties.y !== undefined) {this.y = properties.y;}
  7942. if (properties.value !== undefined) {this.value = properties.value;}
  7943. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  7944. // physics
  7945. if (properties.mass !== undefined) {this.mass = properties.mass;}
  7946. // navigation controls properties
  7947. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  7948. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  7949. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  7950. if (this.id === undefined) {
  7951. throw "Node must have an id";
  7952. }
  7953. // copy group properties
  7954. if (this.group) {
  7955. var groupObj = this.grouplist.get(this.group);
  7956. for (var prop in groupObj) {
  7957. if (groupObj.hasOwnProperty(prop)) {
  7958. this[prop] = groupObj[prop];
  7959. }
  7960. }
  7961. }
  7962. // individual shape properties
  7963. if (properties.shape !== undefined) {this.shape = properties.shape;}
  7964. if (properties.image !== undefined) {this.image = properties.image;}
  7965. if (properties.radius !== undefined) {this.radius = properties.radius;}
  7966. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  7967. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  7968. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  7969. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  7970. if (this.image !== undefined && this.image != "") {
  7971. if (this.imagelist) {
  7972. this.imageObj = this.imagelist.load(this.image);
  7973. }
  7974. else {
  7975. throw "No imagelist provided";
  7976. }
  7977. }
  7978. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  7979. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  7980. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  7981. if (this.shape == 'image') {
  7982. this.radiusMin = constants.nodes.widthMin;
  7983. this.radiusMax = constants.nodes.widthMax;
  7984. }
  7985. // choose draw method depending on the shape
  7986. switch (this.shape) {
  7987. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7988. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7989. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7990. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7991. // TODO: add diamond shape
  7992. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7993. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7994. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7995. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7996. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7997. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7998. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7999. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8000. }
  8001. // reset the size of the node, this can be changed
  8002. this._reset();
  8003. };
  8004. /**
  8005. * select this node
  8006. */
  8007. Node.prototype.select = function() {
  8008. this.selected = true;
  8009. this._reset();
  8010. };
  8011. /**
  8012. * unselect this node
  8013. */
  8014. Node.prototype.unselect = function() {
  8015. this.selected = false;
  8016. this._reset();
  8017. };
  8018. /**
  8019. * Reset the calculated size of the node, forces it to recalculate its size
  8020. */
  8021. Node.prototype.clearSizeCache = function() {
  8022. this._reset();
  8023. };
  8024. /**
  8025. * Reset the calculated size of the node, forces it to recalculate its size
  8026. * @private
  8027. */
  8028. Node.prototype._reset = function() {
  8029. this.width = undefined;
  8030. this.height = undefined;
  8031. };
  8032. /**
  8033. * get the title of this node.
  8034. * @return {string} title The title of the node, or undefined when no title
  8035. * has been set.
  8036. */
  8037. Node.prototype.getTitle = function() {
  8038. return typeof this.title === "function" ? this.title() : this.title;
  8039. };
  8040. /**
  8041. * Calculate the distance to the border of the Node
  8042. * @param {CanvasRenderingContext2D} ctx
  8043. * @param {Number} angle Angle in radians
  8044. * @returns {number} distance Distance to the border in pixels
  8045. */
  8046. Node.prototype.distanceToBorder = function (ctx, angle) {
  8047. var borderWidth = 1;
  8048. if (!this.width) {
  8049. this.resize(ctx);
  8050. }
  8051. switch (this.shape) {
  8052. case 'circle':
  8053. case 'dot':
  8054. return this.radius + borderWidth;
  8055. case 'ellipse':
  8056. var a = this.width / 2;
  8057. var b = this.height / 2;
  8058. var w = (Math.sin(angle) * a);
  8059. var h = (Math.cos(angle) * b);
  8060. return a * b / Math.sqrt(w * w + h * h);
  8061. // TODO: implement distanceToBorder for database
  8062. // TODO: implement distanceToBorder for triangle
  8063. // TODO: implement distanceToBorder for triangleDown
  8064. case 'box':
  8065. case 'image':
  8066. case 'text':
  8067. default:
  8068. if (this.width) {
  8069. return Math.min(
  8070. Math.abs(this.width / 2 / Math.cos(angle)),
  8071. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8072. // TODO: reckon with border radius too in case of box
  8073. }
  8074. else {
  8075. return 0;
  8076. }
  8077. }
  8078. // TODO: implement calculation of distance to border for all shapes
  8079. };
  8080. /**
  8081. * Set forces acting on the node
  8082. * @param {number} fx Force in horizontal direction
  8083. * @param {number} fy Force in vertical direction
  8084. */
  8085. Node.prototype._setForce = function(fx, fy) {
  8086. this.fx = fx;
  8087. this.fy = fy;
  8088. };
  8089. /**
  8090. * Add forces acting on the node
  8091. * @param {number} fx Force in horizontal direction
  8092. * @param {number} fy Force in vertical direction
  8093. * @private
  8094. */
  8095. Node.prototype._addForce = function(fx, fy) {
  8096. this.fx += fx;
  8097. this.fy += fy;
  8098. };
  8099. /**
  8100. * Perform one discrete step for the node
  8101. * @param {number} interval Time interval in seconds
  8102. */
  8103. Node.prototype.discreteStep = function(interval) {
  8104. if (!this.xFixed) {
  8105. var dx = this.damping * this.vx; // damping force
  8106. var ax = (this.fx - dx) / this.mass; // acceleration
  8107. this.vx += ax * interval; // velocity
  8108. this.x += this.vx * interval; // position
  8109. }
  8110. if (!this.yFixed) {
  8111. var dy = this.damping * this.vy; // damping force
  8112. var ay = (this.fy - dy) / this.mass; // acceleration
  8113. this.vy += ay * interval; // velocity
  8114. this.y += this.vy * interval; // position
  8115. }
  8116. };
  8117. /**
  8118. * Perform one discrete step for the node
  8119. * @param {number} interval Time interval in seconds
  8120. * @param {number} maxVelocity The speed limit imposed on the velocity
  8121. */
  8122. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8123. if (!this.xFixed) {
  8124. var dx = this.damping * this.vx; // damping force
  8125. var ax = (this.fx - dx) / this.mass; // acceleration
  8126. this.vx += ax * interval; // velocity
  8127. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8128. this.x += this.vx * interval; // position
  8129. }
  8130. else {
  8131. this.fx = 0;
  8132. }
  8133. if (!this.yFixed) {
  8134. var dy = this.damping * this.vy; // damping force
  8135. var ay = (this.fy - dy) / this.mass; // acceleration
  8136. this.vy += ay * interval; // velocity
  8137. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8138. this.y += this.vy * interval; // position
  8139. }
  8140. else {
  8141. this.fy = 0;
  8142. }
  8143. };
  8144. /**
  8145. * Check if this node has a fixed x and y position
  8146. * @return {boolean} true if fixed, false if not
  8147. */
  8148. Node.prototype.isFixed = function() {
  8149. return (this.xFixed && this.yFixed);
  8150. };
  8151. /**
  8152. * Check if this node is moving
  8153. * @param {number} vmin the minimum velocity considered as "moving"
  8154. * @return {boolean} true if moving, false if it has no velocity
  8155. */
  8156. // TODO: replace this method with calculating the kinetic energy
  8157. Node.prototype.isMoving = function(vmin) {
  8158. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8159. };
  8160. /**
  8161. * check if this node is selecte
  8162. * @return {boolean} selected True if node is selected, else false
  8163. */
  8164. Node.prototype.isSelected = function() {
  8165. return this.selected;
  8166. };
  8167. /**
  8168. * Retrieve the value of the node. Can be undefined
  8169. * @return {Number} value
  8170. */
  8171. Node.prototype.getValue = function() {
  8172. return this.value;
  8173. };
  8174. /**
  8175. * Calculate the distance from the nodes location to the given location (x,y)
  8176. * @param {Number} x
  8177. * @param {Number} y
  8178. * @return {Number} value
  8179. */
  8180. Node.prototype.getDistance = function(x, y) {
  8181. var dx = this.x - x,
  8182. dy = this.y - y;
  8183. return Math.sqrt(dx * dx + dy * dy);
  8184. };
  8185. /**
  8186. * Adjust the value range of the node. The node will adjust it's radius
  8187. * based on its value.
  8188. * @param {Number} min
  8189. * @param {Number} max
  8190. */
  8191. Node.prototype.setValueRange = function(min, max) {
  8192. if (!this.radiusFixed && this.value !== undefined) {
  8193. if (max == min) {
  8194. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8195. }
  8196. else {
  8197. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8198. this.radius = (this.value - min) * scale + this.radiusMin;
  8199. }
  8200. }
  8201. this.baseRadiusValue = this.radius;
  8202. };
  8203. /**
  8204. * Draw this node in the given canvas
  8205. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8206. * @param {CanvasRenderingContext2D} ctx
  8207. */
  8208. Node.prototype.draw = function(ctx) {
  8209. throw "Draw method not initialized for node";
  8210. };
  8211. /**
  8212. * Recalculate the size of this node in the given canvas
  8213. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8214. * @param {CanvasRenderingContext2D} ctx
  8215. */
  8216. Node.prototype.resize = function(ctx) {
  8217. throw "Resize method not initialized for node";
  8218. };
  8219. /**
  8220. * Check if this object is overlapping with the provided object
  8221. * @param {Object} obj an object with parameters left, top, right, bottom
  8222. * @return {boolean} True if location is located on node
  8223. */
  8224. Node.prototype.isOverlappingWith = function(obj) {
  8225. return (this.left < obj.right &&
  8226. this.left + this.width > obj.left &&
  8227. this.top < obj.bottom &&
  8228. this.top + this.height > obj.top);
  8229. };
  8230. Node.prototype._resizeImage = function (ctx) {
  8231. // TODO: pre calculate the image size
  8232. if (!this.width || !this.height) { // undefined or 0
  8233. var width, height;
  8234. if (this.value) {
  8235. this.radius = this.baseRadiusValue;
  8236. var scale = this.imageObj.height / this.imageObj.width;
  8237. if (scale !== undefined) {
  8238. width = this.radius || this.imageObj.width;
  8239. height = this.radius * scale || this.imageObj.height;
  8240. }
  8241. else {
  8242. width = 0;
  8243. height = 0;
  8244. }
  8245. }
  8246. else {
  8247. width = this.imageObj.width;
  8248. height = this.imageObj.height;
  8249. }
  8250. this.width = width;
  8251. this.height = height;
  8252. this.growthIndicator = 0;
  8253. if (this.width > 0 && this.height > 0) {
  8254. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8255. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8256. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8257. this.growthIndicator = this.width - width;
  8258. }
  8259. }
  8260. };
  8261. Node.prototype._drawImage = function (ctx) {
  8262. this._resizeImage(ctx);
  8263. this.left = this.x - this.width / 2;
  8264. this.top = this.y - this.height / 2;
  8265. var yLabel;
  8266. if (this.imageObj.width != 0 ) {
  8267. // draw the shade
  8268. if (this.clusterSize > 1) {
  8269. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8270. lineWidth *= this.graphScaleInv;
  8271. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8272. ctx.globalAlpha = 0.5;
  8273. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8274. }
  8275. // draw the image
  8276. ctx.globalAlpha = 1.0;
  8277. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8278. yLabel = this.y + this.height / 2;
  8279. }
  8280. else {
  8281. // image still loading... just draw the label for now
  8282. yLabel = this.y;
  8283. }
  8284. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8285. };
  8286. Node.prototype._resizeBox = function (ctx) {
  8287. if (!this.width) {
  8288. var margin = 5;
  8289. var textSize = this.getTextSize(ctx);
  8290. this.width = textSize.width + 2 * margin;
  8291. this.height = textSize.height + 2 * margin;
  8292. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8293. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8294. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8295. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8296. }
  8297. };
  8298. Node.prototype._drawBox = function (ctx) {
  8299. this._resizeBox(ctx);
  8300. this.left = this.x - this.width / 2;
  8301. this.top = this.y - this.height / 2;
  8302. var clusterLineWidth = 2.5;
  8303. var selectionLineWidth = 2;
  8304. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8305. // draw the outer border
  8306. if (this.clusterSize > 1) {
  8307. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8308. ctx.lineWidth *= this.graphScaleInv;
  8309. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8310. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8311. ctx.stroke();
  8312. }
  8313. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8314. ctx.lineWidth *= this.graphScaleInv;
  8315. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8316. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8317. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8318. ctx.fill();
  8319. ctx.stroke();
  8320. this._label(ctx, this.label, this.x, this.y);
  8321. };
  8322. Node.prototype._resizeDatabase = function (ctx) {
  8323. if (!this.width) {
  8324. var margin = 5;
  8325. var textSize = this.getTextSize(ctx);
  8326. var size = textSize.width + 2 * margin;
  8327. this.width = size;
  8328. this.height = size;
  8329. // scaling used for clustering
  8330. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8331. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8332. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8333. this.growthIndicator = this.width - size;
  8334. }
  8335. };
  8336. Node.prototype._drawDatabase = function (ctx) {
  8337. this._resizeDatabase(ctx);
  8338. this.left = this.x - this.width / 2;
  8339. this.top = this.y - this.height / 2;
  8340. var clusterLineWidth = 2.5;
  8341. var selectionLineWidth = 2;
  8342. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8343. // draw the outer border
  8344. if (this.clusterSize > 1) {
  8345. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8346. ctx.lineWidth *= this.graphScaleInv;
  8347. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8348. 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);
  8349. ctx.stroke();
  8350. }
  8351. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8352. ctx.lineWidth *= this.graphScaleInv;
  8353. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8354. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8355. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8356. ctx.fill();
  8357. ctx.stroke();
  8358. this._label(ctx, this.label, this.x, this.y);
  8359. };
  8360. Node.prototype._resizeCircle = function (ctx) {
  8361. if (!this.width) {
  8362. var margin = 5;
  8363. var textSize = this.getTextSize(ctx);
  8364. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8365. this.radius = diameter / 2;
  8366. this.width = diameter;
  8367. this.height = diameter;
  8368. // scaling used for clustering
  8369. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8370. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8371. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8372. this.growthIndicator = this.radius - 0.5*diameter;
  8373. }
  8374. };
  8375. Node.prototype._drawCircle = function (ctx) {
  8376. this._resizeCircle(ctx);
  8377. this.left = this.x - this.width / 2;
  8378. this.top = this.y - this.height / 2;
  8379. var clusterLineWidth = 2.5;
  8380. var selectionLineWidth = 2;
  8381. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8382. // draw the outer border
  8383. if (this.clusterSize > 1) {
  8384. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8385. ctx.lineWidth *= this.graphScaleInv;
  8386. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8387. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8388. ctx.stroke();
  8389. }
  8390. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8391. ctx.lineWidth *= this.graphScaleInv;
  8392. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8393. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8394. ctx.circle(this.x, this.y, this.radius);
  8395. ctx.fill();
  8396. ctx.stroke();
  8397. this._label(ctx, this.label, this.x, this.y);
  8398. };
  8399. Node.prototype._resizeEllipse = function (ctx) {
  8400. if (!this.width) {
  8401. var textSize = this.getTextSize(ctx);
  8402. this.width = textSize.width * 1.5;
  8403. this.height = textSize.height * 2;
  8404. if (this.width < this.height) {
  8405. this.width = this.height;
  8406. }
  8407. var defaultSize = this.width;
  8408. // scaling used for clustering
  8409. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8410. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8411. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8412. this.growthIndicator = this.width - defaultSize;
  8413. }
  8414. };
  8415. Node.prototype._drawEllipse = function (ctx) {
  8416. this._resizeEllipse(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.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*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.ellipse(this.left, this.top, this.width, this.height);
  8435. ctx.fill();
  8436. ctx.stroke();
  8437. this._label(ctx, this.label, this.x, this.y);
  8438. };
  8439. Node.prototype._drawDot = function (ctx) {
  8440. this._drawShape(ctx, 'circle');
  8441. };
  8442. Node.prototype._drawTriangle = function (ctx) {
  8443. this._drawShape(ctx, 'triangle');
  8444. };
  8445. Node.prototype._drawTriangleDown = function (ctx) {
  8446. this._drawShape(ctx, 'triangleDown');
  8447. };
  8448. Node.prototype._drawSquare = function (ctx) {
  8449. this._drawShape(ctx, 'square');
  8450. };
  8451. Node.prototype._drawStar = function (ctx) {
  8452. this._drawShape(ctx, 'star');
  8453. };
  8454. Node.prototype._resizeShape = function (ctx) {
  8455. if (!this.width) {
  8456. this.radius = this.baseRadiusValue;
  8457. var size = 2 * this.radius;
  8458. this.width = size;
  8459. this.height = size;
  8460. // scaling used for clustering
  8461. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8462. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8463. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8464. this.growthIndicator = this.width - size;
  8465. }
  8466. };
  8467. Node.prototype._drawShape = function (ctx, shape) {
  8468. this._resizeShape(ctx);
  8469. this.left = this.x - this.width / 2;
  8470. this.top = this.y - this.height / 2;
  8471. var clusterLineWidth = 2.5;
  8472. var selectionLineWidth = 2;
  8473. var radiusMultiplier = 2;
  8474. // choose draw method depending on the shape
  8475. switch (shape) {
  8476. case 'dot': radiusMultiplier = 2; break;
  8477. case 'square': radiusMultiplier = 2; break;
  8478. case 'triangle': radiusMultiplier = 3; break;
  8479. case 'triangleDown': radiusMultiplier = 3; break;
  8480. case 'star': radiusMultiplier = 4; break;
  8481. }
  8482. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8483. // draw the outer border
  8484. if (this.clusterSize > 1) {
  8485. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8486. ctx.lineWidth *= this.graphScaleInv;
  8487. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8488. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8489. ctx.stroke();
  8490. }
  8491. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8492. ctx.lineWidth *= this.graphScaleInv;
  8493. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8494. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8495. ctx[shape](this.x, this.y, this.radius);
  8496. ctx.fill();
  8497. ctx.stroke();
  8498. if (this.label) {
  8499. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8500. }
  8501. };
  8502. Node.prototype._resizeText = function (ctx) {
  8503. if (!this.width) {
  8504. var margin = 5;
  8505. var textSize = this.getTextSize(ctx);
  8506. this.width = textSize.width + 2 * margin;
  8507. this.height = textSize.height + 2 * margin;
  8508. // scaling used for clustering
  8509. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8510. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8511. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8512. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8513. }
  8514. };
  8515. Node.prototype._drawText = function (ctx) {
  8516. this._resizeText(ctx);
  8517. this.left = this.x - this.width / 2;
  8518. this.top = this.y - this.height / 2;
  8519. this._label(ctx, this.label, this.x, this.y);
  8520. };
  8521. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8522. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8523. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8524. ctx.fillStyle = this.fontColor || "black";
  8525. ctx.textAlign = align || "center";
  8526. ctx.textBaseline = baseline || "middle";
  8527. var lines = text.split('\n'),
  8528. lineCount = lines.length,
  8529. fontSize = (this.fontSize + 4),
  8530. yLine = y + (1 - lineCount) / 2 * fontSize;
  8531. for (var i = 0; i < lineCount; i++) {
  8532. ctx.fillText(lines[i], x, yLine);
  8533. yLine += fontSize;
  8534. }
  8535. }
  8536. };
  8537. Node.prototype.getTextSize = function(ctx) {
  8538. if (this.label !== undefined) {
  8539. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8540. var lines = this.label.split('\n'),
  8541. height = (this.fontSize + 4) * lines.length,
  8542. width = 0;
  8543. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8544. width = Math.max(width, ctx.measureText(lines[i]).width);
  8545. }
  8546. return {"width": width, "height": height};
  8547. }
  8548. else {
  8549. return {"width": 0, "height": 0};
  8550. }
  8551. };
  8552. /**
  8553. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8554. * there is a safety margin of 0.3 * width;
  8555. *
  8556. * @returns {boolean}
  8557. */
  8558. Node.prototype.inArea = function() {
  8559. if (this.width !== undefined) {
  8560. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8561. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8562. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8563. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8564. }
  8565. else {
  8566. return true;
  8567. }
  8568. };
  8569. /**
  8570. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8571. * @returns {boolean}
  8572. */
  8573. Node.prototype.inView = function() {
  8574. return (this.x >= this.canvasTopLeft.x &&
  8575. this.x < this.canvasBottomRight.x &&
  8576. this.y >= this.canvasTopLeft.y &&
  8577. this.y < this.canvasBottomRight.y);
  8578. };
  8579. /**
  8580. * This allows the zoom level of the graph to influence the rendering
  8581. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8582. *
  8583. * @param scale
  8584. * @param canvasTopLeft
  8585. * @param canvasBottomRight
  8586. */
  8587. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8588. this.graphScaleInv = 1.0/scale;
  8589. this.graphScale = scale;
  8590. this.canvasTopLeft = canvasTopLeft;
  8591. this.canvasBottomRight = canvasBottomRight;
  8592. };
  8593. /**
  8594. * This allows the zoom level of the graph to influence the rendering
  8595. *
  8596. * @param scale
  8597. */
  8598. Node.prototype.setScale = function(scale) {
  8599. this.graphScaleInv = 1.0/scale;
  8600. this.graphScale = scale;
  8601. };
  8602. /**
  8603. * set the velocity at 0. Is called when this node is contained in another during clustering
  8604. */
  8605. Node.prototype.clearVelocity = function() {
  8606. this.vx = 0;
  8607. this.vy = 0;
  8608. };
  8609. /**
  8610. * Basic preservation of (kinectic) energy
  8611. *
  8612. * @param massBeforeClustering
  8613. */
  8614. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8615. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8616. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8617. this.vx = Math.sqrt(energyBefore/this.mass);
  8618. energyBefore = this.vy * this.vy * massBeforeClustering;
  8619. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8620. this.vy = Math.sqrt(energyBefore/this.mass);
  8621. };
  8622. /**
  8623. * @class Edge
  8624. *
  8625. * A edge connects two nodes
  8626. * @param {Object} properties Object with properties. Must contain
  8627. * At least properties from and to.
  8628. * Available properties: from (number),
  8629. * to (number), label (string, color (string),
  8630. * width (number), style (string),
  8631. * length (number), title (string)
  8632. * @param {Graph} graph A graph object, used to find and edge to
  8633. * nodes.
  8634. * @param {Object} constants An object with default values for
  8635. * example for the color
  8636. */
  8637. function Edge (properties, graph, constants) {
  8638. if (!graph) {
  8639. throw "No graph provided";
  8640. }
  8641. this.graph = graph;
  8642. // initialize constants
  8643. this.widthMin = constants.edges.widthMin;
  8644. this.widthMax = constants.edges.widthMax;
  8645. // initialize variables
  8646. this.id = undefined;
  8647. this.fromId = undefined;
  8648. this.toId = undefined;
  8649. this.style = constants.edges.style;
  8650. this.title = undefined;
  8651. this.width = constants.edges.width;
  8652. this.value = undefined;
  8653. this.length = constants.physics.springLength;
  8654. this.customLength = false;
  8655. this.selected = false;
  8656. this.smooth = constants.smoothCurves;
  8657. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  8658. this.from = null; // a node
  8659. this.to = null; // a node
  8660. this.via = null; // a temp node
  8661. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8662. // by storing the original information we can revert to the original connection when the cluser is opened.
  8663. this.originalFromId = [];
  8664. this.originalToId = [];
  8665. this.connected = false;
  8666. // Added to support dashed lines
  8667. // David Jordan
  8668. // 2012-08-08
  8669. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8670. this.color = {color:constants.edges.color.color,
  8671. highlight:constants.edges.color.highlight};
  8672. this.widthFixed = false;
  8673. this.lengthFixed = false;
  8674. this.setProperties(properties, constants);
  8675. }
  8676. /**
  8677. * Set or overwrite properties for the edge
  8678. * @param {Object} properties an object with properties
  8679. * @param {Object} constants and object with default, global properties
  8680. */
  8681. Edge.prototype.setProperties = function(properties, constants) {
  8682. if (!properties) {
  8683. return;
  8684. }
  8685. if (properties.from !== undefined) {this.fromId = properties.from;}
  8686. if (properties.to !== undefined) {this.toId = properties.to;}
  8687. if (properties.id !== undefined) {this.id = properties.id;}
  8688. if (properties.style !== undefined) {this.style = properties.style;}
  8689. if (properties.label !== undefined) {this.label = properties.label;}
  8690. if (this.label) {
  8691. this.fontSize = constants.edges.fontSize;
  8692. this.fontFace = constants.edges.fontFace;
  8693. this.fontColor = constants.edges.fontColor;
  8694. this.fontFill = constants.edges.fontFill;
  8695. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8696. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8697. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8698. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8699. }
  8700. if (properties.title !== undefined) {this.title = properties.title;}
  8701. if (properties.width !== undefined) {this.width = properties.width;}
  8702. if (properties.value !== undefined) {this.value = properties.value;}
  8703. if (properties.length !== undefined) {this.length = properties.length;
  8704. this.customLength = true;}
  8705. // scale the arrow
  8706. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
  8707. // Added to support dashed lines
  8708. // David Jordan
  8709. // 2012-08-08
  8710. if (properties.dash) {
  8711. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8712. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8713. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8714. }
  8715. if (properties.color !== undefined) {
  8716. if (util.isString(properties.color)) {
  8717. this.color.color = properties.color;
  8718. this.color.highlight = properties.color;
  8719. }
  8720. else {
  8721. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8722. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8723. }
  8724. }
  8725. // A node is connected when it has a from and to node.
  8726. this.connect();
  8727. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8728. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8729. // set draw method based on style
  8730. switch (this.style) {
  8731. case 'line': this.draw = this._drawLine; break;
  8732. case 'arrow': this.draw = this._drawArrow; break;
  8733. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8734. case 'dash-line': this.draw = this._drawDashLine; break;
  8735. default: this.draw = this._drawLine; break;
  8736. }
  8737. };
  8738. /**
  8739. * Connect an edge to its nodes
  8740. */
  8741. Edge.prototype.connect = function () {
  8742. this.disconnect();
  8743. this.from = this.graph.nodes[this.fromId] || null;
  8744. this.to = this.graph.nodes[this.toId] || null;
  8745. this.connected = (this.from && this.to);
  8746. if (this.connected) {
  8747. this.from.attachEdge(this);
  8748. this.to.attachEdge(this);
  8749. }
  8750. else {
  8751. if (this.from) {
  8752. this.from.detachEdge(this);
  8753. }
  8754. if (this.to) {
  8755. this.to.detachEdge(this);
  8756. }
  8757. }
  8758. };
  8759. /**
  8760. * Disconnect an edge from its nodes
  8761. */
  8762. Edge.prototype.disconnect = function () {
  8763. if (this.from) {
  8764. this.from.detachEdge(this);
  8765. this.from = null;
  8766. }
  8767. if (this.to) {
  8768. this.to.detachEdge(this);
  8769. this.to = null;
  8770. }
  8771. this.connected = false;
  8772. };
  8773. /**
  8774. * get the title of this edge.
  8775. * @return {string} title The title of the edge, or undefined when no title
  8776. * has been set.
  8777. */
  8778. Edge.prototype.getTitle = function() {
  8779. return typeof this.title === "function" ? this.title() : this.title;
  8780. };
  8781. /**
  8782. * Retrieve the value of the edge. Can be undefined
  8783. * @return {Number} value
  8784. */
  8785. Edge.prototype.getValue = function() {
  8786. return this.value;
  8787. };
  8788. /**
  8789. * Adjust the value range of the edge. The edge will adjust it's width
  8790. * based on its value.
  8791. * @param {Number} min
  8792. * @param {Number} max
  8793. */
  8794. Edge.prototype.setValueRange = function(min, max) {
  8795. if (!this.widthFixed && this.value !== undefined) {
  8796. var scale = (this.widthMax - this.widthMin) / (max - min);
  8797. this.width = (this.value - min) * scale + this.widthMin;
  8798. }
  8799. };
  8800. /**
  8801. * Redraw a edge
  8802. * Draw this edge in the given canvas
  8803. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8804. * @param {CanvasRenderingContext2D} ctx
  8805. */
  8806. Edge.prototype.draw = function(ctx) {
  8807. throw "Method draw not initialized in edge";
  8808. };
  8809. /**
  8810. * Check if this object is overlapping with the provided object
  8811. * @param {Object} obj an object with parameters left, top
  8812. * @return {boolean} True if location is located on the edge
  8813. */
  8814. Edge.prototype.isOverlappingWith = function(obj) {
  8815. if (this.connected) {
  8816. var distMax = 10;
  8817. var xFrom = this.from.x;
  8818. var yFrom = this.from.y;
  8819. var xTo = this.to.x;
  8820. var yTo = this.to.y;
  8821. var xObj = obj.left;
  8822. var yObj = obj.top;
  8823. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8824. return (dist < distMax);
  8825. }
  8826. else {
  8827. return false
  8828. }
  8829. };
  8830. /**
  8831. * Redraw a edge as a line
  8832. * Draw this edge in the given canvas
  8833. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8834. * @param {CanvasRenderingContext2D} ctx
  8835. * @private
  8836. */
  8837. Edge.prototype._drawLine = function(ctx) {
  8838. // set style
  8839. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8840. else {ctx.strokeStyle = this.color.color;}
  8841. ctx.lineWidth = this._getLineWidth();
  8842. if (this.from != this.to) {
  8843. // draw line
  8844. this._line(ctx);
  8845. // draw label
  8846. var point;
  8847. if (this.label) {
  8848. if (this.smooth == true) {
  8849. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8850. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8851. point = {x:midpointX, y:midpointY};
  8852. }
  8853. else {
  8854. point = this._pointOnLine(0.5);
  8855. }
  8856. this._label(ctx, this.label, point.x, point.y);
  8857. }
  8858. }
  8859. else {
  8860. var x, y;
  8861. var radius = this.length / 4;
  8862. var node = this.from;
  8863. if (!node.width) {
  8864. node.resize(ctx);
  8865. }
  8866. if (node.width > node.height) {
  8867. x = node.x + node.width / 2;
  8868. y = node.y - radius;
  8869. }
  8870. else {
  8871. x = node.x + radius;
  8872. y = node.y - node.height / 2;
  8873. }
  8874. this._circle(ctx, x, y, radius);
  8875. point = this._pointOnCircle(x, y, radius, 0.5);
  8876. this._label(ctx, this.label, point.x, point.y);
  8877. }
  8878. };
  8879. /**
  8880. * Get the line width of the edge. Depends on width and whether one of the
  8881. * connected nodes is selected.
  8882. * @return {Number} width
  8883. * @private
  8884. */
  8885. Edge.prototype._getLineWidth = function() {
  8886. if (this.selected == true) {
  8887. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8888. }
  8889. else {
  8890. return this.width*this.graphScaleInv;
  8891. }
  8892. };
  8893. /**
  8894. * Draw a line between two nodes
  8895. * @param {CanvasRenderingContext2D} ctx
  8896. * @private
  8897. */
  8898. Edge.prototype._line = function (ctx) {
  8899. // draw a straight line
  8900. ctx.beginPath();
  8901. ctx.moveTo(this.from.x, this.from.y);
  8902. if (this.smooth == true) {
  8903. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8904. }
  8905. else {
  8906. ctx.lineTo(this.to.x, this.to.y);
  8907. }
  8908. ctx.stroke();
  8909. };
  8910. /**
  8911. * Draw a line from a node to itself, a circle
  8912. * @param {CanvasRenderingContext2D} ctx
  8913. * @param {Number} x
  8914. * @param {Number} y
  8915. * @param {Number} radius
  8916. * @private
  8917. */
  8918. Edge.prototype._circle = function (ctx, x, y, radius) {
  8919. // draw a circle
  8920. ctx.beginPath();
  8921. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8922. ctx.stroke();
  8923. };
  8924. /**
  8925. * Draw label with white background and with the middle at (x, y)
  8926. * @param {CanvasRenderingContext2D} ctx
  8927. * @param {String} text
  8928. * @param {Number} x
  8929. * @param {Number} y
  8930. * @private
  8931. */
  8932. Edge.prototype._label = function (ctx, text, x, y) {
  8933. if (text) {
  8934. // TODO: cache the calculated size
  8935. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8936. this.fontSize + "px " + this.fontFace;
  8937. ctx.fillStyle = this.fontFill;
  8938. var width = ctx.measureText(text).width;
  8939. var height = this.fontSize;
  8940. var left = x - width / 2;
  8941. var top = y - height / 2;
  8942. ctx.fillRect(left, top, width, height);
  8943. // draw text
  8944. ctx.fillStyle = this.fontColor || "black";
  8945. ctx.textAlign = "left";
  8946. ctx.textBaseline = "top";
  8947. ctx.fillText(text, left, top);
  8948. }
  8949. };
  8950. /**
  8951. * Redraw a edge as a dashed line
  8952. * Draw this edge in the given canvas
  8953. * @author David Jordan
  8954. * @date 2012-08-08
  8955. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8956. * @param {CanvasRenderingContext2D} ctx
  8957. * @private
  8958. */
  8959. Edge.prototype._drawDashLine = function(ctx) {
  8960. // set style
  8961. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8962. else {ctx.strokeStyle = this.color.color;}
  8963. ctx.lineWidth = this._getLineWidth();
  8964. // only firefox and chrome support this method, else we use the legacy one.
  8965. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  8966. ctx.beginPath();
  8967. ctx.moveTo(this.from.x, this.from.y);
  8968. // configure the dash pattern
  8969. var pattern = [0];
  8970. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  8971. pattern = [this.dash.length,this.dash.gap];
  8972. }
  8973. else {
  8974. pattern = [5,5];
  8975. }
  8976. // set dash settings for chrome or firefox
  8977. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  8978. ctx.setLineDash(pattern);
  8979. ctx.lineDashOffset = 0;
  8980. } else { //Firefox
  8981. ctx.mozDash = pattern;
  8982. ctx.mozDashOffset = 0;
  8983. }
  8984. // draw the line
  8985. if (this.smooth == true) {
  8986. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8987. }
  8988. else {
  8989. ctx.lineTo(this.to.x, this.to.y);
  8990. }
  8991. ctx.stroke();
  8992. // restore the dash settings.
  8993. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  8994. ctx.setLineDash([0]);
  8995. ctx.lineDashOffset = 0;
  8996. } else { //Firefox
  8997. ctx.mozDash = [0];
  8998. ctx.mozDashOffset = 0;
  8999. }
  9000. }
  9001. else { // unsupporting smooth lines
  9002. // draw dashed line
  9003. ctx.beginPath();
  9004. ctx.lineCap = 'round';
  9005. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9006. {
  9007. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9008. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9009. }
  9010. 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
  9011. {
  9012. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9013. [this.dash.length,this.dash.gap]);
  9014. }
  9015. else //If all else fails draw a line
  9016. {
  9017. ctx.moveTo(this.from.x, this.from.y);
  9018. ctx.lineTo(this.to.x, this.to.y);
  9019. }
  9020. ctx.stroke();
  9021. }
  9022. // draw label
  9023. if (this.label) {
  9024. var point;
  9025. if (this.smooth == true) {
  9026. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9027. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9028. point = {x:midpointX, y:midpointY};
  9029. }
  9030. else {
  9031. point = this._pointOnLine(0.5);
  9032. }
  9033. this._label(ctx, this.label, point.x, point.y);
  9034. }
  9035. };
  9036. /**
  9037. * Get a point on a line
  9038. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9039. * @return {Object} point
  9040. * @private
  9041. */
  9042. Edge.prototype._pointOnLine = function (percentage) {
  9043. return {
  9044. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9045. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9046. }
  9047. };
  9048. /**
  9049. * Get a point on a circle
  9050. * @param {Number} x
  9051. * @param {Number} y
  9052. * @param {Number} radius
  9053. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9054. * @return {Object} point
  9055. * @private
  9056. */
  9057. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9058. var angle = (percentage - 3/8) * 2 * Math.PI;
  9059. return {
  9060. x: x + radius * Math.cos(angle),
  9061. y: y - radius * Math.sin(angle)
  9062. }
  9063. };
  9064. /**
  9065. * Redraw a edge as a line with an arrow halfway the line
  9066. * Draw this edge in the given canvas
  9067. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9068. * @param {CanvasRenderingContext2D} ctx
  9069. * @private
  9070. */
  9071. Edge.prototype._drawArrowCenter = function(ctx) {
  9072. var point;
  9073. // set style
  9074. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9075. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9076. ctx.lineWidth = this._getLineWidth();
  9077. if (this.from != this.to) {
  9078. // draw line
  9079. this._line(ctx);
  9080. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9081. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9082. // draw an arrow halfway the line
  9083. if (this.smooth == true) {
  9084. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9085. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9086. point = {x:midpointX, y:midpointY};
  9087. }
  9088. else {
  9089. point = this._pointOnLine(0.5);
  9090. }
  9091. ctx.arrow(point.x, point.y, angle, length);
  9092. ctx.fill();
  9093. ctx.stroke();
  9094. // draw label
  9095. if (this.label) {
  9096. this._label(ctx, this.label, point.x, point.y);
  9097. }
  9098. }
  9099. else {
  9100. // draw circle
  9101. var x, y;
  9102. var radius = 0.25 * Math.max(100,this.length);
  9103. var node = this.from;
  9104. if (!node.width) {
  9105. node.resize(ctx);
  9106. }
  9107. if (node.width > node.height) {
  9108. x = node.x + node.width * 0.5;
  9109. y = node.y - radius;
  9110. }
  9111. else {
  9112. x = node.x + radius;
  9113. y = node.y - node.height * 0.5;
  9114. }
  9115. this._circle(ctx, x, y, radius);
  9116. // draw all arrows
  9117. var angle = 0.2 * Math.PI;
  9118. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9119. point = this._pointOnCircle(x, y, radius, 0.5);
  9120. ctx.arrow(point.x, point.y, angle, length);
  9121. ctx.fill();
  9122. ctx.stroke();
  9123. // draw label
  9124. if (this.label) {
  9125. point = this._pointOnCircle(x, y, radius, 0.5);
  9126. this._label(ctx, this.label, point.x, point.y);
  9127. }
  9128. }
  9129. };
  9130. /**
  9131. * Redraw a edge as a line with an arrow
  9132. * Draw this edge in the given canvas
  9133. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9134. * @param {CanvasRenderingContext2D} ctx
  9135. * @private
  9136. */
  9137. Edge.prototype._drawArrow = function(ctx) {
  9138. // set style
  9139. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9140. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9141. ctx.lineWidth = this._getLineWidth();
  9142. var angle, length;
  9143. //draw a line
  9144. if (this.from != this.to) {
  9145. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9146. var dx = (this.to.x - this.from.x);
  9147. var dy = (this.to.y - this.from.y);
  9148. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9149. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9150. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9151. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9152. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9153. if (this.smooth == true) {
  9154. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9155. dx = (this.to.x - this.via.x);
  9156. dy = (this.to.y - this.via.y);
  9157. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9158. }
  9159. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9160. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9161. var xTo,yTo;
  9162. if (this.smooth == true) {
  9163. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9164. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9165. }
  9166. else {
  9167. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9168. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9169. }
  9170. ctx.beginPath();
  9171. ctx.moveTo(xFrom,yFrom);
  9172. if (this.smooth == true) {
  9173. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9174. }
  9175. else {
  9176. ctx.lineTo(xTo, yTo);
  9177. }
  9178. ctx.stroke();
  9179. // draw arrow at the end of the line
  9180. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9181. ctx.arrow(xTo, yTo, angle, length);
  9182. ctx.fill();
  9183. ctx.stroke();
  9184. // draw label
  9185. if (this.label) {
  9186. var point;
  9187. if (this.smooth == true) {
  9188. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9189. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9190. point = {x:midpointX, y:midpointY};
  9191. }
  9192. else {
  9193. point = this._pointOnLine(0.5);
  9194. }
  9195. this._label(ctx, this.label, point.x, point.y);
  9196. }
  9197. }
  9198. else {
  9199. // draw circle
  9200. var node = this.from;
  9201. var x, y, arrow;
  9202. var radius = 0.25 * Math.max(100,this.length);
  9203. if (!node.width) {
  9204. node.resize(ctx);
  9205. }
  9206. if (node.width > node.height) {
  9207. x = node.x + node.width * 0.5;
  9208. y = node.y - radius;
  9209. arrow = {
  9210. x: x,
  9211. y: node.y,
  9212. angle: 0.9 * Math.PI
  9213. };
  9214. }
  9215. else {
  9216. x = node.x + radius;
  9217. y = node.y - node.height * 0.5;
  9218. arrow = {
  9219. x: node.x,
  9220. y: y,
  9221. angle: 0.6 * Math.PI
  9222. };
  9223. }
  9224. ctx.beginPath();
  9225. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9226. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9227. ctx.stroke();
  9228. // draw all arrows
  9229. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9230. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9231. ctx.fill();
  9232. ctx.stroke();
  9233. // draw label
  9234. if (this.label) {
  9235. point = this._pointOnCircle(x, y, radius, 0.5);
  9236. this._label(ctx, this.label, point.x, point.y);
  9237. }
  9238. }
  9239. };
  9240. /**
  9241. * Calculate the distance between a point (x3,y3) and a line segment from
  9242. * (x1,y1) to (x2,y2).
  9243. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9244. * @param {number} x1
  9245. * @param {number} y1
  9246. * @param {number} x2
  9247. * @param {number} y2
  9248. * @param {number} x3
  9249. * @param {number} y3
  9250. * @private
  9251. */
  9252. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9253. if (this.smooth == true) {
  9254. var minDistance = 1e9;
  9255. var i,t,x,y,dx,dy;
  9256. for (i = 0; i < 10; i++) {
  9257. t = 0.1*i;
  9258. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9259. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9260. dx = Math.abs(x3-x);
  9261. dy = Math.abs(y3-y);
  9262. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9263. }
  9264. return minDistance
  9265. }
  9266. else {
  9267. var px = x2-x1,
  9268. py = y2-y1,
  9269. something = px*px + py*py,
  9270. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9271. if (u > 1) {
  9272. u = 1;
  9273. }
  9274. else if (u < 0) {
  9275. u = 0;
  9276. }
  9277. var x = x1 + u * px,
  9278. y = y1 + u * py,
  9279. dx = x - x3,
  9280. dy = y - y3;
  9281. //# Note: If the actual distance does not matter,
  9282. //# if you only want to compare what this function
  9283. //# returns to other results of this function, you
  9284. //# can just return the squared distance instead
  9285. //# (i.e. remove the sqrt) to gain a little performance
  9286. return Math.sqrt(dx*dx + dy*dy);
  9287. }
  9288. };
  9289. /**
  9290. * This allows the zoom level of the graph to influence the rendering
  9291. *
  9292. * @param scale
  9293. */
  9294. Edge.prototype.setScale = function(scale) {
  9295. this.graphScaleInv = 1.0/scale;
  9296. };
  9297. Edge.prototype.select = function() {
  9298. this.selected = true;
  9299. };
  9300. Edge.prototype.unselect = function() {
  9301. this.selected = false;
  9302. };
  9303. Edge.prototype.positionBezierNode = function() {
  9304. if (this.via !== null) {
  9305. this.via.x = 0.5 * (this.from.x + this.to.x);
  9306. this.via.y = 0.5 * (this.from.y + this.to.y);
  9307. }
  9308. };
  9309. /**
  9310. * Popup is a class to create a popup window with some text
  9311. * @param {Element} container The container object.
  9312. * @param {Number} [x]
  9313. * @param {Number} [y]
  9314. * @param {String} [text]
  9315. * @param {Object} [style] An object containing borderColor,
  9316. * backgroundColor, etc.
  9317. */
  9318. function Popup(container, x, y, text, style) {
  9319. if (container) {
  9320. this.container = container;
  9321. }
  9322. else {
  9323. this.container = document.body;
  9324. }
  9325. // x, y and text are optional, see if a style object was passed in their place
  9326. if (style === undefined) {
  9327. if (typeof x === "object") {
  9328. style = x;
  9329. x = undefined;
  9330. } else if (typeof text === "object") {
  9331. style = text;
  9332. text = undefined;
  9333. } else {
  9334. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9335. style = {
  9336. fontColor: 'black',
  9337. fontSize: 14, // px
  9338. fontFace: 'verdana',
  9339. color: {
  9340. border: '#666',
  9341. background: '#FFFFC6'
  9342. }
  9343. }
  9344. }
  9345. }
  9346. this.x = 0;
  9347. this.y = 0;
  9348. this.padding = 5;
  9349. if (x !== undefined && y !== undefined ) {
  9350. this.setPosition(x, y);
  9351. }
  9352. if (text !== undefined) {
  9353. this.setText(text);
  9354. }
  9355. // create the frame
  9356. this.frame = document.createElement("div");
  9357. var styleAttr = this.frame.style;
  9358. styleAttr.position = "absolute";
  9359. styleAttr.visibility = "hidden";
  9360. styleAttr.border = "1px solid " + style.color.border;
  9361. styleAttr.color = style.fontColor;
  9362. styleAttr.fontSize = style.fontSize + "px";
  9363. styleAttr.fontFamily = style.fontFace;
  9364. styleAttr.padding = this.padding + "px";
  9365. styleAttr.backgroundColor = style.color.background;
  9366. styleAttr.borderRadius = "3px";
  9367. styleAttr.MozBorderRadius = "3px";
  9368. styleAttr.WebkitBorderRadius = "3px";
  9369. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9370. styleAttr.whiteSpace = "nowrap";
  9371. this.container.appendChild(this.frame);
  9372. }
  9373. /**
  9374. * @param {number} x Horizontal position of the popup window
  9375. * @param {number} y Vertical position of the popup window
  9376. */
  9377. Popup.prototype.setPosition = function(x, y) {
  9378. this.x = parseInt(x);
  9379. this.y = parseInt(y);
  9380. };
  9381. /**
  9382. * Set the text for the popup window. This can be HTML code
  9383. * @param {string} text
  9384. */
  9385. Popup.prototype.setText = function(text) {
  9386. this.frame.innerHTML = text;
  9387. };
  9388. /**
  9389. * Show the popup window
  9390. * @param {boolean} show Optional. Show or hide the window
  9391. */
  9392. Popup.prototype.show = function (show) {
  9393. if (show === undefined) {
  9394. show = true;
  9395. }
  9396. if (show) {
  9397. var height = this.frame.clientHeight;
  9398. var width = this.frame.clientWidth;
  9399. var maxHeight = this.frame.parentNode.clientHeight;
  9400. var maxWidth = this.frame.parentNode.clientWidth;
  9401. var top = (this.y - height);
  9402. if (top + height + this.padding > maxHeight) {
  9403. top = maxHeight - height - this.padding;
  9404. }
  9405. if (top < this.padding) {
  9406. top = this.padding;
  9407. }
  9408. var left = this.x;
  9409. if (left + width + this.padding > maxWidth) {
  9410. left = maxWidth - width - this.padding;
  9411. }
  9412. if (left < this.padding) {
  9413. left = this.padding;
  9414. }
  9415. this.frame.style.left = left + "px";
  9416. this.frame.style.top = top + "px";
  9417. this.frame.style.visibility = "visible";
  9418. }
  9419. else {
  9420. this.hide();
  9421. }
  9422. };
  9423. /**
  9424. * Hide the popup window
  9425. */
  9426. Popup.prototype.hide = function () {
  9427. this.frame.style.visibility = "hidden";
  9428. };
  9429. /**
  9430. * @class Groups
  9431. * This class can store groups and properties specific for groups.
  9432. */
  9433. function Groups() {
  9434. this.clear();
  9435. this.defaultIndex = 0;
  9436. }
  9437. /**
  9438. * default constants for group colors
  9439. */
  9440. Groups.DEFAULT = [
  9441. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9442. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9443. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9444. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9445. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9446. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9447. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9448. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9449. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9450. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9451. ];
  9452. /**
  9453. * Clear all groups
  9454. */
  9455. Groups.prototype.clear = function () {
  9456. this.groups = {};
  9457. this.groups.length = function()
  9458. {
  9459. var i = 0;
  9460. for ( var p in this ) {
  9461. if (this.hasOwnProperty(p)) {
  9462. i++;
  9463. }
  9464. }
  9465. return i;
  9466. }
  9467. };
  9468. /**
  9469. * get group properties of a groupname. If groupname is not found, a new group
  9470. * is added.
  9471. * @param {*} groupname Can be a number, string, Date, etc.
  9472. * @return {Object} group The created group, containing all group properties
  9473. */
  9474. Groups.prototype.get = function (groupname) {
  9475. var group = this.groups[groupname];
  9476. if (group == undefined) {
  9477. // create new group
  9478. var index = this.defaultIndex % Groups.DEFAULT.length;
  9479. this.defaultIndex++;
  9480. group = {};
  9481. group.color = Groups.DEFAULT[index];
  9482. this.groups[groupname] = group;
  9483. }
  9484. return group;
  9485. };
  9486. /**
  9487. * Add a custom group style
  9488. * @param {String} groupname
  9489. * @param {Object} style An object containing borderColor,
  9490. * backgroundColor, etc.
  9491. * @return {Object} group The created group object
  9492. */
  9493. Groups.prototype.add = function (groupname, style) {
  9494. this.groups[groupname] = style;
  9495. if (style.color) {
  9496. style.color = util.parseColor(style.color);
  9497. }
  9498. return style;
  9499. };
  9500. /**
  9501. * @class Images
  9502. * This class loads images and keeps them stored.
  9503. */
  9504. function Images() {
  9505. this.images = {};
  9506. this.callback = undefined;
  9507. }
  9508. /**
  9509. * Set an onload callback function. This will be called each time an image
  9510. * is loaded
  9511. * @param {function} callback
  9512. */
  9513. Images.prototype.setOnloadCallback = function(callback) {
  9514. this.callback = callback;
  9515. };
  9516. /**
  9517. *
  9518. * @param {string} url Url of the image
  9519. * @return {Image} img The image object
  9520. */
  9521. Images.prototype.load = function(url) {
  9522. var img = this.images[url];
  9523. if (img == undefined) {
  9524. // create the image
  9525. var images = this;
  9526. img = new Image();
  9527. this.images[url] = img;
  9528. img.onload = function() {
  9529. if (images.callback) {
  9530. images.callback(this);
  9531. }
  9532. };
  9533. img.src = url;
  9534. }
  9535. return img;
  9536. };
  9537. /**
  9538. * Created by Alex on 2/6/14.
  9539. */
  9540. var physicsMixin = {
  9541. /**
  9542. * Toggling barnes Hut calculation on and off.
  9543. *
  9544. * @private
  9545. */
  9546. _toggleBarnesHut: function () {
  9547. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9548. this._loadSelectedForceSolver();
  9549. this.moving = true;
  9550. this.start();
  9551. },
  9552. /**
  9553. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9554. *
  9555. * @private
  9556. */
  9557. _loadSelectedForceSolver: function () {
  9558. // this overloads the this._calculateNodeForces
  9559. if (this.constants.physics.barnesHut.enabled == true) {
  9560. this._clearMixin(repulsionMixin);
  9561. this._clearMixin(hierarchalRepulsionMixin);
  9562. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9563. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9564. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9565. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9566. this._loadMixin(barnesHutMixin);
  9567. }
  9568. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9569. this._clearMixin(barnesHutMixin);
  9570. this._clearMixin(repulsionMixin);
  9571. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9572. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9573. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9574. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9575. this._loadMixin(hierarchalRepulsionMixin);
  9576. }
  9577. else {
  9578. this._clearMixin(barnesHutMixin);
  9579. this._clearMixin(hierarchalRepulsionMixin);
  9580. this.barnesHutTree = undefined;
  9581. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9582. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9583. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9584. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9585. this._loadMixin(repulsionMixin);
  9586. }
  9587. },
  9588. /**
  9589. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9590. * if there is more than one node. If it is just one node, we dont calculate anything.
  9591. *
  9592. * @private
  9593. */
  9594. _initializeForceCalculation: function () {
  9595. // stop calculation if there is only one node
  9596. if (this.nodeIndices.length == 1) {
  9597. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9598. }
  9599. else {
  9600. // if there are too many nodes on screen, we cluster without repositioning
  9601. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9602. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9603. }
  9604. // we now start the force calculation
  9605. this._calculateForces();
  9606. }
  9607. },
  9608. /**
  9609. * Calculate the external forces acting on the nodes
  9610. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9611. * @private
  9612. */
  9613. _calculateForces: function () {
  9614. // Gravity is required to keep separated groups from floating off
  9615. // the forces are reset to zero in this loop by using _setForce instead
  9616. // of _addForce
  9617. this._calculateGravitationalForces();
  9618. this._calculateNodeForces();
  9619. if (this.constants.smoothCurves == true) {
  9620. this._calculateSpringForcesWithSupport();
  9621. }
  9622. else {
  9623. this._calculateSpringForces();
  9624. }
  9625. },
  9626. /**
  9627. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9628. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9629. * This function joins the datanodes and invisible (called support) nodes into one object.
  9630. * We do this so we do not contaminate this.nodes with the support nodes.
  9631. *
  9632. * @private
  9633. */
  9634. _updateCalculationNodes: function () {
  9635. if (this.constants.smoothCurves == true) {
  9636. this.calculationNodes = {};
  9637. this.calculationNodeIndices = [];
  9638. for (var nodeId in this.nodes) {
  9639. if (this.nodes.hasOwnProperty(nodeId)) {
  9640. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9641. }
  9642. }
  9643. var supportNodes = this.sectors['support']['nodes'];
  9644. for (var supportNodeId in supportNodes) {
  9645. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9646. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9647. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9648. }
  9649. else {
  9650. supportNodes[supportNodeId]._setForce(0, 0);
  9651. }
  9652. }
  9653. }
  9654. for (var idx in this.calculationNodes) {
  9655. if (this.calculationNodes.hasOwnProperty(idx)) {
  9656. this.calculationNodeIndices.push(idx);
  9657. }
  9658. }
  9659. }
  9660. else {
  9661. this.calculationNodes = this.nodes;
  9662. this.calculationNodeIndices = this.nodeIndices;
  9663. }
  9664. },
  9665. /**
  9666. * this function applies the central gravity effect to keep groups from floating off
  9667. *
  9668. * @private
  9669. */
  9670. _calculateGravitationalForces: function () {
  9671. var dx, dy, distance, node, i;
  9672. var nodes = this.calculationNodes;
  9673. var gravity = this.constants.physics.centralGravity;
  9674. var gravityForce = 0;
  9675. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9676. node = nodes[this.calculationNodeIndices[i]];
  9677. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9678. // gravity does not apply when we are in a pocket sector
  9679. if (this._sector() == "default" && gravity != 0) {
  9680. dx = -node.x;
  9681. dy = -node.y;
  9682. distance = Math.sqrt(dx * dx + dy * dy);
  9683. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9684. node.fx = dx * gravityForce;
  9685. node.fy = dy * gravityForce;
  9686. }
  9687. else {
  9688. node.fx = 0;
  9689. node.fy = 0;
  9690. }
  9691. }
  9692. },
  9693. /**
  9694. * this function calculates the effects of the springs in the case of unsmooth curves.
  9695. *
  9696. * @private
  9697. */
  9698. _calculateSpringForces: function () {
  9699. var edgeLength, edge, edgeId;
  9700. var dx, dy, fx, fy, springForce, length;
  9701. var edges = this.edges;
  9702. // forces caused by the edges, modelled as springs
  9703. for (edgeId in edges) {
  9704. if (edges.hasOwnProperty(edgeId)) {
  9705. edge = edges[edgeId];
  9706. if (edge.connected) {
  9707. // only calculate forces if nodes are in the same sector
  9708. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9709. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9710. // this implies that the edges between big clusters are longer
  9711. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9712. dx = (edge.from.x - edge.to.x);
  9713. dy = (edge.from.y - edge.to.y);
  9714. length = Math.sqrt(dx * dx + dy * dy);
  9715. if (length == 0) {
  9716. length = 0.01;
  9717. }
  9718. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9719. fx = dx * springForce;
  9720. fy = dy * springForce;
  9721. edge.from.fx += fx;
  9722. edge.from.fy += fy;
  9723. edge.to.fx -= fx;
  9724. edge.to.fy -= fy;
  9725. }
  9726. }
  9727. }
  9728. }
  9729. },
  9730. /**
  9731. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9732. *
  9733. * @private
  9734. */
  9735. _calculateSpringForcesWithSupport: function () {
  9736. var edgeLength, edge, edgeId, combinedClusterSize;
  9737. var edges = this.edges;
  9738. // forces caused by the edges, modelled as springs
  9739. for (edgeId in edges) {
  9740. if (edges.hasOwnProperty(edgeId)) {
  9741. edge = edges[edgeId];
  9742. if (edge.connected) {
  9743. // only calculate forces if nodes are in the same sector
  9744. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9745. if (edge.via != null) {
  9746. var node1 = edge.to;
  9747. var node2 = edge.via;
  9748. var node3 = edge.from;
  9749. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9750. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9751. // this implies that the edges between big clusters are longer
  9752. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9753. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9754. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9755. }
  9756. }
  9757. }
  9758. }
  9759. }
  9760. },
  9761. /**
  9762. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9763. *
  9764. * @param node1
  9765. * @param node2
  9766. * @param edgeLength
  9767. * @private
  9768. */
  9769. _calculateSpringForce: function (node1, node2, edgeLength) {
  9770. var dx, dy, fx, fy, springForce, length;
  9771. dx = (node1.x - node2.x);
  9772. dy = (node1.y - node2.y);
  9773. length = Math.sqrt(dx * dx + dy * dy);
  9774. if (length == 0) {
  9775. length = 0.01;
  9776. }
  9777. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9778. fx = dx * springForce;
  9779. fy = dy * springForce;
  9780. node1.fx += fx;
  9781. node1.fy += fy;
  9782. node2.fx -= fx;
  9783. node2.fy -= fy;
  9784. },
  9785. /**
  9786. * Load the HTML for the physics config and bind it
  9787. * @private
  9788. */
  9789. _loadPhysicsConfiguration: function () {
  9790. if (this.physicsConfiguration === undefined) {
  9791. this.backupConstants = {};
  9792. util.copyObject(this.constants, this.backupConstants);
  9793. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  9794. this.physicsConfiguration = document.createElement('div');
  9795. this.physicsConfiguration.className = "PhysicsConfiguration";
  9796. this.physicsConfiguration.innerHTML = '' +
  9797. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9798. '<tr>' +
  9799. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9800. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  9801. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9802. '</tr>' +
  9803. '</table>' +
  9804. '<table id="graph_BH_table" style="display:none">' +
  9805. '<tr><td><b>Barnes Hut</b></td></tr>' +
  9806. '<tr>' +
  9807. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' +
  9808. '</tr>' +
  9809. '<tr>' +
  9810. '<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>' +
  9811. '</tr>' +
  9812. '<tr>' +
  9813. '<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>' +
  9814. '</tr>' +
  9815. '<tr>' +
  9816. '<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>' +
  9817. '</tr>' +
  9818. '<tr>' +
  9819. '<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>' +
  9820. '</tr>' +
  9821. '</table>' +
  9822. '<table id="graph_R_table" style="display:none">' +
  9823. '<tr><td><b>Repulsion</b></td></tr>' +
  9824. '<tr>' +
  9825. '<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>' +
  9826. '</tr>' +
  9827. '<tr>' +
  9828. '<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>' +
  9829. '</tr>' +
  9830. '<tr>' +
  9831. '<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>' +
  9832. '</tr>' +
  9833. '<tr>' +
  9834. '<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>' +
  9835. '</tr>' +
  9836. '<tr>' +
  9837. '<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>' +
  9838. '</tr>' +
  9839. '</table>' +
  9840. '<table id="graph_H_table" style="display:none">' +
  9841. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  9842. '<tr>' +
  9843. '<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>' +
  9844. '</tr>' +
  9845. '<tr>' +
  9846. '<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>' +
  9847. '</tr>' +
  9848. '<tr>' +
  9849. '<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>' +
  9850. '</tr>' +
  9851. '<tr>' +
  9852. '<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>' +
  9853. '</tr>' +
  9854. '<tr>' +
  9855. '<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>' +
  9856. '</tr>' +
  9857. '<tr>' +
  9858. '<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>' +
  9859. '</tr>' +
  9860. '<tr>' +
  9861. '<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>' +
  9862. '</tr>' +
  9863. '<tr>' +
  9864. '<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>' +
  9865. '</tr>' +
  9866. '</table>' +
  9867. '<table><tr><td><b>Options:</b></td></tr>' +
  9868. '<tr>' +
  9869. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9870. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  9871. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  9872. '</tr>' +
  9873. '</table>'
  9874. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  9875. this.optionsDiv = document.createElement("div");
  9876. this.optionsDiv.style.fontSize = "14px";
  9877. this.optionsDiv.style.fontFamily = "verdana";
  9878. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  9879. var rangeElement;
  9880. rangeElement = document.getElementById('graph_BH_gc');
  9881. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  9882. rangeElement = document.getElementById('graph_BH_cg');
  9883. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  9884. rangeElement = document.getElementById('graph_BH_sc');
  9885. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  9886. rangeElement = document.getElementById('graph_BH_sl');
  9887. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  9888. rangeElement = document.getElementById('graph_BH_damp');
  9889. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  9890. rangeElement = document.getElementById('graph_R_nd');
  9891. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  9892. rangeElement = document.getElementById('graph_R_cg');
  9893. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  9894. rangeElement = document.getElementById('graph_R_sc');
  9895. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  9896. rangeElement = document.getElementById('graph_R_sl');
  9897. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  9898. rangeElement = document.getElementById('graph_R_damp');
  9899. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  9900. rangeElement = document.getElementById('graph_H_nd');
  9901. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  9902. rangeElement = document.getElementById('graph_H_cg');
  9903. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  9904. rangeElement = document.getElementById('graph_H_sc');
  9905. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  9906. rangeElement = document.getElementById('graph_H_sl');
  9907. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  9908. rangeElement = document.getElementById('graph_H_damp');
  9909. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  9910. rangeElement = document.getElementById('graph_H_direction');
  9911. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  9912. rangeElement = document.getElementById('graph_H_levsep');
  9913. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  9914. rangeElement = document.getElementById('graph_H_nspac');
  9915. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  9916. var radioButton1 = document.getElementById("graph_physicsMethod1");
  9917. var radioButton2 = document.getElementById("graph_physicsMethod2");
  9918. var radioButton3 = document.getElementById("graph_physicsMethod3");
  9919. radioButton2.checked = true;
  9920. if (this.constants.physics.barnesHut.enabled) {
  9921. radioButton1.checked = true;
  9922. }
  9923. if (this.constants.hierarchicalLayout.enabled) {
  9924. radioButton3.checked = true;
  9925. }
  9926. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9927. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  9928. var graph_generateOptions = document.getElementById("graph_generateOptions");
  9929. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  9930. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  9931. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  9932. if (this.constants.smoothCurves == true) {
  9933. graph_toggleSmooth.style.background = "#A4FF56";
  9934. }
  9935. else {
  9936. graph_toggleSmooth.style.background = "#FF8532";
  9937. }
  9938. switchConfigurations.apply(this);
  9939. radioButton1.onchange = switchConfigurations.bind(this);
  9940. radioButton2.onchange = switchConfigurations.bind(this);
  9941. radioButton3.onchange = switchConfigurations.bind(this);
  9942. }
  9943. },
  9944. /**
  9945. * This overwrites the this.constants.
  9946. *
  9947. * @param constantsVariableName
  9948. * @param value
  9949. * @private
  9950. */
  9951. _overWriteGraphConstants: function (constantsVariableName, value) {
  9952. var nameArray = constantsVariableName.split("_");
  9953. if (nameArray.length == 1) {
  9954. this.constants[nameArray[0]] = value;
  9955. }
  9956. else if (nameArray.length == 2) {
  9957. this.constants[nameArray[0]][nameArray[1]] = value;
  9958. }
  9959. else if (nameArray.length == 3) {
  9960. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  9961. }
  9962. }
  9963. };
  9964. /**
  9965. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  9966. */
  9967. function graphToggleSmoothCurves () {
  9968. this.constants.smoothCurves = !this.constants.smoothCurves;
  9969. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9970. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  9971. else {graph_toggleSmooth.style.background = "#FF8532";}
  9972. this._configureSmoothCurves(false);
  9973. };
  9974. /**
  9975. * this function is used to scramble the nodes
  9976. *
  9977. */
  9978. function graphRepositionNodes () {
  9979. for (var nodeId in this.calculationNodes) {
  9980. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  9981. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  9982. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  9983. }
  9984. }
  9985. if (this.constants.hierarchicalLayout.enabled == true) {
  9986. this._setupHierarchicalLayout();
  9987. }
  9988. else {
  9989. this.repositionNodes();
  9990. }
  9991. this.moving = true;
  9992. this.start();
  9993. };
  9994. /**
  9995. * this is used to generate an options file from the playing with physics system.
  9996. */
  9997. function graphGenerateOptions () {
  9998. var options = "No options are required, default values used.";
  9999. var optionsSpecific = [];
  10000. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10001. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10002. if (radioButton1.checked == true) {
  10003. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10004. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10005. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10006. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10007. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10008. if (optionsSpecific.length != 0) {
  10009. options = "var options = {";
  10010. options += "physics: {barnesHut: {";
  10011. for (var i = 0; i < optionsSpecific.length; i++) {
  10012. options += optionsSpecific[i];
  10013. if (i < optionsSpecific.length - 1) {
  10014. options += ", "
  10015. }
  10016. }
  10017. options += '}}'
  10018. }
  10019. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10020. if (optionsSpecific.length == 0) {options = "var options = {";}
  10021. else {options += ", "}
  10022. options += "smoothCurves: " + this.constants.smoothCurves;
  10023. }
  10024. if (options != "No options are required, default values used.") {
  10025. options += '};'
  10026. }
  10027. }
  10028. else if (radioButton2.checked == true) {
  10029. options = "var options = {";
  10030. options += "physics: {barnesHut: {enabled: false}";
  10031. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10032. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10033. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10034. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10035. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10036. if (optionsSpecific.length != 0) {
  10037. options += ", repulsion: {";
  10038. for (var i = 0; i < optionsSpecific.length; i++) {
  10039. options += optionsSpecific[i];
  10040. if (i < optionsSpecific.length - 1) {
  10041. options += ", "
  10042. }
  10043. }
  10044. options += '}}'
  10045. }
  10046. if (optionsSpecific.length == 0) {options += "}"}
  10047. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10048. options += ", smoothCurves: " + this.constants.smoothCurves;
  10049. }
  10050. options += '};'
  10051. }
  10052. else {
  10053. options = "var options = {";
  10054. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10055. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10056. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10057. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10058. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10059. if (optionsSpecific.length != 0) {
  10060. options += "physics: {hierarchicalRepulsion: {";
  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. options += 'hierarchicalLayout: {';
  10070. optionsSpecific = [];
  10071. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10072. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10073. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10074. if (optionsSpecific.length != 0) {
  10075. for (var i = 0; i < optionsSpecific.length; i++) {
  10076. options += optionsSpecific[i];
  10077. if (i < optionsSpecific.length - 1) {
  10078. options += ", "
  10079. }
  10080. }
  10081. options += '}'
  10082. }
  10083. else {
  10084. options += "enabled:true}";
  10085. }
  10086. options += '};'
  10087. }
  10088. this.optionsDiv.innerHTML = options;
  10089. };
  10090. /**
  10091. * this is used to switch between barnesHut, repulsion and hierarchical.
  10092. *
  10093. */
  10094. function switchConfigurations () {
  10095. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10096. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10097. var tableId = "graph_" + radioButton + "_table";
  10098. var table = document.getElementById(tableId);
  10099. table.style.display = "block";
  10100. for (var i = 0; i < ids.length; i++) {
  10101. if (ids[i] != tableId) {
  10102. table = document.getElementById(ids[i]);
  10103. table.style.display = "none";
  10104. }
  10105. }
  10106. this._restoreNodes();
  10107. if (radioButton == "R") {
  10108. this.constants.hierarchicalLayout.enabled = false;
  10109. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10110. this.constants.physics.barnesHut.enabled = false;
  10111. }
  10112. else if (radioButton == "H") {
  10113. if (this.constants.hierarchicalLayout.enabled == false) {
  10114. this.constants.hierarchicalLayout.enabled = true;
  10115. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10116. this.constants.physics.barnesHut.enabled = false;
  10117. this._setupHierarchicalLayout();
  10118. }
  10119. }
  10120. else {
  10121. this.constants.hierarchicalLayout.enabled = false;
  10122. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10123. this.constants.physics.barnesHut.enabled = true;
  10124. }
  10125. this._loadSelectedForceSolver();
  10126. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10127. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10128. else {graph_toggleSmooth.style.background = "#FF8532";}
  10129. this.moving = true;
  10130. this.start();
  10131. }
  10132. /**
  10133. * this generates the ranges depending on the iniital values.
  10134. *
  10135. * @param id
  10136. * @param map
  10137. * @param constantsVariableName
  10138. */
  10139. function showValueOfRange (id,map,constantsVariableName) {
  10140. var valueId = id + "_value";
  10141. var rangeValue = document.getElementById(id).value;
  10142. if (map instanceof Array) {
  10143. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10144. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10145. }
  10146. else {
  10147. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10148. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10149. }
  10150. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10151. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10152. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10153. this._setupHierarchicalLayout();
  10154. }
  10155. this.moving = true;
  10156. this.start();
  10157. };
  10158. /**
  10159. * Created by Alex on 2/10/14.
  10160. */
  10161. var hierarchalRepulsionMixin = {
  10162. /**
  10163. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10164. * This field is linearly approximated.
  10165. *
  10166. * @private
  10167. */
  10168. _calculateNodeForces: function () {
  10169. var dx, dy, distance, fx, fy, combinedClusterSize,
  10170. repulsingForce, node1, node2, i, j;
  10171. var nodes = this.calculationNodes;
  10172. var nodeIndices = this.calculationNodeIndices;
  10173. // approximation constants
  10174. var b = 5;
  10175. var a_base = 0.5 * -b;
  10176. // repulsing forces between nodes
  10177. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10178. var minimumDistance = nodeDistance;
  10179. // we loop from i over all but the last entree in the array
  10180. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10181. for (i = 0; i < nodeIndices.length - 1; i++) {
  10182. node1 = nodes[nodeIndices[i]];
  10183. for (j = i + 1; j < nodeIndices.length; j++) {
  10184. node2 = nodes[nodeIndices[j]];
  10185. dx = node2.x - node1.x;
  10186. dy = node2.y - node1.y;
  10187. distance = Math.sqrt(dx * dx + dy * dy);
  10188. var a = a_base / minimumDistance;
  10189. if (distance < 2 * minimumDistance) {
  10190. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10191. // normalize force with
  10192. if (distance == 0) {
  10193. distance = 0.01;
  10194. }
  10195. else {
  10196. repulsingForce = repulsingForce / distance;
  10197. }
  10198. fx = dx * repulsingForce;
  10199. fy = dy * repulsingForce;
  10200. node1.fx -= fx;
  10201. node1.fy -= fy;
  10202. node2.fx += fx;
  10203. node2.fy += fy;
  10204. }
  10205. }
  10206. }
  10207. }
  10208. };
  10209. /**
  10210. * Created by Alex on 2/10/14.
  10211. */
  10212. var barnesHutMixin = {
  10213. /**
  10214. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10215. * The Barnes Hut method is used to speed up this N-body simulation.
  10216. *
  10217. * @private
  10218. */
  10219. _calculateNodeForces : function() {
  10220. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10221. var node;
  10222. var nodes = this.calculationNodes;
  10223. var nodeIndices = this.calculationNodeIndices;
  10224. var nodeCount = nodeIndices.length;
  10225. this._formBarnesHutTree(nodes,nodeIndices);
  10226. var barnesHutTree = this.barnesHutTree;
  10227. // place the nodes one by one recursively
  10228. for (var i = 0; i < nodeCount; i++) {
  10229. node = nodes[nodeIndices[i]];
  10230. // starting with root is irrelevant, it never passes the BarnesHut condition
  10231. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10232. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10233. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10234. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10235. }
  10236. }
  10237. },
  10238. /**
  10239. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10240. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10241. *
  10242. * @param parentBranch
  10243. * @param node
  10244. * @private
  10245. */
  10246. _getForceContribution : function(parentBranch,node) {
  10247. // we get no force contribution from an empty region
  10248. if (parentBranch.childrenCount > 0) {
  10249. var dx,dy,distance;
  10250. // get the distance from the center of mass to the node.
  10251. dx = parentBranch.centerOfMass.x - node.x;
  10252. dy = parentBranch.centerOfMass.y - node.y;
  10253. distance = Math.sqrt(dx * dx + dy * dy);
  10254. // BarnesHut condition
  10255. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10256. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10257. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10258. // duplicate code to reduce function calls to speed up program
  10259. if (distance == 0) {
  10260. distance = 0.1*Math.random();
  10261. dx = distance;
  10262. }
  10263. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10264. var fx = dx * gravityForce;
  10265. var fy = dy * gravityForce;
  10266. node.fx += fx;
  10267. node.fy += fy;
  10268. }
  10269. else {
  10270. // Did not pass the condition, go into children if available
  10271. if (parentBranch.childrenCount == 4) {
  10272. this._getForceContribution(parentBranch.children.NW,node);
  10273. this._getForceContribution(parentBranch.children.NE,node);
  10274. this._getForceContribution(parentBranch.children.SW,node);
  10275. this._getForceContribution(parentBranch.children.SE,node);
  10276. }
  10277. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10278. if (parentBranch.children.data.id != node.id) { // if it is not self
  10279. // duplicate code to reduce function calls to speed up program
  10280. if (distance == 0) {
  10281. distance = 0.5*Math.random();
  10282. dx = distance;
  10283. }
  10284. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10285. var fx = dx * gravityForce;
  10286. var fy = dy * gravityForce;
  10287. node.fx += fx;
  10288. node.fy += fy;
  10289. }
  10290. }
  10291. }
  10292. }
  10293. },
  10294. /**
  10295. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10296. *
  10297. * @param nodes
  10298. * @param nodeIndices
  10299. * @private
  10300. */
  10301. _formBarnesHutTree : function(nodes,nodeIndices) {
  10302. var node;
  10303. var nodeCount = nodeIndices.length;
  10304. var minX = Number.MAX_VALUE,
  10305. minY = Number.MAX_VALUE,
  10306. maxX =-Number.MAX_VALUE,
  10307. maxY =-Number.MAX_VALUE;
  10308. // get the range of the nodes
  10309. for (var i = 0; i < nodeCount; i++) {
  10310. var x = nodes[nodeIndices[i]].x;
  10311. var y = nodes[nodeIndices[i]].y;
  10312. if (x < minX) { minX = x; }
  10313. if (x > maxX) { maxX = x; }
  10314. if (y < minY) { minY = y; }
  10315. if (y > maxY) { maxY = y; }
  10316. }
  10317. // make the range a square
  10318. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10319. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10320. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10321. var minimumTreeSize = 1e-5;
  10322. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10323. var halfRootSize = 0.5 * rootSize;
  10324. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10325. // construct the barnesHutTree
  10326. var barnesHutTree = {root:{
  10327. centerOfMass:{x:0,y:0}, // Center of Mass
  10328. mass:0,
  10329. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10330. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10331. size: rootSize,
  10332. calcSize: 1 / rootSize,
  10333. children: {data:null},
  10334. maxWidth: 0,
  10335. level: 0,
  10336. childrenCount: 4
  10337. }};
  10338. this._splitBranch(barnesHutTree.root);
  10339. // place the nodes one by one recursively
  10340. for (i = 0; i < nodeCount; i++) {
  10341. node = nodes[nodeIndices[i]];
  10342. this._placeInTree(barnesHutTree.root,node);
  10343. }
  10344. // make global
  10345. this.barnesHutTree = barnesHutTree
  10346. },
  10347. /**
  10348. * this updates the mass of a branch. this is increased by adding a node.
  10349. *
  10350. * @param parentBranch
  10351. * @param node
  10352. * @private
  10353. */
  10354. _updateBranchMass : function(parentBranch, node) {
  10355. var totalMass = parentBranch.mass + node.mass;
  10356. var totalMassInv = 1/totalMass;
  10357. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10358. parentBranch.centerOfMass.x *= totalMassInv;
  10359. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10360. parentBranch.centerOfMass.y *= totalMassInv;
  10361. parentBranch.mass = totalMass;
  10362. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10363. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10364. },
  10365. /**
  10366. * determine in which branch the node will be placed.
  10367. *
  10368. * @param parentBranch
  10369. * @param node
  10370. * @param skipMassUpdate
  10371. * @private
  10372. */
  10373. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10374. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10375. // update the mass of the branch.
  10376. this._updateBranchMass(parentBranch,node);
  10377. }
  10378. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10379. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10380. this._placeInRegion(parentBranch,node,"NW");
  10381. }
  10382. else { // in SW
  10383. this._placeInRegion(parentBranch,node,"SW");
  10384. }
  10385. }
  10386. else { // in NE or SE
  10387. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10388. this._placeInRegion(parentBranch,node,"NE");
  10389. }
  10390. else { // in SE
  10391. this._placeInRegion(parentBranch,node,"SE");
  10392. }
  10393. }
  10394. },
  10395. /**
  10396. * actually place the node in a region (or branch)
  10397. *
  10398. * @param parentBranch
  10399. * @param node
  10400. * @param region
  10401. * @private
  10402. */
  10403. _placeInRegion : function(parentBranch,node,region) {
  10404. switch (parentBranch.children[region].childrenCount) {
  10405. case 0: // place node here
  10406. parentBranch.children[region].children.data = node;
  10407. parentBranch.children[region].childrenCount = 1;
  10408. this._updateBranchMass(parentBranch.children[region],node);
  10409. break;
  10410. case 1: // convert into children
  10411. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10412. // we move one node a pixel and we do not put it in the tree.
  10413. if (parentBranch.children[region].children.data.x == node.x &&
  10414. parentBranch.children[region].children.data.y == node.y) {
  10415. node.x += Math.random();
  10416. node.y += Math.random();
  10417. }
  10418. else {
  10419. this._splitBranch(parentBranch.children[region]);
  10420. this._placeInTree(parentBranch.children[region],node);
  10421. }
  10422. break;
  10423. case 4: // place in branch
  10424. this._placeInTree(parentBranch.children[region],node);
  10425. break;
  10426. }
  10427. },
  10428. /**
  10429. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10430. * after the split is complete.
  10431. *
  10432. * @param parentBranch
  10433. * @private
  10434. */
  10435. _splitBranch : function(parentBranch) {
  10436. // if the branch is filled with a node, replace the node in the new subset.
  10437. var containedNode = null;
  10438. if (parentBranch.childrenCount == 1) {
  10439. containedNode = parentBranch.children.data;
  10440. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10441. }
  10442. parentBranch.childrenCount = 4;
  10443. parentBranch.children.data = null;
  10444. this._insertRegion(parentBranch,"NW");
  10445. this._insertRegion(parentBranch,"NE");
  10446. this._insertRegion(parentBranch,"SW");
  10447. this._insertRegion(parentBranch,"SE");
  10448. if (containedNode != null) {
  10449. this._placeInTree(parentBranch,containedNode);
  10450. }
  10451. },
  10452. /**
  10453. * This function subdivides the region into four new segments.
  10454. * Specifically, this inserts a single new segment.
  10455. * It fills the children section of the parentBranch
  10456. *
  10457. * @param parentBranch
  10458. * @param region
  10459. * @param parentRange
  10460. * @private
  10461. */
  10462. _insertRegion : function(parentBranch, region) {
  10463. var minX,maxX,minY,maxY;
  10464. var childSize = 0.5 * parentBranch.size;
  10465. switch (region) {
  10466. case "NW":
  10467. minX = parentBranch.range.minX;
  10468. maxX = parentBranch.range.minX + childSize;
  10469. minY = parentBranch.range.minY;
  10470. maxY = parentBranch.range.minY + childSize;
  10471. break;
  10472. case "NE":
  10473. minX = parentBranch.range.minX + childSize;
  10474. maxX = parentBranch.range.maxX;
  10475. minY = parentBranch.range.minY;
  10476. maxY = parentBranch.range.minY + childSize;
  10477. break;
  10478. case "SW":
  10479. minX = parentBranch.range.minX;
  10480. maxX = parentBranch.range.minX + childSize;
  10481. minY = parentBranch.range.minY + childSize;
  10482. maxY = parentBranch.range.maxY;
  10483. break;
  10484. case "SE":
  10485. minX = parentBranch.range.minX + childSize;
  10486. maxX = parentBranch.range.maxX;
  10487. minY = parentBranch.range.minY + childSize;
  10488. maxY = parentBranch.range.maxY;
  10489. break;
  10490. }
  10491. parentBranch.children[region] = {
  10492. centerOfMass:{x:0,y:0},
  10493. mass:0,
  10494. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10495. size: 0.5 * parentBranch.size,
  10496. calcSize: 2 * parentBranch.calcSize,
  10497. children: {data:null},
  10498. maxWidth: 0,
  10499. level: parentBranch.level+1,
  10500. childrenCount: 0
  10501. };
  10502. },
  10503. /**
  10504. * This function is for debugging purposed, it draws the tree.
  10505. *
  10506. * @param ctx
  10507. * @param color
  10508. * @private
  10509. */
  10510. _drawTree : function(ctx,color) {
  10511. if (this.barnesHutTree !== undefined) {
  10512. ctx.lineWidth = 1;
  10513. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10514. }
  10515. },
  10516. /**
  10517. * This function is for debugging purposes. It draws the branches recursively.
  10518. *
  10519. * @param branch
  10520. * @param ctx
  10521. * @param color
  10522. * @private
  10523. */
  10524. _drawBranch : function(branch,ctx,color) {
  10525. if (color === undefined) {
  10526. color = "#FF0000";
  10527. }
  10528. if (branch.childrenCount == 4) {
  10529. this._drawBranch(branch.children.NW,ctx);
  10530. this._drawBranch(branch.children.NE,ctx);
  10531. this._drawBranch(branch.children.SE,ctx);
  10532. this._drawBranch(branch.children.SW,ctx);
  10533. }
  10534. ctx.strokeStyle = color;
  10535. ctx.beginPath();
  10536. ctx.moveTo(branch.range.minX,branch.range.minY);
  10537. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10538. ctx.stroke();
  10539. ctx.beginPath();
  10540. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10541. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10542. ctx.stroke();
  10543. ctx.beginPath();
  10544. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10545. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10546. ctx.stroke();
  10547. ctx.beginPath();
  10548. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10549. ctx.lineTo(branch.range.minX,branch.range.minY);
  10550. ctx.stroke();
  10551. /*
  10552. if (branch.mass > 0) {
  10553. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10554. ctx.stroke();
  10555. }
  10556. */
  10557. }
  10558. };
  10559. /**
  10560. * Created by Alex on 2/10/14.
  10561. */
  10562. var repulsionMixin = {
  10563. /**
  10564. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10565. * This field is linearly approximated.
  10566. *
  10567. * @private
  10568. */
  10569. _calculateNodeForces: function () {
  10570. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10571. repulsingForce, node1, node2, i, j;
  10572. var nodes = this.calculationNodes;
  10573. var nodeIndices = this.calculationNodeIndices;
  10574. // approximation constants
  10575. var a_base = -2 / 3;
  10576. var b = 4 / 3;
  10577. // repulsing forces between nodes
  10578. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10579. var minimumDistance = nodeDistance;
  10580. // we loop from i over all but the last entree in the array
  10581. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10582. for (i = 0; i < nodeIndices.length - 1; i++) {
  10583. node1 = nodes[nodeIndices[i]];
  10584. for (j = i + 1; j < nodeIndices.length; j++) {
  10585. node2 = nodes[nodeIndices[j]];
  10586. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10587. dx = node2.x - node1.x;
  10588. dy = node2.y - node1.y;
  10589. distance = Math.sqrt(dx * dx + dy * dy);
  10590. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10591. var a = a_base / minimumDistance;
  10592. if (distance < 2 * minimumDistance) {
  10593. if (distance < 0.5 * minimumDistance) {
  10594. repulsingForce = 1.0;
  10595. }
  10596. else {
  10597. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10598. }
  10599. // amplify the repulsion for clusters.
  10600. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10601. repulsingForce = repulsingForce / distance;
  10602. fx = dx * repulsingForce;
  10603. fy = dy * repulsingForce;
  10604. node1.fx -= fx;
  10605. node1.fy -= fy;
  10606. node2.fx += fx;
  10607. node2.fy += fy;
  10608. }
  10609. }
  10610. }
  10611. }
  10612. };
  10613. var HierarchicalLayoutMixin = {
  10614. _resetLevels : function() {
  10615. for (var nodeId in this.nodes) {
  10616. if (this.nodes.hasOwnProperty(nodeId)) {
  10617. var node = this.nodes[nodeId];
  10618. if (node.preassignedLevel == false) {
  10619. node.level = -1;
  10620. }
  10621. }
  10622. }
  10623. },
  10624. /**
  10625. * This is the main function to layout the nodes in a hierarchical way.
  10626. * It checks if the node details are supplied correctly
  10627. *
  10628. * @private
  10629. */
  10630. _setupHierarchicalLayout : function() {
  10631. if (this.constants.hierarchicalLayout.enabled == true) {
  10632. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10633. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10634. }
  10635. else {
  10636. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10637. }
  10638. // get the size of the largest hubs and check if the user has defined a level for a node.
  10639. var hubsize = 0;
  10640. var node, nodeId;
  10641. var definedLevel = false;
  10642. var undefinedLevel = false;
  10643. for (nodeId in this.nodes) {
  10644. if (this.nodes.hasOwnProperty(nodeId)) {
  10645. node = this.nodes[nodeId];
  10646. if (node.level != -1) {
  10647. definedLevel = true;
  10648. }
  10649. else {
  10650. undefinedLevel = true;
  10651. }
  10652. if (hubsize < node.edges.length) {
  10653. hubsize = node.edges.length;
  10654. }
  10655. }
  10656. }
  10657. // if the user defined some levels but not all, alert and run without hierarchical layout
  10658. if (undefinedLevel == true && definedLevel == true) {
  10659. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10660. this.zoomExtent(true,this.constants.clustering.enabled);
  10661. if (!this.constants.clustering.enabled) {
  10662. this.start();
  10663. }
  10664. }
  10665. else {
  10666. // setup the system to use hierarchical method.
  10667. this._changeConstants();
  10668. // define levels if undefined by the users. Based on hubsize
  10669. if (undefinedLevel == true) {
  10670. this._determineLevels(hubsize);
  10671. }
  10672. // check the distribution of the nodes per level.
  10673. var distribution = this._getDistribution();
  10674. // place the nodes on the canvas. This also stablilizes the system.
  10675. this._placeNodesByHierarchy(distribution);
  10676. // start the simulation.
  10677. this.start();
  10678. }
  10679. }
  10680. },
  10681. /**
  10682. * This function places the nodes on the canvas based on the hierarchial distribution.
  10683. *
  10684. * @param {Object} distribution | obtained by the function this._getDistribution()
  10685. * @private
  10686. */
  10687. _placeNodesByHierarchy : function(distribution) {
  10688. var nodeId, node;
  10689. // start placing all the level 0 nodes first. Then recursively position their branches.
  10690. for (nodeId in distribution[0].nodes) {
  10691. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10692. node = distribution[0].nodes[nodeId];
  10693. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10694. if (node.xFixed) {
  10695. node.x = distribution[0].minPos;
  10696. node.xFixed = false;
  10697. distribution[0].minPos += distribution[0].nodeSpacing;
  10698. }
  10699. }
  10700. else {
  10701. if (node.yFixed) {
  10702. node.y = distribution[0].minPos;
  10703. node.yFixed = false;
  10704. distribution[0].minPos += distribution[0].nodeSpacing;
  10705. }
  10706. }
  10707. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10708. }
  10709. }
  10710. // stabilize the system after positioning. This function calls zoomExtent.
  10711. this._stabilize();
  10712. },
  10713. /**
  10714. * This function get the distribution of levels based on hubsize
  10715. *
  10716. * @returns {Object}
  10717. * @private
  10718. */
  10719. _getDistribution : function() {
  10720. var distribution = {};
  10721. var nodeId, node, level;
  10722. // 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.
  10723. // the fix of X is removed after the x value has been set.
  10724. for (nodeId in this.nodes) {
  10725. if (this.nodes.hasOwnProperty(nodeId)) {
  10726. node = this.nodes[nodeId];
  10727. node.xFixed = true;
  10728. node.yFixed = true;
  10729. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10730. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10731. }
  10732. else {
  10733. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10734. }
  10735. if (!distribution.hasOwnProperty(node.level)) {
  10736. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10737. }
  10738. distribution[node.level].amount += 1;
  10739. distribution[node.level].nodes[node.id] = node;
  10740. }
  10741. }
  10742. // determine the largest amount of nodes of all levels
  10743. var maxCount = 0;
  10744. for (level in distribution) {
  10745. if (distribution.hasOwnProperty(level)) {
  10746. if (maxCount < distribution[level].amount) {
  10747. maxCount = distribution[level].amount;
  10748. }
  10749. }
  10750. }
  10751. // set the initial position and spacing of each nodes accordingly
  10752. for (level in distribution) {
  10753. if (distribution.hasOwnProperty(level)) {
  10754. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10755. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10756. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10757. }
  10758. }
  10759. return distribution;
  10760. },
  10761. /**
  10762. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10763. *
  10764. * @param hubsize
  10765. * @private
  10766. */
  10767. _determineLevels : function(hubsize) {
  10768. var nodeId, node;
  10769. // determine hubs
  10770. for (nodeId in this.nodes) {
  10771. if (this.nodes.hasOwnProperty(nodeId)) {
  10772. node = this.nodes[nodeId];
  10773. if (node.edges.length == hubsize) {
  10774. node.level = 0;
  10775. }
  10776. }
  10777. }
  10778. // branch from hubs
  10779. for (nodeId in this.nodes) {
  10780. if (this.nodes.hasOwnProperty(nodeId)) {
  10781. node = this.nodes[nodeId];
  10782. if (node.level == 0) {
  10783. this._setLevel(1,node.edges,node.id);
  10784. }
  10785. }
  10786. }
  10787. },
  10788. /**
  10789. * Since hierarchical layout does not support:
  10790. * - smooth curves (based on the physics),
  10791. * - clustering (based on dynamic node counts)
  10792. *
  10793. * We disable both features so there will be no problems.
  10794. *
  10795. * @private
  10796. */
  10797. _changeConstants : function() {
  10798. this.constants.clustering.enabled = false;
  10799. this.constants.physics.barnesHut.enabled = false;
  10800. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10801. this._loadSelectedForceSolver();
  10802. this.constants.smoothCurves = false;
  10803. this._configureSmoothCurves();
  10804. },
  10805. /**
  10806. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10807. * on a X position that ensures there will be no overlap.
  10808. *
  10809. * @param edges
  10810. * @param parentId
  10811. * @param distribution
  10812. * @param parentLevel
  10813. * @private
  10814. */
  10815. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10816. for (var i = 0; i < edges.length; i++) {
  10817. var childNode = null;
  10818. if (edges[i].toId == parentId) {
  10819. childNode = edges[i].from;
  10820. }
  10821. else {
  10822. childNode = edges[i].to;
  10823. }
  10824. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10825. var nodeMoved = false;
  10826. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10827. if (childNode.xFixed && childNode.level > parentLevel) {
  10828. childNode.xFixed = false;
  10829. childNode.x = distribution[childNode.level].minPos;
  10830. nodeMoved = true;
  10831. }
  10832. }
  10833. else {
  10834. if (childNode.yFixed && childNode.level > parentLevel) {
  10835. childNode.yFixed = false;
  10836. childNode.y = distribution[childNode.level].minPos;
  10837. nodeMoved = true;
  10838. }
  10839. }
  10840. if (nodeMoved == true) {
  10841. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10842. if (childNode.edges.length > 1) {
  10843. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10844. }
  10845. }
  10846. }
  10847. },
  10848. /**
  10849. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10850. *
  10851. * @param level
  10852. * @param edges
  10853. * @param parentId
  10854. * @private
  10855. */
  10856. _setLevel : function(level, edges, parentId) {
  10857. for (var i = 0; i < edges.length; i++) {
  10858. var childNode = null;
  10859. if (edges[i].toId == parentId) {
  10860. childNode = edges[i].from;
  10861. }
  10862. else {
  10863. childNode = edges[i].to;
  10864. }
  10865. if (childNode.level == -1 || childNode.level > level) {
  10866. childNode.level = level;
  10867. if (edges.length > 1) {
  10868. this._setLevel(level+1, childNode.edges, childNode.id);
  10869. }
  10870. }
  10871. }
  10872. },
  10873. /**
  10874. * Unfix nodes
  10875. *
  10876. * @private
  10877. */
  10878. _restoreNodes : function() {
  10879. for (nodeId in this.nodes) {
  10880. if (this.nodes.hasOwnProperty(nodeId)) {
  10881. this.nodes[nodeId].xFixed = false;
  10882. this.nodes[nodeId].yFixed = false;
  10883. }
  10884. }
  10885. }
  10886. };
  10887. /**
  10888. * Created by Alex on 2/4/14.
  10889. */
  10890. var manipulationMixin = {
  10891. /**
  10892. * clears the toolbar div element of children
  10893. *
  10894. * @private
  10895. */
  10896. _clearManipulatorBar : function() {
  10897. while (this.manipulationDiv.hasChildNodes()) {
  10898. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10899. }
  10900. },
  10901. /**
  10902. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  10903. * these functions to their original functionality, we saved them in this.cachedFunctions.
  10904. * This function restores these functions to their original function.
  10905. *
  10906. * @private
  10907. */
  10908. _restoreOverloadedFunctions : function() {
  10909. for (var functionName in this.cachedFunctions) {
  10910. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  10911. this[functionName] = this.cachedFunctions[functionName];
  10912. }
  10913. }
  10914. },
  10915. /**
  10916. * Enable or disable edit-mode.
  10917. *
  10918. * @private
  10919. */
  10920. _toggleEditMode : function() {
  10921. this.editMode = !this.editMode;
  10922. var toolbar = document.getElementById("graph-manipulationDiv");
  10923. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10924. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  10925. if (this.editMode == true) {
  10926. toolbar.style.display="block";
  10927. closeDiv.style.display="block";
  10928. editModeDiv.style.display="none";
  10929. closeDiv.onclick = this._toggleEditMode.bind(this);
  10930. }
  10931. else {
  10932. toolbar.style.display="none";
  10933. closeDiv.style.display="none";
  10934. editModeDiv.style.display="block";
  10935. closeDiv.onclick = null;
  10936. }
  10937. this._createManipulatorBar()
  10938. },
  10939. /**
  10940. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  10941. *
  10942. * @private
  10943. */
  10944. _createManipulatorBar : function() {
  10945. // remove bound functions
  10946. if (this.boundFunction) {
  10947. this.off('select', this.boundFunction);
  10948. }
  10949. // restore overloaded functions
  10950. this._restoreOverloadedFunctions();
  10951. // resume calculation
  10952. this.freezeSimulation = false;
  10953. // reset global variables
  10954. this.blockConnectingEdgeSelection = false;
  10955. this.forceAppendSelection = false;
  10956. if (this.editMode == true) {
  10957. while (this.manipulationDiv.hasChildNodes()) {
  10958. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10959. }
  10960. // add the icons to the manipulator div
  10961. this.manipulationDiv.innerHTML = "" +
  10962. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  10963. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  10964. "<div class='graph-seperatorLine'></div>" +
  10965. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  10966. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  10967. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10968. this.manipulationDiv.innerHTML += "" +
  10969. "<div class='graph-seperatorLine'></div>" +
  10970. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  10971. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  10972. }
  10973. if (this._selectionIsEmpty() == false) {
  10974. this.manipulationDiv.innerHTML += "" +
  10975. "<div class='graph-seperatorLine'></div>" +
  10976. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  10977. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  10978. }
  10979. // bind the icons
  10980. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  10981. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  10982. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  10983. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  10984. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10985. var editButton = document.getElementById("graph-manipulate-editNode");
  10986. editButton.onclick = this._editNode.bind(this);
  10987. }
  10988. if (this._selectionIsEmpty() == false) {
  10989. var deleteButton = document.getElementById("graph-manipulate-delete");
  10990. deleteButton.onclick = this._deleteSelected.bind(this);
  10991. }
  10992. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10993. closeDiv.onclick = this._toggleEditMode.bind(this);
  10994. this.boundFunction = this._createManipulatorBar.bind(this);
  10995. this.on('select', this.boundFunction);
  10996. }
  10997. else {
  10998. this.editModeDiv.innerHTML = "" +
  10999. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11000. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  11001. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11002. editModeButton.onclick = this._toggleEditMode.bind(this);
  11003. }
  11004. },
  11005. /**
  11006. * Create the toolbar for adding Nodes
  11007. *
  11008. * @private
  11009. */
  11010. _createAddNodeToolbar : function() {
  11011. // clear the toolbar
  11012. this._clearManipulatorBar();
  11013. if (this.boundFunction) {
  11014. this.off('select', this.boundFunction);
  11015. }
  11016. // create the toolbar contents
  11017. this.manipulationDiv.innerHTML = "" +
  11018. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11019. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11020. "<div class='graph-seperatorLine'></div>" +
  11021. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11022. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11023. // bind the icon
  11024. var backButton = document.getElementById("graph-manipulate-back");
  11025. backButton.onclick = this._createManipulatorBar.bind(this);
  11026. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11027. this.boundFunction = this._addNode.bind(this);
  11028. this.on('select', this.boundFunction);
  11029. },
  11030. /**
  11031. * create the toolbar to connect nodes
  11032. *
  11033. * @private
  11034. */
  11035. _createAddEdgeToolbar : function() {
  11036. // clear the toolbar
  11037. this._clearManipulatorBar();
  11038. this._unselectAll(true);
  11039. this.freezeSimulation = true;
  11040. if (this.boundFunction) {
  11041. this.off('select', this.boundFunction);
  11042. }
  11043. this._unselectAll();
  11044. this.forceAppendSelection = false;
  11045. this.blockConnectingEdgeSelection = true;
  11046. this.manipulationDiv.innerHTML = "" +
  11047. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11048. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11049. "<div class='graph-seperatorLine'></div>" +
  11050. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11051. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11052. // bind the icon
  11053. var backButton = document.getElementById("graph-manipulate-back");
  11054. backButton.onclick = this._createManipulatorBar.bind(this);
  11055. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11056. this.boundFunction = this._handleConnect.bind(this);
  11057. this.on('select', this.boundFunction);
  11058. // temporarily overload functions
  11059. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11060. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11061. this._handleTouch = this._handleConnect;
  11062. this._handleOnRelease = this._finishConnect;
  11063. // redraw to show the unselect
  11064. this._redraw();
  11065. },
  11066. /**
  11067. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11068. * to walk the user through the process.
  11069. *
  11070. * @private
  11071. */
  11072. _handleConnect : function(pointer) {
  11073. if (this._getSelectedNodeCount() == 0) {
  11074. var node = this._getNodeAt(pointer);
  11075. if (node != null) {
  11076. if (node.clusterSize > 1) {
  11077. alert("Cannot create edges to a cluster.")
  11078. }
  11079. else {
  11080. this._selectObject(node,false);
  11081. // create a node the temporary line can look at
  11082. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11083. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11084. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11085. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11086. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11087. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11088. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11089. // create a temporary edge
  11090. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11091. this.edges['connectionEdge'].from = node;
  11092. this.edges['connectionEdge'].connected = true;
  11093. this.edges['connectionEdge'].smooth = true;
  11094. this.edges['connectionEdge'].selected = true;
  11095. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11096. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11097. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11098. this._handleOnDrag = function(event) {
  11099. var pointer = this._getPointer(event.gesture.center);
  11100. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11101. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11102. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11103. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11104. };
  11105. this.moving = true;
  11106. this.start();
  11107. }
  11108. }
  11109. }
  11110. },
  11111. _finishConnect : function(pointer) {
  11112. if (this._getSelectedNodeCount() == 1) {
  11113. // restore the drag function
  11114. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11115. delete this.cachedFunctions["_handleOnDrag"];
  11116. // remember the edge id
  11117. var connectFromId = this.edges['connectionEdge'].fromId;
  11118. // remove the temporary nodes and edge
  11119. delete this.edges['connectionEdge'];
  11120. delete this.sectors['support']['nodes']['targetNode'];
  11121. delete this.sectors['support']['nodes']['targetViaNode'];
  11122. var node = this._getNodeAt(pointer);
  11123. if (node != null) {
  11124. if (node.clusterSize > 1) {
  11125. alert("Cannot create edges to a cluster.")
  11126. }
  11127. else {
  11128. this._createEdge(connectFromId,node.id);
  11129. this._createManipulatorBar();
  11130. }
  11131. }
  11132. this._unselectAll();
  11133. }
  11134. },
  11135. /**
  11136. * Adds a node on the specified location
  11137. */
  11138. _addNode : function() {
  11139. if (this._selectionIsEmpty() && this.editMode == true) {
  11140. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11141. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11142. if (this.triggerFunctions.add) {
  11143. if (this.triggerFunctions.add.length == 2) {
  11144. var me = this;
  11145. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11146. me.nodesData.add(finalizedData);
  11147. me._createManipulatorBar();
  11148. me.moving = true;
  11149. me.start();
  11150. });
  11151. }
  11152. else {
  11153. alert(this.constants.labels['addError']);
  11154. this._createManipulatorBar();
  11155. this.moving = true;
  11156. this.start();
  11157. }
  11158. }
  11159. else {
  11160. this.nodesData.add(defaultData);
  11161. this._createManipulatorBar();
  11162. this.moving = true;
  11163. this.start();
  11164. }
  11165. }
  11166. },
  11167. /**
  11168. * connect two nodes with a new edge.
  11169. *
  11170. * @private
  11171. */
  11172. _createEdge : function(sourceNodeId,targetNodeId) {
  11173. if (this.editMode == true) {
  11174. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11175. if (this.triggerFunctions.connect) {
  11176. if (this.triggerFunctions.connect.length == 2) {
  11177. var me = this;
  11178. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11179. me.edgesData.add(finalizedData);
  11180. me.moving = true;
  11181. me.start();
  11182. });
  11183. }
  11184. else {
  11185. alert(this.constants.labels["linkError"]);
  11186. this.moving = true;
  11187. this.start();
  11188. }
  11189. }
  11190. else {
  11191. this.edgesData.add(defaultData);
  11192. this.moving = true;
  11193. this.start();
  11194. }
  11195. }
  11196. },
  11197. /**
  11198. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11199. *
  11200. * @private
  11201. */
  11202. _editNode : function() {
  11203. if (this.triggerFunctions.edit && this.editMode == true) {
  11204. var node = this._getSelectedNode();
  11205. var data = {id:node.id,
  11206. label: node.label,
  11207. group: node.group,
  11208. shape: node.shape,
  11209. color: {
  11210. background:node.color.background,
  11211. border:node.color.border,
  11212. highlight: {
  11213. background:node.color.highlight.background,
  11214. border:node.color.highlight.border
  11215. }
  11216. }};
  11217. if (this.triggerFunctions.edit.length == 2) {
  11218. var me = this;
  11219. this.triggerFunctions.edit(data, function (finalizedData) {
  11220. me.nodesData.update(finalizedData);
  11221. me._createManipulatorBar();
  11222. me.moving = true;
  11223. me.start();
  11224. });
  11225. }
  11226. else {
  11227. alert(this.constants.labels["editError"]);
  11228. }
  11229. }
  11230. else {
  11231. alert(this.constants.labels["editBoundError"]);
  11232. }
  11233. },
  11234. /**
  11235. * delete everything in the selection
  11236. *
  11237. * @private
  11238. */
  11239. _deleteSelected : function() {
  11240. if (!this._selectionIsEmpty() && this.editMode == true) {
  11241. if (!this._clusterInSelection()) {
  11242. var selectedNodes = this.getSelectedNodes();
  11243. var selectedEdges = this.getSelectedEdges();
  11244. if (this.triggerFunctions.del) {
  11245. var me = this;
  11246. var data = {nodes: selectedNodes, edges: selectedEdges};
  11247. if (this.triggerFunctions.del.length = 2) {
  11248. this.triggerFunctions.del(data, function (finalizedData) {
  11249. me.edgesData.remove(finalizedData.edges);
  11250. me.nodesData.remove(finalizedData.nodes);
  11251. me._unselectAll();
  11252. me.moving = true;
  11253. me.start();
  11254. });
  11255. }
  11256. else {
  11257. alert(this.constants.labels["deleteError"])
  11258. }
  11259. }
  11260. else {
  11261. this.edgesData.remove(selectedEdges);
  11262. this.nodesData.remove(selectedNodes);
  11263. this._unselectAll();
  11264. this.moving = true;
  11265. this.start();
  11266. }
  11267. }
  11268. else {
  11269. alert(this.constants.labels["deleteClusterError"]);
  11270. }
  11271. }
  11272. }
  11273. };
  11274. /**
  11275. * Creation of the SectorMixin var.
  11276. *
  11277. * This contains all the functions the Graph object can use to employ the sector system.
  11278. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11279. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11280. *
  11281. * Alex de Mulder
  11282. * 21-01-2013
  11283. */
  11284. var SectorMixin = {
  11285. /**
  11286. * This function is only called by the setData function of the Graph object.
  11287. * This loads the global references into the active sector. This initializes the sector.
  11288. *
  11289. * @private
  11290. */
  11291. _putDataInSector : function() {
  11292. this.sectors["active"][this._sector()].nodes = this.nodes;
  11293. this.sectors["active"][this._sector()].edges = this.edges;
  11294. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11295. },
  11296. /**
  11297. * /**
  11298. * This function sets the global references to nodes, edges and nodeIndices back to
  11299. * those of the supplied (active) sector. If a type is defined, do the specific type
  11300. *
  11301. * @param {String} sectorId
  11302. * @param {String} [sectorType] | "active" or "frozen"
  11303. * @private
  11304. */
  11305. _switchToSector : function(sectorId, sectorType) {
  11306. if (sectorType === undefined || sectorType == "active") {
  11307. this._switchToActiveSector(sectorId);
  11308. }
  11309. else {
  11310. this._switchToFrozenSector(sectorId);
  11311. }
  11312. },
  11313. /**
  11314. * This function sets the global references to nodes, edges and nodeIndices back to
  11315. * those of the supplied active sector.
  11316. *
  11317. * @param sectorId
  11318. * @private
  11319. */
  11320. _switchToActiveSector : function(sectorId) {
  11321. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11322. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11323. this.edges = this.sectors["active"][sectorId]["edges"];
  11324. },
  11325. /**
  11326. * This function sets the global references to nodes, edges and nodeIndices back to
  11327. * those of the supplied active sector.
  11328. *
  11329. * @param sectorId
  11330. * @private
  11331. */
  11332. _switchToSupportSector : function() {
  11333. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11334. this.nodes = this.sectors["support"]["nodes"];
  11335. this.edges = this.sectors["support"]["edges"];
  11336. },
  11337. /**
  11338. * This function sets the global references to nodes, edges and nodeIndices back to
  11339. * those of the supplied frozen sector.
  11340. *
  11341. * @param sectorId
  11342. * @private
  11343. */
  11344. _switchToFrozenSector : function(sectorId) {
  11345. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11346. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11347. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11348. },
  11349. /**
  11350. * This function sets the global references to nodes, edges and nodeIndices back to
  11351. * those of the currently active sector.
  11352. *
  11353. * @private
  11354. */
  11355. _loadLatestSector : function() {
  11356. this._switchToSector(this._sector());
  11357. },
  11358. /**
  11359. * This function returns the currently active sector Id
  11360. *
  11361. * @returns {String}
  11362. * @private
  11363. */
  11364. _sector : function() {
  11365. return this.activeSector[this.activeSector.length-1];
  11366. },
  11367. /**
  11368. * This function returns the previously active sector Id
  11369. *
  11370. * @returns {String}
  11371. * @private
  11372. */
  11373. _previousSector : function() {
  11374. if (this.activeSector.length > 1) {
  11375. return this.activeSector[this.activeSector.length-2];
  11376. }
  11377. else {
  11378. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11379. }
  11380. },
  11381. /**
  11382. * We add the active sector at the end of the this.activeSector array
  11383. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11384. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11385. *
  11386. * @param newId
  11387. * @private
  11388. */
  11389. _setActiveSector : function(newId) {
  11390. this.activeSector.push(newId);
  11391. },
  11392. /**
  11393. * We remove the currently active sector id from the active sector stack. This happens when
  11394. * we reactivate the previously active sector
  11395. *
  11396. * @private
  11397. */
  11398. _forgetLastSector : function() {
  11399. this.activeSector.pop();
  11400. },
  11401. /**
  11402. * This function creates a new active sector with the supplied newId. This newId
  11403. * is the expanding node id.
  11404. *
  11405. * @param {String} newId | Id of the new active sector
  11406. * @private
  11407. */
  11408. _createNewSector : function(newId) {
  11409. // create the new sector
  11410. this.sectors["active"][newId] = {"nodes":{},
  11411. "edges":{},
  11412. "nodeIndices":[],
  11413. "formationScale": this.scale,
  11414. "drawingNode": undefined};
  11415. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11416. this.sectors["active"][newId]['drawingNode'] = new Node(
  11417. {id:newId,
  11418. color: {
  11419. background: "#eaefef",
  11420. border: "495c5e"
  11421. }
  11422. },{},{},this.constants);
  11423. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11424. },
  11425. /**
  11426. * This function removes the currently active sector. This is called when we create a new
  11427. * active sector.
  11428. *
  11429. * @param {String} sectorId | Id of the active sector that will be removed
  11430. * @private
  11431. */
  11432. _deleteActiveSector : function(sectorId) {
  11433. delete this.sectors["active"][sectorId];
  11434. },
  11435. /**
  11436. * This function removes the currently active sector. This is called when we reactivate
  11437. * the previously active sector.
  11438. *
  11439. * @param {String} sectorId | Id of the active sector that will be removed
  11440. * @private
  11441. */
  11442. _deleteFrozenSector : function(sectorId) {
  11443. delete this.sectors["frozen"][sectorId];
  11444. },
  11445. /**
  11446. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11447. * We copy the references, then delete the active entree.
  11448. *
  11449. * @param sectorId
  11450. * @private
  11451. */
  11452. _freezeSector : function(sectorId) {
  11453. // we move the set references from the active to the frozen stack.
  11454. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11455. // we have moved the sector data into the frozen set, we now remove it from the active set
  11456. this._deleteActiveSector(sectorId);
  11457. },
  11458. /**
  11459. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11460. * object to the "active" object.
  11461. *
  11462. * @param sectorId
  11463. * @private
  11464. */
  11465. _activateSector : function(sectorId) {
  11466. // we move the set references from the frozen to the active stack.
  11467. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11468. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11469. this._deleteFrozenSector(sectorId);
  11470. },
  11471. /**
  11472. * This function merges the data from the currently active sector with a frozen sector. This is used
  11473. * in the process of reverting back to the previously active sector.
  11474. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11475. * upon the creation of a new active sector.
  11476. *
  11477. * @param sectorId
  11478. * @private
  11479. */
  11480. _mergeThisWithFrozen : function(sectorId) {
  11481. // copy all nodes
  11482. for (var nodeId in this.nodes) {
  11483. if (this.nodes.hasOwnProperty(nodeId)) {
  11484. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11485. }
  11486. }
  11487. // copy all edges (if not fully clustered, else there are no edges)
  11488. for (var edgeId in this.edges) {
  11489. if (this.edges.hasOwnProperty(edgeId)) {
  11490. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11491. }
  11492. }
  11493. // merge the nodeIndices
  11494. for (var i = 0; i < this.nodeIndices.length; i++) {
  11495. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11496. }
  11497. },
  11498. /**
  11499. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11500. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11501. *
  11502. * @private
  11503. */
  11504. _collapseThisToSingleCluster : function() {
  11505. this.clusterToFit(1,false);
  11506. },
  11507. /**
  11508. * We create a new active sector from the node that we want to open.
  11509. *
  11510. * @param node
  11511. * @private
  11512. */
  11513. _addSector : function(node) {
  11514. // this is the currently active sector
  11515. var sector = this._sector();
  11516. // // this should allow me to select nodes from a frozen set.
  11517. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11518. // console.log("the node is part of the active sector");
  11519. // }
  11520. // else {
  11521. // console.log("I dont know what the fuck happened!!");
  11522. // }
  11523. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11524. delete this.nodes[node.id];
  11525. var unqiueIdentifier = util.randomUUID();
  11526. // we fully freeze the currently active sector
  11527. this._freezeSector(sector);
  11528. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11529. this._createNewSector(unqiueIdentifier);
  11530. // we add the active sector to the sectors array to be able to revert these steps later on
  11531. this._setActiveSector(unqiueIdentifier);
  11532. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11533. this._switchToSector(this._sector());
  11534. // finally we add the node we removed from our previous active sector to the new active sector
  11535. this.nodes[node.id] = node;
  11536. },
  11537. /**
  11538. * We close the sector that is currently open and revert back to the one before.
  11539. * If the active sector is the "default" sector, nothing happens.
  11540. *
  11541. * @private
  11542. */
  11543. _collapseSector : function() {
  11544. // the currently active sector
  11545. var sector = this._sector();
  11546. // we cannot collapse the default sector
  11547. if (sector != "default") {
  11548. if ((this.nodeIndices.length == 1) ||
  11549. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11550. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11551. var previousSector = this._previousSector();
  11552. // we collapse the sector back to a single cluster
  11553. this._collapseThisToSingleCluster();
  11554. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11555. // This previous sector is the one we will reactivate
  11556. this._mergeThisWithFrozen(previousSector);
  11557. // the previously active (frozen) sector now has all the data from the currently active sector.
  11558. // we can now delete the active sector.
  11559. this._deleteActiveSector(sector);
  11560. // we activate the previously active (and currently frozen) sector.
  11561. this._activateSector(previousSector);
  11562. // we load the references from the newly active sector into the global references
  11563. this._switchToSector(previousSector);
  11564. // we forget the previously active sector because we reverted to the one before
  11565. this._forgetLastSector();
  11566. // finally, we update the node index list.
  11567. this._updateNodeIndexList();
  11568. // we refresh the list with calulation nodes and calculation node indices.
  11569. this._updateCalculationNodes();
  11570. }
  11571. }
  11572. },
  11573. /**
  11574. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11575. *
  11576. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11577. * | we dont pass the function itself because then the "this" is the window object
  11578. * | instead of the Graph object
  11579. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11580. * @private
  11581. */
  11582. _doInAllActiveSectors : function(runFunction,argument) {
  11583. if (argument === undefined) {
  11584. for (var sector in this.sectors["active"]) {
  11585. if (this.sectors["active"].hasOwnProperty(sector)) {
  11586. // switch the global references to those of this sector
  11587. this._switchToActiveSector(sector);
  11588. this[runFunction]();
  11589. }
  11590. }
  11591. }
  11592. else {
  11593. for (var sector in this.sectors["active"]) {
  11594. if (this.sectors["active"].hasOwnProperty(sector)) {
  11595. // switch the global references to those of this sector
  11596. this._switchToActiveSector(sector);
  11597. var args = Array.prototype.splice.call(arguments, 1);
  11598. if (args.length > 1) {
  11599. this[runFunction](args[0],args[1]);
  11600. }
  11601. else {
  11602. this[runFunction](argument);
  11603. }
  11604. }
  11605. }
  11606. }
  11607. // we revert the global references back to our active sector
  11608. this._loadLatestSector();
  11609. },
  11610. /**
  11611. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11612. *
  11613. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11614. * | we dont pass the function itself because then the "this" is the window object
  11615. * | instead of the Graph object
  11616. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11617. * @private
  11618. */
  11619. _doInSupportSector : function(runFunction,argument) {
  11620. if (argument === undefined) {
  11621. this._switchToSupportSector();
  11622. this[runFunction]();
  11623. }
  11624. else {
  11625. this._switchToSupportSector();
  11626. var args = Array.prototype.splice.call(arguments, 1);
  11627. if (args.length > 1) {
  11628. this[runFunction](args[0],args[1]);
  11629. }
  11630. else {
  11631. this[runFunction](argument);
  11632. }
  11633. }
  11634. // we revert the global references back to our active sector
  11635. this._loadLatestSector();
  11636. },
  11637. /**
  11638. * This runs a function in all frozen sectors. This is used in the _redraw().
  11639. *
  11640. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11641. * | we don't pass the function itself because then the "this" is the window object
  11642. * | instead of the Graph object
  11643. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11644. * @private
  11645. */
  11646. _doInAllFrozenSectors : function(runFunction,argument) {
  11647. if (argument === undefined) {
  11648. for (var sector in this.sectors["frozen"]) {
  11649. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11650. // switch the global references to those of this sector
  11651. this._switchToFrozenSector(sector);
  11652. this[runFunction]();
  11653. }
  11654. }
  11655. }
  11656. else {
  11657. for (var sector in this.sectors["frozen"]) {
  11658. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11659. // switch the global references to those of this sector
  11660. this._switchToFrozenSector(sector);
  11661. var args = Array.prototype.splice.call(arguments, 1);
  11662. if (args.length > 1) {
  11663. this[runFunction](args[0],args[1]);
  11664. }
  11665. else {
  11666. this[runFunction](argument);
  11667. }
  11668. }
  11669. }
  11670. }
  11671. this._loadLatestSector();
  11672. },
  11673. /**
  11674. * This runs a function in all sectors. This is used in the _redraw().
  11675. *
  11676. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11677. * | we don't pass the function itself because then the "this" is the window object
  11678. * | instead of the Graph object
  11679. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11680. * @private
  11681. */
  11682. _doInAllSectors : function(runFunction,argument) {
  11683. var args = Array.prototype.splice.call(arguments, 1);
  11684. if (argument === undefined) {
  11685. this._doInAllActiveSectors(runFunction);
  11686. this._doInAllFrozenSectors(runFunction);
  11687. }
  11688. else {
  11689. if (args.length > 1) {
  11690. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11691. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11692. }
  11693. else {
  11694. this._doInAllActiveSectors(runFunction,argument);
  11695. this._doInAllFrozenSectors(runFunction,argument);
  11696. }
  11697. }
  11698. },
  11699. /**
  11700. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11701. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11702. *
  11703. * @private
  11704. */
  11705. _clearNodeIndexList : function() {
  11706. var sector = this._sector();
  11707. this.sectors["active"][sector]["nodeIndices"] = [];
  11708. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11709. },
  11710. /**
  11711. * Draw the encompassing sector node
  11712. *
  11713. * @param ctx
  11714. * @param sectorType
  11715. * @private
  11716. */
  11717. _drawSectorNodes : function(ctx,sectorType) {
  11718. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11719. for (var sector in this.sectors[sectorType]) {
  11720. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11721. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11722. this._switchToSector(sector,sectorType);
  11723. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11724. for (var nodeId in this.nodes) {
  11725. if (this.nodes.hasOwnProperty(nodeId)) {
  11726. node = this.nodes[nodeId];
  11727. node.resize(ctx);
  11728. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11729. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11730. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11731. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11732. }
  11733. }
  11734. node = this.sectors[sectorType][sector]["drawingNode"];
  11735. node.x = 0.5 * (maxX + minX);
  11736. node.y = 0.5 * (maxY + minY);
  11737. node.width = 2 * (node.x - minX);
  11738. node.height = 2 * (node.y - minY);
  11739. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11740. node.setScale(this.scale);
  11741. node._drawCircle(ctx);
  11742. }
  11743. }
  11744. }
  11745. },
  11746. _drawAllSectorNodes : function(ctx) {
  11747. this._drawSectorNodes(ctx,"frozen");
  11748. this._drawSectorNodes(ctx,"active");
  11749. this._loadLatestSector();
  11750. }
  11751. };
  11752. /**
  11753. * Creation of the ClusterMixin var.
  11754. *
  11755. * This contains all the functions the Graph object can use to employ clustering
  11756. *
  11757. * Alex de Mulder
  11758. * 21-01-2013
  11759. */
  11760. var ClusterMixin = {
  11761. /**
  11762. * This is only called in the constructor of the graph object
  11763. *
  11764. */
  11765. startWithClustering : function() {
  11766. // cluster if the data set is big
  11767. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11768. // updates the lables after clustering
  11769. this.updateLabels();
  11770. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11771. // the setData function.
  11772. if (this.stabilize) {
  11773. this._stabilize();
  11774. }
  11775. this.start();
  11776. },
  11777. /**
  11778. * This function clusters until the initialMaxNodes has been reached
  11779. *
  11780. * @param {Number} maxNumberOfNodes
  11781. * @param {Boolean} reposition
  11782. */
  11783. clusterToFit : function(maxNumberOfNodes, reposition) {
  11784. var numberOfNodes = this.nodeIndices.length;
  11785. var maxLevels = 50;
  11786. var level = 0;
  11787. // we first cluster the hubs, then we pull in the outliers, repeat
  11788. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11789. if (level % 3 == 0) {
  11790. this.forceAggregateHubs(true);
  11791. this.normalizeClusterLevels();
  11792. }
  11793. else {
  11794. this.increaseClusterLevel(); // this also includes a cluster normalization
  11795. }
  11796. numberOfNodes = this.nodeIndices.length;
  11797. level += 1;
  11798. }
  11799. // after the clustering we reposition the nodes to reduce the initial chaos
  11800. if (level > 0 && reposition == true) {
  11801. this.repositionNodes();
  11802. }
  11803. this._updateCalculationNodes();
  11804. },
  11805. /**
  11806. * This function can be called to open up a specific cluster. It is only called by
  11807. * It will unpack the cluster back one level.
  11808. *
  11809. * @param node | Node object: cluster to open.
  11810. */
  11811. openCluster : function(node) {
  11812. var isMovingBeforeClustering = this.moving;
  11813. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11814. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11815. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11816. this._addSector(node);
  11817. var level = 0;
  11818. // we decluster until we reach a decent number of nodes
  11819. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11820. this.decreaseClusterLevel();
  11821. level += 1;
  11822. }
  11823. }
  11824. else {
  11825. this._expandClusterNode(node,false,true);
  11826. // update the index list, dynamic edges and labels
  11827. this._updateNodeIndexList();
  11828. this._updateDynamicEdges();
  11829. this._updateCalculationNodes();
  11830. this.updateLabels();
  11831. }
  11832. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11833. if (this.moving != isMovingBeforeClustering) {
  11834. this.start();
  11835. }
  11836. },
  11837. /**
  11838. * This calls the updateClustes with default arguments
  11839. */
  11840. updateClustersDefault : function() {
  11841. if (this.constants.clustering.enabled == true) {
  11842. this.updateClusters(0,false,false);
  11843. }
  11844. },
  11845. /**
  11846. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11847. * be clustered with their connected node. This can be repeated as many times as needed.
  11848. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11849. */
  11850. increaseClusterLevel : function() {
  11851. this.updateClusters(-1,false,true);
  11852. },
  11853. /**
  11854. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11855. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11856. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11857. */
  11858. decreaseClusterLevel : function() {
  11859. this.updateClusters(1,false,true);
  11860. },
  11861. /**
  11862. * This is the main clustering function. It clusters and declusters on zoom or forced
  11863. * This function clusters on zoom, it can be called with a predefined zoom direction
  11864. * If out, check if we can form clusters, if in, check if we can open clusters.
  11865. * This function is only called from _zoom()
  11866. *
  11867. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11868. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11869. * @param {Boolean} force | enabled or disable forcing
  11870. * @param {Boolean} doNotStart | if true do not call start
  11871. *
  11872. */
  11873. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11874. var isMovingBeforeClustering = this.moving;
  11875. var amountOfNodes = this.nodeIndices.length;
  11876. // on zoom out collapse the sector if the scale is at the level the sector was made
  11877. if (this.previousScale > this.scale && zoomDirection == 0) {
  11878. this._collapseSector();
  11879. }
  11880. // check if we zoom in or out
  11881. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11882. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11883. // outer nodes determines if it is being clustered
  11884. this._formClusters(force);
  11885. }
  11886. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11887. if (force == true) {
  11888. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11889. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11890. this._openClusters(recursive,force);
  11891. }
  11892. else {
  11893. // if a cluster takes up a set percentage of the active window
  11894. this._openClustersBySize();
  11895. }
  11896. }
  11897. this._updateNodeIndexList();
  11898. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11899. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11900. this._aggregateHubs(force);
  11901. this._updateNodeIndexList();
  11902. }
  11903. // we now reduce chains.
  11904. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11905. this.handleChains();
  11906. this._updateNodeIndexList();
  11907. }
  11908. this.previousScale = this.scale;
  11909. // rest of the update the index list, dynamic edges and labels
  11910. this._updateDynamicEdges();
  11911. this.updateLabels();
  11912. // if a cluster was formed, we increase the clusterSession
  11913. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  11914. this.clusterSession += 1;
  11915. // if clusters have been made, we normalize the cluster level
  11916. this.normalizeClusterLevels();
  11917. }
  11918. if (doNotStart == false || doNotStart === undefined) {
  11919. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11920. if (this.moving != isMovingBeforeClustering) {
  11921. this.start();
  11922. }
  11923. }
  11924. this._updateCalculationNodes();
  11925. },
  11926. /**
  11927. * This function handles the chains. It is called on every updateClusters().
  11928. */
  11929. handleChains : function() {
  11930. // after clustering we check how many chains there are
  11931. var chainPercentage = this._getChainFraction();
  11932. if (chainPercentage > this.constants.clustering.chainThreshold) {
  11933. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  11934. }
  11935. },
  11936. /**
  11937. * this functions starts clustering by hubs
  11938. * The minimum hub threshold is set globally
  11939. *
  11940. * @private
  11941. */
  11942. _aggregateHubs : function(force) {
  11943. this._getHubSize();
  11944. this._formClustersByHub(force,false);
  11945. },
  11946. /**
  11947. * This function is fired by keypress. It forces hubs to form.
  11948. *
  11949. */
  11950. forceAggregateHubs : function(doNotStart) {
  11951. var isMovingBeforeClustering = this.moving;
  11952. var amountOfNodes = this.nodeIndices.length;
  11953. this._aggregateHubs(true);
  11954. // update the index list, dynamic edges and labels
  11955. this._updateNodeIndexList();
  11956. this._updateDynamicEdges();
  11957. this.updateLabels();
  11958. // if a cluster was formed, we increase the clusterSession
  11959. if (this.nodeIndices.length != amountOfNodes) {
  11960. this.clusterSession += 1;
  11961. }
  11962. if (doNotStart == false || doNotStart === undefined) {
  11963. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11964. if (this.moving != isMovingBeforeClustering) {
  11965. this.start();
  11966. }
  11967. }
  11968. },
  11969. /**
  11970. * If a cluster takes up more than a set percentage of the screen, open the cluster
  11971. *
  11972. * @private
  11973. */
  11974. _openClustersBySize : function() {
  11975. for (var nodeId in this.nodes) {
  11976. if (this.nodes.hasOwnProperty(nodeId)) {
  11977. var node = this.nodes[nodeId];
  11978. if (node.inView() == true) {
  11979. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11980. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11981. this.openCluster(node);
  11982. }
  11983. }
  11984. }
  11985. }
  11986. },
  11987. /**
  11988. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  11989. * has to be opened based on the current zoom level.
  11990. *
  11991. * @private
  11992. */
  11993. _openClusters : function(recursive,force) {
  11994. for (var i = 0; i < this.nodeIndices.length; i++) {
  11995. var node = this.nodes[this.nodeIndices[i]];
  11996. this._expandClusterNode(node,recursive,force);
  11997. this._updateCalculationNodes();
  11998. }
  11999. },
  12000. /**
  12001. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12002. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12003. * This recursive behaviour is optional and can be set by the recursive argument.
  12004. *
  12005. * @param {Node} parentNode | to check for cluster and expand
  12006. * @param {Boolean} recursive | enabled or disable recursive calling
  12007. * @param {Boolean} force | enabled or disable forcing
  12008. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12009. * @private
  12010. */
  12011. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12012. // first check if node is a cluster
  12013. if (parentNode.clusterSize > 1) {
  12014. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12015. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12016. openAll = true;
  12017. }
  12018. recursive = openAll ? true : recursive;
  12019. // if the last child has been added on a smaller scale than current scale decluster
  12020. if (parentNode.formationScale < this.scale || force == true) {
  12021. // we will check if any of the contained child nodes should be removed from the cluster
  12022. for (var containedNodeId in parentNode.containedNodes) {
  12023. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12024. var childNode = parentNode.containedNodes[containedNodeId];
  12025. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12026. // the largest cluster is the one that comes from outside
  12027. if (force == true) {
  12028. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12029. || openAll) {
  12030. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12031. }
  12032. }
  12033. else {
  12034. if (this._nodeInActiveArea(parentNode)) {
  12035. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12036. }
  12037. }
  12038. }
  12039. }
  12040. }
  12041. }
  12042. },
  12043. /**
  12044. * ONLY CALLED FROM _expandClusterNode
  12045. *
  12046. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12047. * the child node from the parent contained_node object and put it back into the global nodes object.
  12048. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12049. *
  12050. * @param {Node} parentNode | the parent node
  12051. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12052. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12053. * With force and recursive both true, the entire cluster is unpacked
  12054. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12055. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12056. * @private
  12057. */
  12058. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12059. var childNode = parentNode.containedNodes[containedNodeId];
  12060. // if child node has been added on smaller scale than current, kick out
  12061. if (childNode.formationScale < this.scale || force == true) {
  12062. // unselect all selected items
  12063. this._unselectAll();
  12064. // put the child node back in the global nodes object
  12065. this.nodes[containedNodeId] = childNode;
  12066. // release the contained edges from this childNode back into the global edges
  12067. this._releaseContainedEdges(parentNode,childNode);
  12068. // reconnect rerouted edges to the childNode
  12069. this._connectEdgeBackToChild(parentNode,childNode);
  12070. // validate all edges in dynamicEdges
  12071. this._validateEdges(parentNode);
  12072. // undo the changes from the clustering operation on the parent node
  12073. parentNode.mass -= childNode.mass;
  12074. parentNode.clusterSize -= childNode.clusterSize;
  12075. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12076. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12077. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12078. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12079. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12080. // remove node from the list
  12081. delete parentNode.containedNodes[containedNodeId];
  12082. // check if there are other childs with this clusterSession in the parent.
  12083. var othersPresent = false;
  12084. for (var childNodeId in parentNode.containedNodes) {
  12085. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12086. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12087. othersPresent = true;
  12088. break;
  12089. }
  12090. }
  12091. }
  12092. // if there are no others, remove the cluster session from the list
  12093. if (othersPresent == false) {
  12094. parentNode.clusterSessions.pop();
  12095. }
  12096. this._repositionBezierNodes(childNode);
  12097. // this._repositionBezierNodes(parentNode);
  12098. // remove the clusterSession from the child node
  12099. childNode.clusterSession = 0;
  12100. // recalculate the size of the node on the next time the node is rendered
  12101. parentNode.clearSizeCache();
  12102. // restart the simulation to reorganise all nodes
  12103. this.moving = true;
  12104. }
  12105. // check if a further expansion step is possible if recursivity is enabled
  12106. if (recursive == true) {
  12107. this._expandClusterNode(childNode,recursive,force,openAll);
  12108. }
  12109. },
  12110. /**
  12111. * position the bezier nodes at the center of the edges
  12112. *
  12113. * @param node
  12114. * @private
  12115. */
  12116. _repositionBezierNodes : function(node) {
  12117. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12118. node.dynamicEdges[i].positionBezierNode();
  12119. }
  12120. },
  12121. /**
  12122. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12123. * This function is called only from updateClusters()
  12124. * forceLevelCollapse ignores the length of the edge and collapses one level
  12125. * This means that a node with only one edge will be clustered with its connected node
  12126. *
  12127. * @private
  12128. * @param {Boolean} force
  12129. */
  12130. _formClusters : function(force) {
  12131. if (force == false) {
  12132. this._formClustersByZoom();
  12133. }
  12134. else {
  12135. this._forceClustersByZoom();
  12136. }
  12137. },
  12138. /**
  12139. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12140. *
  12141. * @private
  12142. */
  12143. _formClustersByZoom : function() {
  12144. var dx,dy,length,
  12145. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12146. // check if any edges are shorter than minLength and start the clustering
  12147. // the clustering favours the node with the larger mass
  12148. for (var edgeId in this.edges) {
  12149. if (this.edges.hasOwnProperty(edgeId)) {
  12150. var edge = this.edges[edgeId];
  12151. if (edge.connected) {
  12152. if (edge.toId != edge.fromId) {
  12153. dx = (edge.to.x - edge.from.x);
  12154. dy = (edge.to.y - edge.from.y);
  12155. length = Math.sqrt(dx * dx + dy * dy);
  12156. if (length < minLength) {
  12157. // first check which node is larger
  12158. var parentNode = edge.from;
  12159. var childNode = edge.to;
  12160. if (edge.to.mass > edge.from.mass) {
  12161. parentNode = edge.to;
  12162. childNode = edge.from;
  12163. }
  12164. if (childNode.dynamicEdgesLength == 1) {
  12165. this._addToCluster(parentNode,childNode,false);
  12166. }
  12167. else if (parentNode.dynamicEdgesLength == 1) {
  12168. this._addToCluster(childNode,parentNode,false);
  12169. }
  12170. }
  12171. }
  12172. }
  12173. }
  12174. }
  12175. },
  12176. /**
  12177. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12178. * connected node.
  12179. *
  12180. * @private
  12181. */
  12182. _forceClustersByZoom : function() {
  12183. for (var nodeId in this.nodes) {
  12184. // another node could have absorbed this child.
  12185. if (this.nodes.hasOwnProperty(nodeId)) {
  12186. var childNode = this.nodes[nodeId];
  12187. // the edges can be swallowed by another decrease
  12188. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12189. var edge = childNode.dynamicEdges[0];
  12190. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12191. // group to the largest node
  12192. if (childNode.id != parentNode.id) {
  12193. if (parentNode.mass > childNode.mass) {
  12194. this._addToCluster(parentNode,childNode,true);
  12195. }
  12196. else {
  12197. this._addToCluster(childNode,parentNode,true);
  12198. }
  12199. }
  12200. }
  12201. }
  12202. }
  12203. },
  12204. /**
  12205. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12206. * This function clusters a node to its smallest connected neighbour.
  12207. *
  12208. * @param node
  12209. * @private
  12210. */
  12211. _clusterToSmallestNeighbour : function(node) {
  12212. var smallestNeighbour = -1;
  12213. var smallestNeighbourNode = null;
  12214. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12215. if (node.dynamicEdges[i] !== undefined) {
  12216. var neighbour = null;
  12217. if (node.dynamicEdges[i].fromId != node.id) {
  12218. neighbour = node.dynamicEdges[i].from;
  12219. }
  12220. else if (node.dynamicEdges[i].toId != node.id) {
  12221. neighbour = node.dynamicEdges[i].to;
  12222. }
  12223. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12224. smallestNeighbour = neighbour.clusterSessions.length;
  12225. smallestNeighbourNode = neighbour;
  12226. }
  12227. }
  12228. }
  12229. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12230. this._addToCluster(neighbour, node, true);
  12231. }
  12232. },
  12233. /**
  12234. * This function forms clusters from hubs, it loops over all nodes
  12235. *
  12236. * @param {Boolean} force | Disregard zoom level
  12237. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12238. * @private
  12239. */
  12240. _formClustersByHub : function(force, onlyEqual) {
  12241. // we loop over all nodes in the list
  12242. for (var nodeId in this.nodes) {
  12243. // we check if it is still available since it can be used by the clustering in this loop
  12244. if (this.nodes.hasOwnProperty(nodeId)) {
  12245. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12246. }
  12247. }
  12248. },
  12249. /**
  12250. * This function forms a cluster from a specific preselected hub node
  12251. *
  12252. * @param {Node} hubNode | the node we will cluster as a hub
  12253. * @param {Boolean} force | Disregard zoom level
  12254. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12255. * @param {Number} [absorptionSizeOffset] |
  12256. * @private
  12257. */
  12258. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12259. if (absorptionSizeOffset === undefined) {
  12260. absorptionSizeOffset = 0;
  12261. }
  12262. // we decide if the node is a hub
  12263. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12264. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12265. // initialize variables
  12266. var dx,dy,length;
  12267. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12268. var allowCluster = false;
  12269. // we create a list of edges because the dynamicEdges change over the course of this loop
  12270. var edgesIdarray = [];
  12271. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12272. for (var j = 0; j < amountOfInitialEdges; j++) {
  12273. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12274. }
  12275. // if the hub clustering is not forces, we check if one of the edges connected
  12276. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12277. if (force == false) {
  12278. allowCluster = false;
  12279. for (j = 0; j < amountOfInitialEdges; j++) {
  12280. var edge = this.edges[edgesIdarray[j]];
  12281. if (edge !== undefined) {
  12282. if (edge.connected) {
  12283. if (edge.toId != edge.fromId) {
  12284. dx = (edge.to.x - edge.from.x);
  12285. dy = (edge.to.y - edge.from.y);
  12286. length = Math.sqrt(dx * dx + dy * dy);
  12287. if (length < minLength) {
  12288. allowCluster = true;
  12289. break;
  12290. }
  12291. }
  12292. }
  12293. }
  12294. }
  12295. }
  12296. // start the clustering if allowed
  12297. if ((!force && allowCluster) || force) {
  12298. // we loop over all edges INITIALLY connected to this hub
  12299. for (j = 0; j < amountOfInitialEdges; j++) {
  12300. edge = this.edges[edgesIdarray[j]];
  12301. // the edge can be clustered by this function in a previous loop
  12302. if (edge !== undefined) {
  12303. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12304. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12305. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12306. (childNode.id != hubNode.id)) {
  12307. this._addToCluster(hubNode,childNode,force);
  12308. }
  12309. }
  12310. }
  12311. }
  12312. }
  12313. },
  12314. /**
  12315. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12316. *
  12317. * @param {Node} parentNode | this is the node that will house the child node
  12318. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12319. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12320. * @private
  12321. */
  12322. _addToCluster : function(parentNode, childNode, force) {
  12323. // join child node in the parent node
  12324. parentNode.containedNodes[childNode.id] = childNode;
  12325. // manage all the edges connected to the child and parent nodes
  12326. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12327. var edge = childNode.dynamicEdges[i];
  12328. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12329. this._addToContainedEdges(parentNode,childNode,edge);
  12330. }
  12331. else {
  12332. this._connectEdgeToCluster(parentNode,childNode,edge);
  12333. }
  12334. }
  12335. // a contained node has no dynamic edges.
  12336. childNode.dynamicEdges = [];
  12337. // remove circular edges from clusters
  12338. this._containCircularEdgesFromNode(parentNode,childNode);
  12339. // remove the childNode from the global nodes object
  12340. delete this.nodes[childNode.id];
  12341. // update the properties of the child and parent
  12342. var massBefore = parentNode.mass;
  12343. childNode.clusterSession = this.clusterSession;
  12344. parentNode.mass += childNode.mass;
  12345. parentNode.clusterSize += childNode.clusterSize;
  12346. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12347. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12348. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12349. parentNode.clusterSessions.push(this.clusterSession);
  12350. }
  12351. // forced clusters only open from screen size and double tap
  12352. if (force == true) {
  12353. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12354. parentNode.formationScale = 0;
  12355. }
  12356. else {
  12357. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12358. }
  12359. // recalculate the size of the node on the next time the node is rendered
  12360. parentNode.clearSizeCache();
  12361. // set the pop-out scale for the childnode
  12362. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12363. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12364. childNode.clearVelocity();
  12365. // the mass has altered, preservation of energy dictates the velocity to be updated
  12366. parentNode.updateVelocity(massBefore);
  12367. // restart the simulation to reorganise all nodes
  12368. this.moving = true;
  12369. },
  12370. /**
  12371. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12372. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12373. * It has to be called if a level is collapsed. It is called by _formClusters().
  12374. * @private
  12375. */
  12376. _updateDynamicEdges : function() {
  12377. for (var i = 0; i < this.nodeIndices.length; i++) {
  12378. var node = this.nodes[this.nodeIndices[i]];
  12379. node.dynamicEdgesLength = node.dynamicEdges.length;
  12380. // this corrects for multiple edges pointing at the same other node
  12381. var correction = 0;
  12382. if (node.dynamicEdgesLength > 1) {
  12383. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12384. var edgeToId = node.dynamicEdges[j].toId;
  12385. var edgeFromId = node.dynamicEdges[j].fromId;
  12386. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12387. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12388. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12389. correction += 1;
  12390. }
  12391. }
  12392. }
  12393. }
  12394. node.dynamicEdgesLength -= correction;
  12395. }
  12396. },
  12397. /**
  12398. * This adds an edge from the childNode to the contained edges of the parent node
  12399. *
  12400. * @param parentNode | Node object
  12401. * @param childNode | Node object
  12402. * @param edge | Edge object
  12403. * @private
  12404. */
  12405. _addToContainedEdges : function(parentNode, childNode, edge) {
  12406. // create an array object if it does not yet exist for this childNode
  12407. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12408. parentNode.containedEdges[childNode.id] = []
  12409. }
  12410. // add this edge to the list
  12411. parentNode.containedEdges[childNode.id].push(edge);
  12412. // remove the edge from the global edges object
  12413. delete this.edges[edge.id];
  12414. // remove the edge from the parent object
  12415. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12416. if (parentNode.dynamicEdges[i].id == edge.id) {
  12417. parentNode.dynamicEdges.splice(i,1);
  12418. break;
  12419. }
  12420. }
  12421. },
  12422. /**
  12423. * This function connects an edge that was connected to a child node to the parent node.
  12424. * It keeps track of which nodes it has been connected to with the originalId array.
  12425. *
  12426. * @param {Node} parentNode | Node object
  12427. * @param {Node} childNode | Node object
  12428. * @param {Edge} edge | Edge object
  12429. * @private
  12430. */
  12431. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12432. // handle circular edges
  12433. if (edge.toId == edge.fromId) {
  12434. this._addToContainedEdges(parentNode, childNode, edge);
  12435. }
  12436. else {
  12437. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12438. edge.originalToId.push(childNode.id);
  12439. edge.to = parentNode;
  12440. edge.toId = parentNode.id;
  12441. }
  12442. else { // edge connected to other node with the "from" side
  12443. edge.originalFromId.push(childNode.id);
  12444. edge.from = parentNode;
  12445. edge.fromId = parentNode.id;
  12446. }
  12447. this._addToReroutedEdges(parentNode,childNode,edge);
  12448. }
  12449. },
  12450. /**
  12451. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12452. * these edges inside of the cluster.
  12453. *
  12454. * @param parentNode
  12455. * @param childNode
  12456. * @private
  12457. */
  12458. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12459. // manage all the edges connected to the child and parent nodes
  12460. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12461. var edge = parentNode.dynamicEdges[i];
  12462. // handle circular edges
  12463. if (edge.toId == edge.fromId) {
  12464. this._addToContainedEdges(parentNode, childNode, edge);
  12465. }
  12466. }
  12467. },
  12468. /**
  12469. * This adds an edge from the childNode to the rerouted edges of the parent node
  12470. *
  12471. * @param parentNode | Node object
  12472. * @param childNode | Node object
  12473. * @param edge | Edge object
  12474. * @private
  12475. */
  12476. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12477. // create an array object if it does not yet exist for this childNode
  12478. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12479. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12480. parentNode.reroutedEdges[childNode.id] = [];
  12481. }
  12482. parentNode.reroutedEdges[childNode.id].push(edge);
  12483. // this edge becomes part of the dynamicEdges of the cluster node
  12484. parentNode.dynamicEdges.push(edge);
  12485. },
  12486. /**
  12487. * This function connects an edge that was connected to a cluster node back to the child node.
  12488. *
  12489. * @param parentNode | Node object
  12490. * @param childNode | Node object
  12491. * @private
  12492. */
  12493. _connectEdgeBackToChild : function(parentNode, childNode) {
  12494. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12495. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12496. var edge = parentNode.reroutedEdges[childNode.id][i];
  12497. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12498. edge.originalFromId.pop();
  12499. edge.fromId = childNode.id;
  12500. edge.from = childNode;
  12501. }
  12502. else {
  12503. edge.originalToId.pop();
  12504. edge.toId = childNode.id;
  12505. edge.to = childNode;
  12506. }
  12507. // append this edge to the list of edges connecting to the childnode
  12508. childNode.dynamicEdges.push(edge);
  12509. // remove the edge from the parent object
  12510. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12511. if (parentNode.dynamicEdges[j].id == edge.id) {
  12512. parentNode.dynamicEdges.splice(j,1);
  12513. break;
  12514. }
  12515. }
  12516. }
  12517. // remove the entry from the rerouted edges
  12518. delete parentNode.reroutedEdges[childNode.id];
  12519. }
  12520. },
  12521. /**
  12522. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12523. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12524. * parentNode
  12525. *
  12526. * @param parentNode | Node object
  12527. * @private
  12528. */
  12529. _validateEdges : function(parentNode) {
  12530. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12531. var edge = parentNode.dynamicEdges[i];
  12532. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12533. parentNode.dynamicEdges.splice(i,1);
  12534. }
  12535. }
  12536. },
  12537. /**
  12538. * This function released the contained edges back into the global domain and puts them back into the
  12539. * dynamic edges of both parent and child.
  12540. *
  12541. * @param {Node} parentNode |
  12542. * @param {Node} childNode |
  12543. * @private
  12544. */
  12545. _releaseContainedEdges : function(parentNode, childNode) {
  12546. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12547. var edge = parentNode.containedEdges[childNode.id][i];
  12548. // put the edge back in the global edges object
  12549. this.edges[edge.id] = edge;
  12550. // put the edge back in the dynamic edges of the child and parent
  12551. childNode.dynamicEdges.push(edge);
  12552. parentNode.dynamicEdges.push(edge);
  12553. }
  12554. // remove the entry from the contained edges
  12555. delete parentNode.containedEdges[childNode.id];
  12556. },
  12557. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12558. /**
  12559. * This updates the node labels for all nodes (for debugging purposes)
  12560. */
  12561. updateLabels : function() {
  12562. var nodeId;
  12563. // update node labels
  12564. for (nodeId in this.nodes) {
  12565. if (this.nodes.hasOwnProperty(nodeId)) {
  12566. var node = this.nodes[nodeId];
  12567. if (node.clusterSize > 1) {
  12568. node.label = "[".concat(String(node.clusterSize),"]");
  12569. }
  12570. }
  12571. }
  12572. // update node labels
  12573. for (nodeId in this.nodes) {
  12574. if (this.nodes.hasOwnProperty(nodeId)) {
  12575. node = this.nodes[nodeId];
  12576. if (node.clusterSize == 1) {
  12577. if (node.originalLabel !== undefined) {
  12578. node.label = node.originalLabel;
  12579. }
  12580. else {
  12581. node.label = String(node.id);
  12582. }
  12583. }
  12584. }
  12585. }
  12586. // /* Debug Override */
  12587. // for (nodeId in this.nodes) {
  12588. // if (this.nodes.hasOwnProperty(nodeId)) {
  12589. // node = this.nodes[nodeId];
  12590. // node.label = String(node.level);
  12591. // }
  12592. // }
  12593. },
  12594. /**
  12595. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12596. * if the rest of the nodes are already a few cluster levels in.
  12597. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12598. * clustered enough to the clusterToSmallestNeighbours function.
  12599. */
  12600. normalizeClusterLevels : function() {
  12601. var maxLevel = 0;
  12602. var minLevel = 1e9;
  12603. var clusterLevel = 0;
  12604. var nodeId;
  12605. // we loop over all nodes in the list
  12606. for (nodeId in this.nodes) {
  12607. if (this.nodes.hasOwnProperty(nodeId)) {
  12608. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12609. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12610. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12611. }
  12612. }
  12613. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12614. var amountOfNodes = this.nodeIndices.length;
  12615. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12616. // we loop over all nodes in the list
  12617. for (nodeId in this.nodes) {
  12618. if (this.nodes.hasOwnProperty(nodeId)) {
  12619. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12620. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12621. }
  12622. }
  12623. }
  12624. this._updateNodeIndexList();
  12625. this._updateDynamicEdges();
  12626. // if a cluster was formed, we increase the clusterSession
  12627. if (this.nodeIndices.length != amountOfNodes) {
  12628. this.clusterSession += 1;
  12629. }
  12630. }
  12631. },
  12632. /**
  12633. * This function determines if the cluster we want to decluster is in the active area
  12634. * this means around the zoom center
  12635. *
  12636. * @param {Node} node
  12637. * @returns {boolean}
  12638. * @private
  12639. */
  12640. _nodeInActiveArea : function(node) {
  12641. return (
  12642. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12643. &&
  12644. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12645. )
  12646. },
  12647. /**
  12648. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12649. * It puts large clusters away from the center and randomizes the order.
  12650. *
  12651. */
  12652. repositionNodes : function() {
  12653. for (var i = 0; i < this.nodeIndices.length; i++) {
  12654. var node = this.nodes[this.nodeIndices[i]];
  12655. if ((node.xFixed == false || node.yFixed == false)) {
  12656. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12657. var angle = 2 * Math.PI * Math.random();
  12658. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12659. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12660. this._repositionBezierNodes(node);
  12661. }
  12662. }
  12663. },
  12664. /**
  12665. * We determine how many connections denote an important hub.
  12666. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12667. *
  12668. * @private
  12669. */
  12670. _getHubSize : function() {
  12671. var average = 0;
  12672. var averageSquared = 0;
  12673. var hubCounter = 0;
  12674. var largestHub = 0;
  12675. for (var i = 0; i < this.nodeIndices.length; i++) {
  12676. var node = this.nodes[this.nodeIndices[i]];
  12677. if (node.dynamicEdgesLength > largestHub) {
  12678. largestHub = node.dynamicEdgesLength;
  12679. }
  12680. average += node.dynamicEdgesLength;
  12681. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12682. hubCounter += 1;
  12683. }
  12684. average = average / hubCounter;
  12685. averageSquared = averageSquared / hubCounter;
  12686. var variance = averageSquared - Math.pow(average,2);
  12687. var standardDeviation = Math.sqrt(variance);
  12688. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12689. // always have at least one to cluster
  12690. if (this.hubThreshold > largestHub) {
  12691. this.hubThreshold = largestHub;
  12692. }
  12693. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12694. // console.log("hubThreshold:",this.hubThreshold);
  12695. },
  12696. /**
  12697. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12698. * with this amount we can cluster specifically on these chains.
  12699. *
  12700. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12701. * @private
  12702. */
  12703. _reduceAmountOfChains : function(fraction) {
  12704. this.hubThreshold = 2;
  12705. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12706. for (var nodeId in this.nodes) {
  12707. if (this.nodes.hasOwnProperty(nodeId)) {
  12708. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12709. if (reduceAmount > 0) {
  12710. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12711. reduceAmount -= 1;
  12712. }
  12713. }
  12714. }
  12715. }
  12716. },
  12717. /**
  12718. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12719. * with this amount we can cluster specifically on these chains.
  12720. *
  12721. * @private
  12722. */
  12723. _getChainFraction : function() {
  12724. var chains = 0;
  12725. var total = 0;
  12726. for (var nodeId in this.nodes) {
  12727. if (this.nodes.hasOwnProperty(nodeId)) {
  12728. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12729. chains += 1;
  12730. }
  12731. total += 1;
  12732. }
  12733. }
  12734. return chains/total;
  12735. }
  12736. };
  12737. var SelectionMixin = {
  12738. /**
  12739. * This function can be called from the _doInAllSectors function
  12740. *
  12741. * @param object
  12742. * @param overlappingNodes
  12743. * @private
  12744. */
  12745. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12746. var nodes = this.nodes;
  12747. for (var nodeId in nodes) {
  12748. if (nodes.hasOwnProperty(nodeId)) {
  12749. if (nodes[nodeId].isOverlappingWith(object)) {
  12750. overlappingNodes.push(nodeId);
  12751. }
  12752. }
  12753. }
  12754. },
  12755. /**
  12756. * retrieve all nodes overlapping with given object
  12757. * @param {Object} object An object with parameters left, top, right, bottom
  12758. * @return {Number[]} An array with id's of the overlapping nodes
  12759. * @private
  12760. */
  12761. _getAllNodesOverlappingWith : function (object) {
  12762. var overlappingNodes = [];
  12763. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12764. return overlappingNodes;
  12765. },
  12766. /**
  12767. * Return a position object in canvasspace from a single point in screenspace
  12768. *
  12769. * @param pointer
  12770. * @returns {{left: number, top: number, right: number, bottom: number}}
  12771. * @private
  12772. */
  12773. _pointerToPositionObject : function(pointer) {
  12774. var x = this._canvasToX(pointer.x);
  12775. var y = this._canvasToY(pointer.y);
  12776. return {left: x,
  12777. top: y,
  12778. right: x,
  12779. bottom: y};
  12780. },
  12781. /**
  12782. * Get the top node at the a specific point (like a click)
  12783. *
  12784. * @param {{x: Number, y: Number}} pointer
  12785. * @return {Node | null} node
  12786. * @private
  12787. */
  12788. _getNodeAt : function (pointer) {
  12789. // we first check if this is an navigation controls element
  12790. var positionObject = this._pointerToPositionObject(pointer);
  12791. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12792. // if there are overlapping nodes, select the last one, this is the
  12793. // one which is drawn on top of the others
  12794. if (overlappingNodes.length > 0) {
  12795. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12796. }
  12797. else {
  12798. return null;
  12799. }
  12800. },
  12801. /**
  12802. * retrieve all edges overlapping with given object, selector is around center
  12803. * @param {Object} object An object with parameters left, top, right, bottom
  12804. * @return {Number[]} An array with id's of the overlapping nodes
  12805. * @private
  12806. */
  12807. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12808. var edges = this.edges;
  12809. for (var edgeId in edges) {
  12810. if (edges.hasOwnProperty(edgeId)) {
  12811. if (edges[edgeId].isOverlappingWith(object)) {
  12812. overlappingEdges.push(edgeId);
  12813. }
  12814. }
  12815. }
  12816. },
  12817. /**
  12818. * retrieve all nodes overlapping with given object
  12819. * @param {Object} object An object with parameters left, top, right, bottom
  12820. * @return {Number[]} An array with id's of the overlapping nodes
  12821. * @private
  12822. */
  12823. _getAllEdgesOverlappingWith : function (object) {
  12824. var overlappingEdges = [];
  12825. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12826. return overlappingEdges;
  12827. },
  12828. /**
  12829. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12830. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12831. *
  12832. * @param pointer
  12833. * @returns {null}
  12834. * @private
  12835. */
  12836. _getEdgeAt : function(pointer) {
  12837. var positionObject = this._pointerToPositionObject(pointer);
  12838. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12839. if (overlappingEdges.length > 0) {
  12840. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12841. }
  12842. else {
  12843. return null;
  12844. }
  12845. },
  12846. /**
  12847. * Add object to the selection array.
  12848. *
  12849. * @param obj
  12850. * @private
  12851. */
  12852. _addToSelection : function(obj) {
  12853. if (obj instanceof Node) {
  12854. this.selectionObj.nodes[obj.id] = obj;
  12855. }
  12856. else {
  12857. this.selectionObj.edges[obj.id] = obj;
  12858. }
  12859. },
  12860. /**
  12861. * Remove a single option from selection.
  12862. *
  12863. * @param {Object} obj
  12864. * @private
  12865. */
  12866. _removeFromSelection : function(obj) {
  12867. if (obj instanceof Node) {
  12868. delete this.selectionObj.nodes[obj.id];
  12869. }
  12870. else {
  12871. delete this.selectionObj.edges[obj.id];
  12872. }
  12873. },
  12874. /**
  12875. * Unselect all. The selectionObj is useful for this.
  12876. *
  12877. * @param {Boolean} [doNotTrigger] | ignore trigger
  12878. * @private
  12879. */
  12880. _unselectAll : function(doNotTrigger) {
  12881. if (doNotTrigger === undefined) {
  12882. doNotTrigger = false;
  12883. }
  12884. for(var nodeId in this.selectionObj.nodes) {
  12885. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12886. this.selectionObj.nodes[nodeId].unselect();
  12887. }
  12888. }
  12889. for(var edgeId in this.selectionObj.edges) {
  12890. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12891. this.selectionObj.edges[edgeId].unselect();
  12892. }
  12893. }
  12894. this.selectionObj = {nodes:{},edges:{}};
  12895. if (doNotTrigger == false) {
  12896. this.emit('select', this.getSelection());
  12897. }
  12898. },
  12899. /**
  12900. * Unselect all clusters. The selectionObj is useful for this.
  12901. *
  12902. * @param {Boolean} [doNotTrigger] | ignore trigger
  12903. * @private
  12904. */
  12905. _unselectClusters : function(doNotTrigger) {
  12906. if (doNotTrigger === undefined) {
  12907. doNotTrigger = false;
  12908. }
  12909. for (var nodeId in this.selectionObj.nodes) {
  12910. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12911. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12912. this.selectionObj.nodes[nodeId].unselect();
  12913. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  12914. }
  12915. }
  12916. }
  12917. if (doNotTrigger == false) {
  12918. this.emit('select', this.getSelection());
  12919. }
  12920. },
  12921. /**
  12922. * return the number of selected nodes
  12923. *
  12924. * @returns {number}
  12925. * @private
  12926. */
  12927. _getSelectedNodeCount : function() {
  12928. var count = 0;
  12929. for (var nodeId in this.selectionObj.nodes) {
  12930. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12931. count += 1;
  12932. }
  12933. }
  12934. return count;
  12935. },
  12936. /**
  12937. * return the number of selected nodes
  12938. *
  12939. * @returns {number}
  12940. * @private
  12941. */
  12942. _getSelectedNode : function() {
  12943. for (var nodeId in this.selectionObj.nodes) {
  12944. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12945. return this.selectionObj.nodes[nodeId];
  12946. }
  12947. }
  12948. return null;
  12949. },
  12950. /**
  12951. * return the number of selected edges
  12952. *
  12953. * @returns {number}
  12954. * @private
  12955. */
  12956. _getSelectedEdgeCount : function() {
  12957. var count = 0;
  12958. for (var edgeId in this.selectionObj.edges) {
  12959. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12960. count += 1;
  12961. }
  12962. }
  12963. return count;
  12964. },
  12965. /**
  12966. * return the number of selected objects.
  12967. *
  12968. * @returns {number}
  12969. * @private
  12970. */
  12971. _getSelectedObjectCount : function() {
  12972. var count = 0;
  12973. for(var nodeId in this.selectionObj.nodes) {
  12974. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12975. count += 1;
  12976. }
  12977. }
  12978. for(var edgeId in this.selectionObj.edges) {
  12979. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12980. count += 1;
  12981. }
  12982. }
  12983. return count;
  12984. },
  12985. /**
  12986. * Check if anything is selected
  12987. *
  12988. * @returns {boolean}
  12989. * @private
  12990. */
  12991. _selectionIsEmpty : function() {
  12992. for(var nodeId in this.selectionObj.nodes) {
  12993. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12994. return false;
  12995. }
  12996. }
  12997. for(var edgeId in this.selectionObj.edges) {
  12998. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12999. return false;
  13000. }
  13001. }
  13002. return true;
  13003. },
  13004. /**
  13005. * check if one of the selected nodes is a cluster.
  13006. *
  13007. * @returns {boolean}
  13008. * @private
  13009. */
  13010. _clusterInSelection : function() {
  13011. for(var nodeId in this.selectionObj.nodes) {
  13012. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13013. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13014. return true;
  13015. }
  13016. }
  13017. }
  13018. return false;
  13019. },
  13020. /**
  13021. * select the edges connected to the node that is being selected
  13022. *
  13023. * @param {Node} node
  13024. * @private
  13025. */
  13026. _selectConnectedEdges : function(node) {
  13027. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13028. var edge = node.dynamicEdges[i];
  13029. edge.select();
  13030. this._addToSelection(edge);
  13031. }
  13032. },
  13033. /**
  13034. * unselect the edges connected to the node that is being selected
  13035. *
  13036. * @param {Node} node
  13037. * @private
  13038. */
  13039. _unselectConnectedEdges : function(node) {
  13040. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13041. var edge = node.dynamicEdges[i];
  13042. edge.unselect();
  13043. this._removeFromSelection(edge);
  13044. }
  13045. },
  13046. /**
  13047. * This is called when someone clicks on a node. either select or deselect it.
  13048. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13049. *
  13050. * @param {Node || Edge} object
  13051. * @param {Boolean} append
  13052. * @param {Boolean} [doNotTrigger] | ignore trigger
  13053. * @private
  13054. */
  13055. _selectObject : function(object, append, doNotTrigger) {
  13056. if (doNotTrigger === undefined) {
  13057. doNotTrigger = false;
  13058. }
  13059. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13060. this._unselectAll(true);
  13061. }
  13062. if (object.selected == false) {
  13063. object.select();
  13064. this._addToSelection(object);
  13065. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13066. this._selectConnectedEdges(object);
  13067. }
  13068. }
  13069. else {
  13070. object.unselect();
  13071. this._removeFromSelection(object);
  13072. }
  13073. if (doNotTrigger == false) {
  13074. this.emit('select', this.getSelection());
  13075. }
  13076. },
  13077. /**
  13078. * handles the selection part of the touch, only for navigation controls elements;
  13079. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13080. * This is the most responsive solution
  13081. *
  13082. * @param {Object} pointer
  13083. * @private
  13084. */
  13085. _handleTouch : function(pointer) {
  13086. },
  13087. /**
  13088. * handles the selection part of the tap;
  13089. *
  13090. * @param {Object} pointer
  13091. * @private
  13092. */
  13093. _handleTap : function(pointer) {
  13094. var node = this._getNodeAt(pointer);
  13095. if (node != null) {
  13096. this._selectObject(node,false);
  13097. }
  13098. else {
  13099. var edge = this._getEdgeAt(pointer);
  13100. if (edge != null) {
  13101. this._selectObject(edge,false);
  13102. }
  13103. else {
  13104. this._unselectAll();
  13105. }
  13106. }
  13107. this.emit("click", this.getSelection());
  13108. this._redraw();
  13109. },
  13110. /**
  13111. * handles the selection part of the double tap and opens a cluster if needed
  13112. *
  13113. * @param {Object} pointer
  13114. * @private
  13115. */
  13116. _handleDoubleTap : function(pointer) {
  13117. var node = this._getNodeAt(pointer);
  13118. if (node != null && node !== undefined) {
  13119. // we reset the areaCenter here so the opening of the node will occur
  13120. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13121. "y" : this._canvasToY(pointer.y)};
  13122. this.openCluster(node);
  13123. }
  13124. this.emit("doubleClick", this.getSelection());
  13125. },
  13126. /**
  13127. * Handle the onHold selection part
  13128. *
  13129. * @param pointer
  13130. * @private
  13131. */
  13132. _handleOnHold : function(pointer) {
  13133. var node = this._getNodeAt(pointer);
  13134. if (node != null) {
  13135. this._selectObject(node,true);
  13136. }
  13137. else {
  13138. var edge = this._getEdgeAt(pointer);
  13139. if (edge != null) {
  13140. this._selectObject(edge,true);
  13141. }
  13142. }
  13143. this._redraw();
  13144. },
  13145. /**
  13146. * handle the onRelease event. These functions are here for the navigation controls module.
  13147. *
  13148. * @private
  13149. */
  13150. _handleOnRelease : function(pointer) {
  13151. },
  13152. /**
  13153. *
  13154. * retrieve the currently selected objects
  13155. * @return {Number[] | String[]} selection An array with the ids of the
  13156. * selected nodes.
  13157. */
  13158. getSelection : function() {
  13159. var nodeIds = this.getSelectedNodes();
  13160. var edgeIds = this.getSelectedEdges();
  13161. return {nodes:nodeIds, edges:edgeIds};
  13162. },
  13163. /**
  13164. *
  13165. * retrieve the currently selected nodes
  13166. * @return {String} selection An array with the ids of the
  13167. * selected nodes.
  13168. */
  13169. getSelectedNodes : function() {
  13170. var idArray = [];
  13171. for(var nodeId in this.selectionObj.nodes) {
  13172. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13173. idArray.push(nodeId);
  13174. }
  13175. }
  13176. return idArray
  13177. },
  13178. /**
  13179. *
  13180. * retrieve the currently selected edges
  13181. * @return {Array} selection An array with the ids of the
  13182. * selected nodes.
  13183. */
  13184. getSelectedEdges : function() {
  13185. var idArray = [];
  13186. for(var edgeId in this.selectionObj.edges) {
  13187. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13188. idArray.push(edgeId);
  13189. }
  13190. }
  13191. return idArray;
  13192. },
  13193. /**
  13194. * select zero or more nodes
  13195. * @param {Number[] | String[]} selection An array with the ids of the
  13196. * selected nodes.
  13197. */
  13198. setSelection : function(selection) {
  13199. var i, iMax, id;
  13200. if (!selection || (selection.length == undefined))
  13201. throw 'Selection must be an array with ids';
  13202. // first unselect any selected node
  13203. this._unselectAll(true);
  13204. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13205. id = selection[i];
  13206. var node = this.nodes[id];
  13207. if (!node) {
  13208. throw new RangeError('Node with id "' + id + '" not found');
  13209. }
  13210. this._selectObject(node,true,true);
  13211. }
  13212. this.redraw();
  13213. },
  13214. /**
  13215. * Validate the selection: remove ids of nodes which no longer exist
  13216. * @private
  13217. */
  13218. _updateSelection : function () {
  13219. for(var nodeId in this.selectionObj.nodes) {
  13220. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13221. if (!this.nodes.hasOwnProperty(nodeId)) {
  13222. delete this.selectionObj.nodes[nodeId];
  13223. }
  13224. }
  13225. }
  13226. for(var edgeId in this.selectionObj.edges) {
  13227. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13228. if (!this.edges.hasOwnProperty(edgeId)) {
  13229. delete this.selectionObj.edges[edgeId];
  13230. }
  13231. }
  13232. }
  13233. }
  13234. };
  13235. /**
  13236. * Created by Alex on 1/22/14.
  13237. */
  13238. var NavigationMixin = {
  13239. _cleanNavigation : function() {
  13240. // clean up previosu navigation items
  13241. var wrapper = document.getElementById('graph-navigation_wrapper');
  13242. if (wrapper != null) {
  13243. this.containerElement.removeChild(wrapper);
  13244. }
  13245. document.onmouseup = null;
  13246. },
  13247. /**
  13248. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13249. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13250. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13251. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13252. *
  13253. * @private
  13254. */
  13255. _loadNavigationElements : function() {
  13256. this._cleanNavigation();
  13257. this.navigationDivs = {};
  13258. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13259. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13260. this.navigationDivs['wrapper'] = document.createElement('div');
  13261. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13262. this.navigationDivs['wrapper'].style.position = "absolute";
  13263. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13264. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13265. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13266. for (var i = 0; i < navigationDivs.length; i++) {
  13267. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13268. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13269. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13270. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13271. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13272. }
  13273. document.onmouseup = this._stopMovement.bind(this);
  13274. },
  13275. /**
  13276. * this stops all movement induced by the navigation buttons
  13277. *
  13278. * @private
  13279. */
  13280. _stopMovement : function() {
  13281. this._xStopMoving();
  13282. this._yStopMoving();
  13283. this._stopZoom();
  13284. },
  13285. /**
  13286. * stops the actions performed by page up and down etc.
  13287. *
  13288. * @param event
  13289. * @private
  13290. */
  13291. _preventDefault : function(event) {
  13292. if (event !== undefined) {
  13293. if (event.preventDefault) {
  13294. event.preventDefault();
  13295. } else {
  13296. event.returnValue = false;
  13297. }
  13298. }
  13299. },
  13300. /**
  13301. * move the screen up
  13302. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13303. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13304. * To avoid this behaviour, we do the translation in the start loop.
  13305. *
  13306. * @private
  13307. */
  13308. _moveUp : function(event) {
  13309. this.yIncrement = this.constants.keyboard.speed.y;
  13310. this.start(); // if there is no node movement, the calculation wont be done
  13311. this._preventDefault(event);
  13312. if (this.navigationDivs) {
  13313. this.navigationDivs['up'].className += " active";
  13314. }
  13315. },
  13316. /**
  13317. * move the screen down
  13318. * @private
  13319. */
  13320. _moveDown : function(event) {
  13321. this.yIncrement = -this.constants.keyboard.speed.y;
  13322. this.start(); // if there is no node movement, the calculation wont be done
  13323. this._preventDefault(event);
  13324. if (this.navigationDivs) {
  13325. this.navigationDivs['down'].className += " active";
  13326. }
  13327. },
  13328. /**
  13329. * move the screen left
  13330. * @private
  13331. */
  13332. _moveLeft : function(event) {
  13333. this.xIncrement = this.constants.keyboard.speed.x;
  13334. this.start(); // if there is no node movement, the calculation wont be done
  13335. this._preventDefault(event);
  13336. if (this.navigationDivs) {
  13337. this.navigationDivs['left'].className += " active";
  13338. }
  13339. },
  13340. /**
  13341. * move the screen right
  13342. * @private
  13343. */
  13344. _moveRight : function(event) {
  13345. this.xIncrement = -this.constants.keyboard.speed.y;
  13346. this.start(); // if there is no node movement, the calculation wont be done
  13347. this._preventDefault(event);
  13348. if (this.navigationDivs) {
  13349. this.navigationDivs['right'].className += " active";
  13350. }
  13351. },
  13352. /**
  13353. * Zoom in, using the same method as the movement.
  13354. * @private
  13355. */
  13356. _zoomIn : function(event) {
  13357. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13358. this.start(); // if there is no node movement, the calculation wont be done
  13359. this._preventDefault(event);
  13360. if (this.navigationDivs) {
  13361. this.navigationDivs['zoomIn'].className += " active";
  13362. }
  13363. },
  13364. /**
  13365. * Zoom out
  13366. * @private
  13367. */
  13368. _zoomOut : function() {
  13369. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13370. this.start(); // if there is no node movement, the calculation wont be done
  13371. this._preventDefault(event);
  13372. if (this.navigationDivs) {
  13373. this.navigationDivs['zoomOut'].className += " active";
  13374. }
  13375. },
  13376. /**
  13377. * Stop zooming and unhighlight the zoom controls
  13378. * @private
  13379. */
  13380. _stopZoom : function() {
  13381. this.zoomIncrement = 0;
  13382. if (this.navigationDivs) {
  13383. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13384. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13385. }
  13386. },
  13387. /**
  13388. * Stop moving in the Y direction and unHighlight the up and down
  13389. * @private
  13390. */
  13391. _yStopMoving : function() {
  13392. this.yIncrement = 0;
  13393. if (this.navigationDivs) {
  13394. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13395. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13396. }
  13397. },
  13398. /**
  13399. * Stop moving in the X direction and unHighlight left and right.
  13400. * @private
  13401. */
  13402. _xStopMoving : function() {
  13403. this.xIncrement = 0;
  13404. if (this.navigationDivs) {
  13405. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13406. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13407. }
  13408. }
  13409. };
  13410. /**
  13411. * Created by Alex on 2/10/14.
  13412. */
  13413. var graphMixinLoaders = {
  13414. /**
  13415. * Load a mixin into the graph object
  13416. *
  13417. * @param {Object} sourceVariable | this object has to contain functions.
  13418. * @private
  13419. */
  13420. _loadMixin: function (sourceVariable) {
  13421. for (var mixinFunction in sourceVariable) {
  13422. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13423. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13424. }
  13425. }
  13426. },
  13427. /**
  13428. * removes a mixin from the graph object.
  13429. *
  13430. * @param {Object} sourceVariable | this object has to contain functions.
  13431. * @private
  13432. */
  13433. _clearMixin: function (sourceVariable) {
  13434. for (var mixinFunction in sourceVariable) {
  13435. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13436. Graph.prototype[mixinFunction] = undefined;
  13437. }
  13438. }
  13439. },
  13440. /**
  13441. * Mixin the physics system and initialize the parameters required.
  13442. *
  13443. * @private
  13444. */
  13445. _loadPhysicsSystem: function () {
  13446. this._loadMixin(physicsMixin);
  13447. this._loadSelectedForceSolver();
  13448. if (this.constants.configurePhysics == true) {
  13449. this._loadPhysicsConfiguration();
  13450. }
  13451. },
  13452. /**
  13453. * Mixin the cluster system and initialize the parameters required.
  13454. *
  13455. * @private
  13456. */
  13457. _loadClusterSystem: function () {
  13458. this.clusterSession = 0;
  13459. this.hubThreshold = 5;
  13460. this._loadMixin(ClusterMixin);
  13461. },
  13462. /**
  13463. * Mixin the sector system and initialize the parameters required
  13464. *
  13465. * @private
  13466. */
  13467. _loadSectorSystem: function () {
  13468. this.sectors = {};
  13469. this.activeSector = ["default"];
  13470. this.sectors["active"] = {};
  13471. this.sectors["active"]["default"] = {"nodes": {},
  13472. "edges": {},
  13473. "nodeIndices": [],
  13474. "formationScale": 1.0,
  13475. "drawingNode": undefined };
  13476. this.sectors["frozen"] = {};
  13477. this.sectors["support"] = {"nodes": {},
  13478. "edges": {},
  13479. "nodeIndices": [],
  13480. "formationScale": 1.0,
  13481. "drawingNode": undefined };
  13482. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13483. this._loadMixin(SectorMixin);
  13484. },
  13485. /**
  13486. * Mixin the selection system and initialize the parameters required
  13487. *
  13488. * @private
  13489. */
  13490. _loadSelectionSystem: function () {
  13491. this.selectionObj = {nodes: {}, edges: {}};
  13492. this._loadMixin(SelectionMixin);
  13493. },
  13494. /**
  13495. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13496. *
  13497. * @private
  13498. */
  13499. _loadManipulationSystem: function () {
  13500. // reset global variables -- these are used by the selection of nodes and edges.
  13501. this.blockConnectingEdgeSelection = false;
  13502. this.forceAppendSelection = false;
  13503. if (this.constants.dataManipulation.enabled == true) {
  13504. // load the manipulator HTML elements. All styling done in css.
  13505. if (this.manipulationDiv === undefined) {
  13506. this.manipulationDiv = document.createElement('div');
  13507. this.manipulationDiv.className = 'graph-manipulationDiv';
  13508. this.manipulationDiv.id = 'graph-manipulationDiv';
  13509. if (this.editMode == true) {
  13510. this.manipulationDiv.style.display = "block";
  13511. }
  13512. else {
  13513. this.manipulationDiv.style.display = "none";
  13514. }
  13515. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13516. }
  13517. if (this.editModeDiv === undefined) {
  13518. this.editModeDiv = document.createElement('div');
  13519. this.editModeDiv.className = 'graph-manipulation-editMode';
  13520. this.editModeDiv.id = 'graph-manipulation-editMode';
  13521. if (this.editMode == true) {
  13522. this.editModeDiv.style.display = "none";
  13523. }
  13524. else {
  13525. this.editModeDiv.style.display = "block";
  13526. }
  13527. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13528. }
  13529. if (this.closeDiv === undefined) {
  13530. this.closeDiv = document.createElement('div');
  13531. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13532. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13533. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13534. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13535. }
  13536. // load the manipulation functions
  13537. this._loadMixin(manipulationMixin);
  13538. // create the manipulator toolbar
  13539. this._createManipulatorBar();
  13540. }
  13541. else {
  13542. if (this.manipulationDiv !== undefined) {
  13543. // removes all the bindings and overloads
  13544. this._createManipulatorBar();
  13545. // remove the manipulation divs
  13546. this.containerElement.removeChild(this.manipulationDiv);
  13547. this.containerElement.removeChild(this.editModeDiv);
  13548. this.containerElement.removeChild(this.closeDiv);
  13549. this.manipulationDiv = undefined;
  13550. this.editModeDiv = undefined;
  13551. this.closeDiv = undefined;
  13552. // remove the mixin functions
  13553. this._clearMixin(manipulationMixin);
  13554. }
  13555. }
  13556. },
  13557. /**
  13558. * Mixin the navigation (User Interface) system and initialize the parameters required
  13559. *
  13560. * @private
  13561. */
  13562. _loadNavigationControls: function () {
  13563. this._loadMixin(NavigationMixin);
  13564. // the clean function removes the button divs, this is done to remove the bindings.
  13565. this._cleanNavigation();
  13566. if (this.constants.navigation.enabled == true) {
  13567. this._loadNavigationElements();
  13568. }
  13569. },
  13570. /**
  13571. * Mixin the hierarchical layout system.
  13572. *
  13573. * @private
  13574. */
  13575. _loadHierarchySystem: function () {
  13576. this._loadMixin(HierarchicalLayoutMixin);
  13577. }
  13578. };
  13579. /**
  13580. * @constructor Graph
  13581. * Create a graph visualization, displaying nodes and edges.
  13582. *
  13583. * @param {Element} container The DOM element in which the Graph will
  13584. * be created. Normally a div element.
  13585. * @param {Object} data An object containing parameters
  13586. * {Array} nodes
  13587. * {Array} edges
  13588. * @param {Object} options Options
  13589. */
  13590. function Graph (container, data, options) {
  13591. this._initializeMixinLoaders();
  13592. // create variables and set default values
  13593. this.containerElement = container;
  13594. this.width = '100%';
  13595. this.height = '100%';
  13596. // render and calculation settings
  13597. this.renderRefreshRate = 60; // hz (fps)
  13598. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13599. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13600. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13601. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13602. this.stabilize = true; // stabilize before displaying the graph
  13603. this.selectable = true;
  13604. this.initializing = true;
  13605. // these functions are triggered when the dataset is edited
  13606. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13607. // set constant values
  13608. this.constants = {
  13609. nodes: {
  13610. radiusMin: 5,
  13611. radiusMax: 20,
  13612. radius: 5,
  13613. shape: 'ellipse',
  13614. image: undefined,
  13615. widthMin: 16, // px
  13616. widthMax: 64, // px
  13617. fixed: false,
  13618. fontColor: 'black',
  13619. fontSize: 14, // px
  13620. fontFace: 'verdana',
  13621. level: -1,
  13622. color: {
  13623. border: '#2B7CE9',
  13624. background: '#97C2FC',
  13625. highlight: {
  13626. border: '#2B7CE9',
  13627. background: '#D2E5FF'
  13628. }
  13629. },
  13630. borderColor: '#2B7CE9',
  13631. backgroundColor: '#97C2FC',
  13632. highlightColor: '#D2E5FF',
  13633. group: undefined
  13634. },
  13635. edges: {
  13636. widthMin: 1,
  13637. widthMax: 15,
  13638. width: 1,
  13639. style: 'line',
  13640. color: {
  13641. color:'#848484',
  13642. highlight:'#848484'
  13643. },
  13644. fontColor: '#343434',
  13645. fontSize: 14, // px
  13646. fontFace: 'arial',
  13647. fontFill: 'white',
  13648. arrowScaleFactor: 1,
  13649. dash: {
  13650. length: 10,
  13651. gap: 5,
  13652. altLength: undefined
  13653. }
  13654. },
  13655. configurePhysics:false,
  13656. physics: {
  13657. barnesHut: {
  13658. enabled: true,
  13659. theta: 1 / 0.6, // inverted to save time during calculation
  13660. gravitationalConstant: -2000,
  13661. centralGravity: 0.3,
  13662. springLength: 95,
  13663. springConstant: 0.04,
  13664. damping: 0.09
  13665. },
  13666. repulsion: {
  13667. centralGravity: 0.1,
  13668. springLength: 200,
  13669. springConstant: 0.05,
  13670. nodeDistance: 100,
  13671. damping: 0.09
  13672. },
  13673. hierarchicalRepulsion: {
  13674. enabled: false,
  13675. centralGravity: 0.0,
  13676. springLength: 100,
  13677. springConstant: 0.01,
  13678. nodeDistance: 60,
  13679. damping: 0.09
  13680. },
  13681. damping: null,
  13682. centralGravity: null,
  13683. springLength: null,
  13684. springConstant: null
  13685. },
  13686. clustering: { // Per Node in Cluster = PNiC
  13687. enabled: false, // (Boolean) | global on/off switch for clustering.
  13688. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13689. 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
  13690. 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
  13691. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13692. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13693. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13694. 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.
  13695. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13696. maxFontSize: 1000,
  13697. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13698. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13699. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13700. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13701. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13702. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13703. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13704. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13705. clusterLevelDifference: 2
  13706. },
  13707. navigation: {
  13708. enabled: false
  13709. },
  13710. keyboard: {
  13711. enabled: false,
  13712. speed: {x: 10, y: 10, zoom: 0.02}
  13713. },
  13714. dataManipulation: {
  13715. enabled: false,
  13716. initiallyVisible: false
  13717. },
  13718. hierarchicalLayout: {
  13719. enabled:false,
  13720. levelSeparation: 150,
  13721. nodeSpacing: 100,
  13722. direction: "UD" // UD, DU, LR, RL
  13723. },
  13724. freezeForStabilization: false,
  13725. smoothCurves: true,
  13726. maxVelocity: 10,
  13727. minVelocity: 0.1, // px/s
  13728. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13729. labels:{
  13730. add:"Add Node",
  13731. edit:"Edit",
  13732. link:"Add Link",
  13733. del:"Delete selected",
  13734. editNode:"Edit Node",
  13735. back:"Back",
  13736. addDescription:"Click in an empty space to place a new node.",
  13737. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13738. addError:"The function for add does not support two arguments (data,callback).",
  13739. linkError:"The function for connect does not support two arguments (data,callback).",
  13740. editError:"The function for edit does not support two arguments (data, callback).",
  13741. editBoundError:"No edit function has been bound to this button.",
  13742. deleteError:"The function for delete does not support two arguments (data, callback).",
  13743. deleteClusterError:"Clusters cannot be deleted."
  13744. },
  13745. tooltip: {
  13746. delay: 300,
  13747. fontColor: 'black',
  13748. fontSize: 14, // px
  13749. fontFace: 'verdana',
  13750. color: {
  13751. border: '#666',
  13752. background: '#FFFFC6'
  13753. }
  13754. }
  13755. };
  13756. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13757. // Node variables
  13758. var graph = this;
  13759. this.groups = new Groups(); // object with groups
  13760. this.images = new Images(); // object with images
  13761. this.images.setOnloadCallback(function () {
  13762. graph._redraw();
  13763. });
  13764. // keyboard navigation variables
  13765. this.xIncrement = 0;
  13766. this.yIncrement = 0;
  13767. this.zoomIncrement = 0;
  13768. // loading all the mixins:
  13769. // load the force calculation functions, grouped under the physics system.
  13770. this._loadPhysicsSystem();
  13771. // create a frame and canvas
  13772. this._create();
  13773. // load the sector system. (mandatory, fully integrated with Graph)
  13774. this._loadSectorSystem();
  13775. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13776. this._loadClusterSystem();
  13777. // load the selection system. (mandatory, required by Graph)
  13778. this._loadSelectionSystem();
  13779. // load the selection system. (mandatory, required by Graph)
  13780. this._loadHierarchySystem();
  13781. // apply options
  13782. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  13783. this._setScale(1);
  13784. this.setOptions(options);
  13785. // other vars
  13786. this.freezeSimulation = false;// freeze the simulation
  13787. this.cachedFunctions = {};
  13788. // containers for nodes and edges
  13789. this.calculationNodes = {};
  13790. this.calculationNodeIndices = [];
  13791. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13792. this.nodes = {}; // object with Node objects
  13793. this.edges = {}; // object with Edge objects
  13794. // position and scale variables and objects
  13795. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13796. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13797. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13798. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13799. this.scale = 1; // defining the global scale variable in the constructor
  13800. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13801. // datasets or dataviews
  13802. this.nodesData = null; // A DataSet or DataView
  13803. this.edgesData = null; // A DataSet or DataView
  13804. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13805. this.nodesListeners = {
  13806. 'add': function (event, params) {
  13807. graph._addNodes(params.items);
  13808. graph.start();
  13809. },
  13810. 'update': function (event, params) {
  13811. graph._updateNodes(params.items);
  13812. graph.start();
  13813. },
  13814. 'remove': function (event, params) {
  13815. graph._removeNodes(params.items);
  13816. graph.start();
  13817. }
  13818. };
  13819. this.edgesListeners = {
  13820. 'add': function (event, params) {
  13821. graph._addEdges(params.items);
  13822. graph.start();
  13823. },
  13824. 'update': function (event, params) {
  13825. graph._updateEdges(params.items);
  13826. graph.start();
  13827. },
  13828. 'remove': function (event, params) {
  13829. graph._removeEdges(params.items);
  13830. graph.start();
  13831. }
  13832. };
  13833. // properties for the animation
  13834. this.moving = true;
  13835. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13836. // load data (the disable start variable will be the same as the enabled clustering)
  13837. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13838. // hierarchical layout
  13839. this.initializing = false;
  13840. if (this.constants.hierarchicalLayout.enabled == true) {
  13841. this._setupHierarchicalLayout();
  13842. }
  13843. else {
  13844. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13845. if (this.stabilize == false) {
  13846. this.zoomExtent(true,this.constants.clustering.enabled);
  13847. }
  13848. }
  13849. // if clustering is disabled, the simulation will have started in the setData function
  13850. if (this.constants.clustering.enabled) {
  13851. this.startWithClustering();
  13852. }
  13853. }
  13854. // Extend Graph with an Emitter mixin
  13855. Emitter(Graph.prototype);
  13856. /**
  13857. * Get the script path where the vis.js library is located
  13858. *
  13859. * @returns {string | null} path Path or null when not found. Path does not
  13860. * end with a slash.
  13861. * @private
  13862. */
  13863. Graph.prototype._getScriptPath = function() {
  13864. var scripts = document.getElementsByTagName( 'script' );
  13865. // find script named vis.js or vis.min.js
  13866. for (var i = 0; i < scripts.length; i++) {
  13867. var src = scripts[i].src;
  13868. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13869. if (match) {
  13870. // return path without the script name
  13871. return src.substring(0, src.length - match[0].length);
  13872. }
  13873. }
  13874. return null;
  13875. };
  13876. /**
  13877. * Find the center position of the graph
  13878. * @private
  13879. */
  13880. Graph.prototype._getRange = function() {
  13881. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13882. for (var nodeId in this.nodes) {
  13883. if (this.nodes.hasOwnProperty(nodeId)) {
  13884. node = this.nodes[nodeId];
  13885. if (minX > (node.x)) {minX = node.x;}
  13886. if (maxX < (node.x)) {maxX = node.x;}
  13887. if (minY > (node.y)) {minY = node.y;}
  13888. if (maxY < (node.y)) {maxY = node.y;}
  13889. }
  13890. }
  13891. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13892. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13893. }
  13894. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13895. };
  13896. /**
  13897. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13898. * @returns {{x: number, y: number}}
  13899. * @private
  13900. */
  13901. Graph.prototype._findCenter = function(range) {
  13902. return {x: (0.5 * (range.maxX + range.minX)),
  13903. y: (0.5 * (range.maxY + range.minY))};
  13904. };
  13905. /**
  13906. * center the graph
  13907. *
  13908. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13909. */
  13910. Graph.prototype._centerGraph = function(range) {
  13911. var center = this._findCenter(range);
  13912. center.x *= this.scale;
  13913. center.y *= this.scale;
  13914. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13915. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13916. this._setTranslation(-center.x,-center.y); // set at 0,0
  13917. };
  13918. /**
  13919. * This function zooms out to fit all data on screen based on amount of nodes
  13920. *
  13921. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13922. * @param {Boolean} [disableStart] | If true, start is not called.
  13923. */
  13924. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  13925. if (initialZoom === undefined) {
  13926. initialZoom = false;
  13927. }
  13928. if (disableStart === undefined) {
  13929. disableStart = false;
  13930. }
  13931. var range = this._getRange();
  13932. var zoomLevel;
  13933. if (initialZoom == true) {
  13934. var numberOfNodes = this.nodeIndices.length;
  13935. if (this.constants.smoothCurves == true) {
  13936. if (this.constants.clustering.enabled == true &&
  13937. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13938. 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.
  13939. }
  13940. else {
  13941. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13942. }
  13943. }
  13944. else {
  13945. if (this.constants.clustering.enabled == true &&
  13946. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13947. 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.
  13948. }
  13949. else {
  13950. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13951. }
  13952. }
  13953. // correct for larger canvasses.
  13954. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  13955. zoomLevel *= factor;
  13956. }
  13957. else {
  13958. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  13959. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  13960. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13961. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13962. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13963. }
  13964. if (zoomLevel > 1.0) {
  13965. zoomLevel = 1.0;
  13966. }
  13967. this._setScale(zoomLevel);
  13968. this._centerGraph(range);
  13969. if (disableStart == false) {
  13970. this.moving = true;
  13971. this.start();
  13972. }
  13973. };
  13974. /**
  13975. * Update the this.nodeIndices with the most recent node index list
  13976. * @private
  13977. */
  13978. Graph.prototype._updateNodeIndexList = function() {
  13979. this._clearNodeIndexList();
  13980. for (var idx in this.nodes) {
  13981. if (this.nodes.hasOwnProperty(idx)) {
  13982. this.nodeIndices.push(idx);
  13983. }
  13984. }
  13985. };
  13986. /**
  13987. * Set nodes and edges, and optionally options as well.
  13988. *
  13989. * @param {Object} data Object containing parameters:
  13990. * {Array | DataSet | DataView} [nodes] Array with nodes
  13991. * {Array | DataSet | DataView} [edges] Array with edges
  13992. * {String} [dot] String containing data in DOT format
  13993. * {Options} [options] Object with options
  13994. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  13995. */
  13996. Graph.prototype.setData = function(data, disableStart) {
  13997. if (disableStart === undefined) {
  13998. disableStart = false;
  13999. }
  14000. if (data && data.dot && (data.nodes || data.edges)) {
  14001. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14002. ' parameter pair "nodes" and "edges", but not both.');
  14003. }
  14004. // set options
  14005. this.setOptions(data && data.options);
  14006. // set all data
  14007. if (data && data.dot) {
  14008. // parse DOT file
  14009. if(data && data.dot) {
  14010. var dotData = vis.util.DOTToGraph(data.dot);
  14011. this.setData(dotData);
  14012. return;
  14013. }
  14014. }
  14015. else {
  14016. this._setNodes(data && data.nodes);
  14017. this._setEdges(data && data.edges);
  14018. }
  14019. this._putDataInSector();
  14020. if (!disableStart) {
  14021. // find a stable position or start animating to a stable position
  14022. if (this.stabilize) {
  14023. var me = this;
  14024. setTimeout(function() {me._stabilize(); me.start();},0)
  14025. }
  14026. else {
  14027. this.start();
  14028. }
  14029. }
  14030. };
  14031. /**
  14032. * Set options
  14033. * @param {Object} options
  14034. * @param {Boolean} [initializeView] | set zoom and translation to default.
  14035. */
  14036. Graph.prototype.setOptions = function (options) {
  14037. if (options) {
  14038. var prop;
  14039. // retrieve parameter values
  14040. if (options.width !== undefined) {this.width = options.width;}
  14041. if (options.height !== undefined) {this.height = options.height;}
  14042. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14043. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14044. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14045. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14046. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14047. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14048. if (options.labels !== undefined) {
  14049. for (prop in options.labels) {
  14050. if (options.labels.hasOwnProperty(prop)) {
  14051. this.constants.labels[prop] = options.labels[prop];
  14052. }
  14053. }
  14054. }
  14055. if (options.onAdd) {
  14056. this.triggerFunctions.add = options.onAdd;
  14057. }
  14058. if (options.onEdit) {
  14059. this.triggerFunctions.edit = options.onEdit;
  14060. }
  14061. if (options.onConnect) {
  14062. this.triggerFunctions.connect = options.onConnect;
  14063. }
  14064. if (options.onDelete) {
  14065. this.triggerFunctions.del = options.onDelete;
  14066. }
  14067. if (options.physics) {
  14068. if (options.physics.barnesHut) {
  14069. this.constants.physics.barnesHut.enabled = true;
  14070. for (prop in options.physics.barnesHut) {
  14071. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14072. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14073. }
  14074. }
  14075. }
  14076. if (options.physics.repulsion) {
  14077. this.constants.physics.barnesHut.enabled = false;
  14078. for (prop in options.physics.repulsion) {
  14079. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14080. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14081. }
  14082. }
  14083. }
  14084. if (options.physics.hierarchicalRepulsion) {
  14085. this.constants.hierarchicalLayout.enabled = true;
  14086. this.constants.physics.hierarchicalRepulsion.enabled = true;
  14087. this.constants.physics.barnesHut.enabled = false;
  14088. for (prop in options.physics.hierarchicalRepulsion) {
  14089. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  14090. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  14091. }
  14092. }
  14093. }
  14094. }
  14095. if (options.hierarchicalLayout) {
  14096. this.constants.hierarchicalLayout.enabled = true;
  14097. for (prop in options.hierarchicalLayout) {
  14098. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14099. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14100. }
  14101. }
  14102. }
  14103. else if (options.hierarchicalLayout !== undefined) {
  14104. this.constants.hierarchicalLayout.enabled = false;
  14105. }
  14106. if (options.clustering) {
  14107. this.constants.clustering.enabled = true;
  14108. for (prop in options.clustering) {
  14109. if (options.clustering.hasOwnProperty(prop)) {
  14110. this.constants.clustering[prop] = options.clustering[prop];
  14111. }
  14112. }
  14113. }
  14114. else if (options.clustering !== undefined) {
  14115. this.constants.clustering.enabled = false;
  14116. }
  14117. if (options.navigation) {
  14118. this.constants.navigation.enabled = true;
  14119. for (prop in options.navigation) {
  14120. if (options.navigation.hasOwnProperty(prop)) {
  14121. this.constants.navigation[prop] = options.navigation[prop];
  14122. }
  14123. }
  14124. }
  14125. else if (options.navigation !== undefined) {
  14126. this.constants.navigation.enabled = false;
  14127. }
  14128. if (options.keyboard) {
  14129. this.constants.keyboard.enabled = true;
  14130. for (prop in options.keyboard) {
  14131. if (options.keyboard.hasOwnProperty(prop)) {
  14132. this.constants.keyboard[prop] = options.keyboard[prop];
  14133. }
  14134. }
  14135. }
  14136. else if (options.keyboard !== undefined) {
  14137. this.constants.keyboard.enabled = false;
  14138. }
  14139. if (options.dataManipulation) {
  14140. this.constants.dataManipulation.enabled = true;
  14141. for (prop in options.dataManipulation) {
  14142. if (options.dataManipulation.hasOwnProperty(prop)) {
  14143. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14144. }
  14145. }
  14146. }
  14147. else if (options.dataManipulation !== undefined) {
  14148. this.constants.dataManipulation.enabled = false;
  14149. }
  14150. // TODO: work out these options and document them
  14151. if (options.edges) {
  14152. for (prop in options.edges) {
  14153. if (options.edges.hasOwnProperty(prop)) {
  14154. if (typeof options.edges[prop] != "object") {
  14155. this.constants.edges[prop] = options.edges[prop];
  14156. }
  14157. }
  14158. }
  14159. if (options.edges.color !== undefined) {
  14160. if (util.isString(options.edges.color)) {
  14161. this.constants.edges.color = {};
  14162. this.constants.edges.color.color = options.edges.color;
  14163. this.constants.edges.color.highlight = options.edges.color;
  14164. }
  14165. else {
  14166. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14167. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14168. }
  14169. }
  14170. if (!options.edges.fontColor) {
  14171. if (options.edges.color !== undefined) {
  14172. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14173. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14174. }
  14175. }
  14176. // Added to support dashed lines
  14177. // David Jordan
  14178. // 2012-08-08
  14179. if (options.edges.dash) {
  14180. if (options.edges.dash.length !== undefined) {
  14181. this.constants.edges.dash.length = options.edges.dash.length;
  14182. }
  14183. if (options.edges.dash.gap !== undefined) {
  14184. this.constants.edges.dash.gap = options.edges.dash.gap;
  14185. }
  14186. if (options.edges.dash.altLength !== undefined) {
  14187. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14188. }
  14189. }
  14190. }
  14191. if (options.nodes) {
  14192. for (prop in options.nodes) {
  14193. if (options.nodes.hasOwnProperty(prop)) {
  14194. this.constants.nodes[prop] = options.nodes[prop];
  14195. }
  14196. }
  14197. if (options.nodes.color) {
  14198. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14199. }
  14200. /*
  14201. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14202. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14203. */
  14204. }
  14205. if (options.groups) {
  14206. for (var groupname in options.groups) {
  14207. if (options.groups.hasOwnProperty(groupname)) {
  14208. var group = options.groups[groupname];
  14209. this.groups.add(groupname, group);
  14210. }
  14211. }
  14212. }
  14213. if (options.tooltip) {
  14214. for (prop in options.tooltip) {
  14215. if (options.tooltip.hasOwnProperty(prop)) {
  14216. this.constants.tooltip[prop] = options.tooltip[prop];
  14217. }
  14218. }
  14219. if (options.tooltip.color) {
  14220. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14221. }
  14222. }
  14223. }
  14224. // (Re)loading the mixins that can be enabled or disabled in the options.
  14225. // load the force calculation functions, grouped under the physics system.
  14226. this._loadPhysicsSystem();
  14227. // load the navigation system.
  14228. this._loadNavigationControls();
  14229. // load the data manipulation system
  14230. this._loadManipulationSystem();
  14231. // configure the smooth curves
  14232. this._configureSmoothCurves();
  14233. // bind keys. If disabled, this will not do anything;
  14234. this._createKeyBinds();
  14235. this.setSize(this.width, this.height);
  14236. this.moving = true;
  14237. this.start();
  14238. };
  14239. /**
  14240. * Create the main frame for the Graph.
  14241. * This function is executed once when a Graph object is created. The frame
  14242. * contains a canvas, and this canvas contains all objects like the axis and
  14243. * nodes.
  14244. * @private
  14245. */
  14246. Graph.prototype._create = function () {
  14247. // remove all elements from the container element.
  14248. while (this.containerElement.hasChildNodes()) {
  14249. this.containerElement.removeChild(this.containerElement.firstChild);
  14250. }
  14251. this.frame = document.createElement('div');
  14252. this.frame.className = 'graph-frame';
  14253. this.frame.style.position = 'relative';
  14254. this.frame.style.overflow = 'hidden';
  14255. // create the graph canvas (HTML canvas element)
  14256. this.frame.canvas = document.createElement( 'canvas' );
  14257. this.frame.canvas.style.position = 'relative';
  14258. this.frame.appendChild(this.frame.canvas);
  14259. if (!this.frame.canvas.getContext) {
  14260. var noCanvas = document.createElement( 'DIV' );
  14261. noCanvas.style.color = 'red';
  14262. noCanvas.style.fontWeight = 'bold' ;
  14263. noCanvas.style.padding = '10px';
  14264. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14265. this.frame.canvas.appendChild(noCanvas);
  14266. }
  14267. var me = this;
  14268. this.drag = {};
  14269. this.pinch = {};
  14270. this.hammer = Hammer(this.frame.canvas, {
  14271. prevent_default: true
  14272. });
  14273. this.hammer.on('tap', me._onTap.bind(me) );
  14274. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14275. this.hammer.on('hold', me._onHold.bind(me) );
  14276. this.hammer.on('pinch', me._onPinch.bind(me) );
  14277. this.hammer.on('touch', me._onTouch.bind(me) );
  14278. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14279. this.hammer.on('drag', me._onDrag.bind(me) );
  14280. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14281. this.hammer.on('release', me._onRelease.bind(me) );
  14282. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14283. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14284. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14285. // add the frame to the container element
  14286. this.containerElement.appendChild(this.frame);
  14287. };
  14288. /**
  14289. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14290. * @private
  14291. */
  14292. Graph.prototype._createKeyBinds = function() {
  14293. var me = this;
  14294. this.mousetrap = mousetrap;
  14295. this.mousetrap.reset();
  14296. if (this.constants.keyboard.enabled == true) {
  14297. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14298. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14299. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14300. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14301. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14302. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14303. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14304. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14305. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14306. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14307. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14308. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14309. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14310. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14311. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14312. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14313. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14314. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14315. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14316. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14317. }
  14318. if (this.constants.dataManipulation.enabled == true) {
  14319. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14320. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14321. }
  14322. };
  14323. /**
  14324. * Get the pointer location from a touch location
  14325. * @param {{pageX: Number, pageY: Number}} touch
  14326. * @return {{x: Number, y: Number}} pointer
  14327. * @private
  14328. */
  14329. Graph.prototype._getPointer = function (touch) {
  14330. return {
  14331. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14332. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14333. };
  14334. };
  14335. /**
  14336. * On start of a touch gesture, store the pointer
  14337. * @param event
  14338. * @private
  14339. */
  14340. Graph.prototype._onTouch = function (event) {
  14341. this.drag.pointer = this._getPointer(event.gesture.center);
  14342. this.drag.pinched = false;
  14343. this.pinch.scale = this._getScale();
  14344. this._handleTouch(this.drag.pointer);
  14345. };
  14346. /**
  14347. * handle drag start event
  14348. * @private
  14349. */
  14350. Graph.prototype._onDragStart = function () {
  14351. this._handleDragStart();
  14352. };
  14353. /**
  14354. * This function is called by _onDragStart.
  14355. * It is separated out because we can then overload it for the datamanipulation system.
  14356. *
  14357. * @private
  14358. */
  14359. Graph.prototype._handleDragStart = function() {
  14360. var drag = this.drag;
  14361. var node = this._getNodeAt(drag.pointer);
  14362. // note: drag.pointer is set in _onTouch to get the initial touch location
  14363. drag.dragging = true;
  14364. drag.selection = [];
  14365. drag.translation = this._getTranslation();
  14366. drag.nodeId = null;
  14367. if (node != null) {
  14368. drag.nodeId = node.id;
  14369. // select the clicked node if not yet selected
  14370. if (!node.isSelected()) {
  14371. this._selectObject(node,false);
  14372. }
  14373. // create an array with the selected nodes and their original location and status
  14374. for (var objectId in this.selectionObj.nodes) {
  14375. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14376. var object = this.selectionObj.nodes[objectId];
  14377. var s = {
  14378. id: object.id,
  14379. node: object,
  14380. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14381. x: object.x,
  14382. y: object.y,
  14383. xFixed: object.xFixed,
  14384. yFixed: object.yFixed
  14385. };
  14386. object.xFixed = true;
  14387. object.yFixed = true;
  14388. drag.selection.push(s);
  14389. }
  14390. }
  14391. }
  14392. };
  14393. /**
  14394. * handle drag event
  14395. * @private
  14396. */
  14397. Graph.prototype._onDrag = function (event) {
  14398. this._handleOnDrag(event)
  14399. };
  14400. /**
  14401. * This function is called by _onDrag.
  14402. * It is separated out because we can then overload it for the datamanipulation system.
  14403. *
  14404. * @private
  14405. */
  14406. Graph.prototype._handleOnDrag = function(event) {
  14407. if (this.drag.pinched) {
  14408. return;
  14409. }
  14410. var pointer = this._getPointer(event.gesture.center);
  14411. var me = this,
  14412. drag = this.drag,
  14413. selection = drag.selection;
  14414. if (selection && selection.length) {
  14415. // calculate delta's and new location
  14416. var deltaX = pointer.x - drag.pointer.x,
  14417. deltaY = pointer.y - drag.pointer.y;
  14418. // update position of all selected nodes
  14419. selection.forEach(function (s) {
  14420. var node = s.node;
  14421. if (!s.xFixed) {
  14422. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14423. }
  14424. if (!s.yFixed) {
  14425. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14426. }
  14427. });
  14428. // start _animationStep if not yet running
  14429. if (!this.moving) {
  14430. this.moving = true;
  14431. this.start();
  14432. }
  14433. }
  14434. else {
  14435. // move the graph
  14436. var diffX = pointer.x - this.drag.pointer.x;
  14437. var diffY = pointer.y - this.drag.pointer.y;
  14438. this._setTranslation(
  14439. this.drag.translation.x + diffX,
  14440. this.drag.translation.y + diffY);
  14441. this._redraw();
  14442. this.moving = true;
  14443. this.start();
  14444. }
  14445. };
  14446. /**
  14447. * handle drag start event
  14448. * @private
  14449. */
  14450. Graph.prototype._onDragEnd = function () {
  14451. this.drag.dragging = false;
  14452. var selection = this.drag.selection;
  14453. if (selection) {
  14454. selection.forEach(function (s) {
  14455. // restore original xFixed and yFixed
  14456. s.node.xFixed = s.xFixed;
  14457. s.node.yFixed = s.yFixed;
  14458. });
  14459. }
  14460. };
  14461. /**
  14462. * handle tap/click event: select/unselect a node
  14463. * @private
  14464. */
  14465. Graph.prototype._onTap = function (event) {
  14466. var pointer = this._getPointer(event.gesture.center);
  14467. this.pointerPosition = pointer;
  14468. this._handleTap(pointer);
  14469. };
  14470. /**
  14471. * handle doubletap event
  14472. * @private
  14473. */
  14474. Graph.prototype._onDoubleTap = function (event) {
  14475. var pointer = this._getPointer(event.gesture.center);
  14476. this._handleDoubleTap(pointer);
  14477. };
  14478. /**
  14479. * handle long tap event: multi select nodes
  14480. * @private
  14481. */
  14482. Graph.prototype._onHold = function (event) {
  14483. var pointer = this._getPointer(event.gesture.center);
  14484. this.pointerPosition = pointer;
  14485. this._handleOnHold(pointer);
  14486. };
  14487. /**
  14488. * handle the release of the screen
  14489. *
  14490. * @private
  14491. */
  14492. Graph.prototype._onRelease = function (event) {
  14493. var pointer = this._getPointer(event.gesture.center);
  14494. this._handleOnRelease(pointer);
  14495. };
  14496. /**
  14497. * Handle pinch event
  14498. * @param event
  14499. * @private
  14500. */
  14501. Graph.prototype._onPinch = function (event) {
  14502. var pointer = this._getPointer(event.gesture.center);
  14503. this.drag.pinched = true;
  14504. if (!('scale' in this.pinch)) {
  14505. this.pinch.scale = 1;
  14506. }
  14507. // TODO: enabled moving while pinching?
  14508. var scale = this.pinch.scale * event.gesture.scale;
  14509. this._zoom(scale, pointer)
  14510. };
  14511. /**
  14512. * Zoom the graph in or out
  14513. * @param {Number} scale a number around 1, and between 0.01 and 10
  14514. * @param {{x: Number, y: Number}} pointer Position on screen
  14515. * @return {Number} appliedScale scale is limited within the boundaries
  14516. * @private
  14517. */
  14518. Graph.prototype._zoom = function(scale, pointer) {
  14519. var scaleOld = this._getScale();
  14520. if (scale < 0.00001) {
  14521. scale = 0.00001;
  14522. }
  14523. if (scale > 10) {
  14524. scale = 10;
  14525. }
  14526. // + this.frame.canvas.clientHeight / 2
  14527. var translation = this._getTranslation();
  14528. var scaleFrac = scale / scaleOld;
  14529. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14530. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14531. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14532. "y" : this._canvasToY(pointer.y)};
  14533. this._setScale(scale);
  14534. this._setTranslation(tx, ty);
  14535. this.updateClustersDefault();
  14536. this._redraw();
  14537. if (scaleOld < scale) {
  14538. this.emit("zoom", {direction:"+"});
  14539. }
  14540. else {
  14541. this.emit("zoom", {direction:"-"});
  14542. }
  14543. return scale;
  14544. };
  14545. /**
  14546. * Event handler for mouse wheel event, used to zoom the timeline
  14547. * See http://adomas.org/javascript-mouse-wheel/
  14548. * https://github.com/EightMedia/hammer.js/issues/256
  14549. * @param {MouseEvent} event
  14550. * @private
  14551. */
  14552. Graph.prototype._onMouseWheel = function(event) {
  14553. // retrieve delta
  14554. var delta = 0;
  14555. if (event.wheelDelta) { /* IE/Opera. */
  14556. delta = event.wheelDelta/120;
  14557. } else if (event.detail) { /* Mozilla case. */
  14558. // In Mozilla, sign of delta is different than in IE.
  14559. // Also, delta is multiple of 3.
  14560. delta = -event.detail/3;
  14561. }
  14562. // If delta is nonzero, handle it.
  14563. // Basically, delta is now positive if wheel was scrolled up,
  14564. // and negative, if wheel was scrolled down.
  14565. if (delta) {
  14566. // calculate the new scale
  14567. var scale = this._getScale();
  14568. var zoom = delta / 10;
  14569. if (delta < 0) {
  14570. zoom = zoom / (1 - zoom);
  14571. }
  14572. scale *= (1 + zoom);
  14573. // calculate the pointer location
  14574. var gesture = util.fakeGesture(this, event);
  14575. var pointer = this._getPointer(gesture.center);
  14576. // apply the new scale
  14577. this._zoom(scale, pointer);
  14578. }
  14579. // Prevent default actions caused by mouse wheel.
  14580. event.preventDefault();
  14581. };
  14582. /**
  14583. * Mouse move handler for checking whether the title moves over a node with a title.
  14584. * @param {Event} event
  14585. * @private
  14586. */
  14587. Graph.prototype._onMouseMoveTitle = function (event) {
  14588. var gesture = util.fakeGesture(this, event);
  14589. var pointer = this._getPointer(gesture.center);
  14590. // check if the previously selected node is still selected
  14591. if (this.popupNode) {
  14592. this._checkHidePopup(pointer);
  14593. }
  14594. // start a timeout that will check if the mouse is positioned above
  14595. // an element
  14596. var me = this;
  14597. var checkShow = function() {
  14598. me._checkShowPopup(pointer);
  14599. };
  14600. if (this.popupTimer) {
  14601. clearInterval(this.popupTimer); // stop any running calculationTimer
  14602. }
  14603. if (!this.drag.dragging) {
  14604. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14605. }
  14606. };
  14607. /**
  14608. * Check if there is an element on the given position in the graph
  14609. * (a node or edge). If so, and if this element has a title,
  14610. * show a popup window with its title.
  14611. *
  14612. * @param {{x:Number, y:Number}} pointer
  14613. * @private
  14614. */
  14615. Graph.prototype._checkShowPopup = function (pointer) {
  14616. var obj = {
  14617. left: this._canvasToX(pointer.x),
  14618. top: this._canvasToY(pointer.y),
  14619. right: this._canvasToX(pointer.x),
  14620. bottom: this._canvasToY(pointer.y)
  14621. };
  14622. var id;
  14623. var lastPopupNode = this.popupNode;
  14624. if (this.popupNode == undefined) {
  14625. // search the nodes for overlap, select the top one in case of multiple nodes
  14626. var nodes = this.nodes;
  14627. for (id in nodes) {
  14628. if (nodes.hasOwnProperty(id)) {
  14629. var node = nodes[id];
  14630. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14631. this.popupNode = node;
  14632. break;
  14633. }
  14634. }
  14635. }
  14636. }
  14637. if (this.popupNode === undefined) {
  14638. // search the edges for overlap
  14639. var edges = this.edges;
  14640. for (id in edges) {
  14641. if (edges.hasOwnProperty(id)) {
  14642. var edge = edges[id];
  14643. if (edge.connected && (edge.getTitle() !== undefined) &&
  14644. edge.isOverlappingWith(obj)) {
  14645. this.popupNode = edge;
  14646. break;
  14647. }
  14648. }
  14649. }
  14650. }
  14651. if (this.popupNode) {
  14652. // show popup message window
  14653. if (this.popupNode != lastPopupNode) {
  14654. var me = this;
  14655. if (!me.popup) {
  14656. me.popup = new Popup(me.frame, me.constants.tooltip);
  14657. }
  14658. // adjust a small offset such that the mouse cursor is located in the
  14659. // bottom left location of the popup, and you can easily move over the
  14660. // popup area
  14661. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14662. me.popup.setText(me.popupNode.getTitle());
  14663. me.popup.show();
  14664. }
  14665. }
  14666. else {
  14667. if (this.popup) {
  14668. this.popup.hide();
  14669. }
  14670. }
  14671. };
  14672. /**
  14673. * Check if the popup must be hided, which is the case when the mouse is no
  14674. * longer hovering on the object
  14675. * @param {{x:Number, y:Number}} pointer
  14676. * @private
  14677. */
  14678. Graph.prototype._checkHidePopup = function (pointer) {
  14679. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14680. this.popupNode = undefined;
  14681. if (this.popup) {
  14682. this.popup.hide();
  14683. }
  14684. }
  14685. };
  14686. /**
  14687. * Set a new size for the graph
  14688. * @param {string} width Width in pixels or percentage (for example '800px'
  14689. * or '50%')
  14690. * @param {string} height Height in pixels or percentage (for example '400px'
  14691. * or '30%')
  14692. */
  14693. Graph.prototype.setSize = function(width, height) {
  14694. this.frame.style.width = width;
  14695. this.frame.style.height = height;
  14696. this.frame.canvas.style.width = '100%';
  14697. this.frame.canvas.style.height = '100%';
  14698. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14699. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14700. if (this.manipulationDiv !== undefined) {
  14701. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14702. }
  14703. if (this.navigationDivs !== undefined) {
  14704. if (this.navigationDivs['wrapper'] !== undefined) {
  14705. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14706. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14707. }
  14708. }
  14709. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14710. };
  14711. /**
  14712. * Set a data set with nodes for the graph
  14713. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14714. * @private
  14715. */
  14716. Graph.prototype._setNodes = function(nodes) {
  14717. var oldNodesData = this.nodesData;
  14718. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14719. this.nodesData = nodes;
  14720. }
  14721. else if (nodes instanceof Array) {
  14722. this.nodesData = new DataSet();
  14723. this.nodesData.add(nodes);
  14724. }
  14725. else if (!nodes) {
  14726. this.nodesData = new DataSet();
  14727. }
  14728. else {
  14729. throw new TypeError('Array or DataSet expected');
  14730. }
  14731. if (oldNodesData) {
  14732. // unsubscribe from old dataset
  14733. util.forEach(this.nodesListeners, function (callback, event) {
  14734. oldNodesData.off(event, callback);
  14735. });
  14736. }
  14737. // remove drawn nodes
  14738. this.nodes = {};
  14739. if (this.nodesData) {
  14740. // subscribe to new dataset
  14741. var me = this;
  14742. util.forEach(this.nodesListeners, function (callback, event) {
  14743. me.nodesData.on(event, callback);
  14744. });
  14745. // draw all new nodes
  14746. var ids = this.nodesData.getIds();
  14747. this._addNodes(ids);
  14748. }
  14749. this._updateSelection();
  14750. };
  14751. /**
  14752. * Add nodes
  14753. * @param {Number[] | String[]} ids
  14754. * @private
  14755. */
  14756. Graph.prototype._addNodes = function(ids) {
  14757. var id;
  14758. for (var i = 0, len = ids.length; i < len; i++) {
  14759. id = ids[i];
  14760. var data = this.nodesData.get(id);
  14761. var node = new Node(data, this.images, this.groups, this.constants);
  14762. this.nodes[id] = node; // note: this may replace an existing node
  14763. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14764. var radius = 10 * 0.1*ids.length;
  14765. var angle = 2 * Math.PI * Math.random();
  14766. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14767. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14768. }
  14769. this.moving = true;
  14770. }
  14771. this._updateNodeIndexList();
  14772. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14773. this._resetLevels();
  14774. this._setupHierarchicalLayout();
  14775. }
  14776. this._updateCalculationNodes();
  14777. this._reconnectEdges();
  14778. this._updateValueRange(this.nodes);
  14779. this.updateLabels();
  14780. };
  14781. /**
  14782. * Update existing nodes, or create them when not yet existing
  14783. * @param {Number[] | String[]} ids
  14784. * @private
  14785. */
  14786. Graph.prototype._updateNodes = function(ids) {
  14787. var nodes = this.nodes,
  14788. nodesData = this.nodesData;
  14789. for (var i = 0, len = ids.length; i < len; i++) {
  14790. var id = ids[i];
  14791. var node = nodes[id];
  14792. var data = nodesData.get(id);
  14793. if (node) {
  14794. // update node
  14795. node.setProperties(data, this.constants);
  14796. }
  14797. else {
  14798. // create node
  14799. node = new Node(properties, this.images, this.groups, this.constants);
  14800. nodes[id] = node;
  14801. }
  14802. }
  14803. this.moving = true;
  14804. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14805. this._resetLevels();
  14806. this._setupHierarchicalLayout();
  14807. }
  14808. this._updateNodeIndexList();
  14809. this._reconnectEdges();
  14810. this._updateValueRange(nodes);
  14811. };
  14812. /**
  14813. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14814. * @param {Number[] | String[]} ids
  14815. * @private
  14816. */
  14817. Graph.prototype._removeNodes = function(ids) {
  14818. var nodes = this.nodes;
  14819. for (var i = 0, len = ids.length; i < len; i++) {
  14820. var id = ids[i];
  14821. delete nodes[id];
  14822. }
  14823. this._updateNodeIndexList();
  14824. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14825. this._resetLevels();
  14826. this._setupHierarchicalLayout();
  14827. }
  14828. this._updateCalculationNodes();
  14829. this._reconnectEdges();
  14830. this._updateSelection();
  14831. this._updateValueRange(nodes);
  14832. };
  14833. /**
  14834. * Load edges by reading the data table
  14835. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14836. * @private
  14837. * @private
  14838. */
  14839. Graph.prototype._setEdges = function(edges) {
  14840. var oldEdgesData = this.edgesData;
  14841. if (edges instanceof DataSet || edges instanceof DataView) {
  14842. this.edgesData = edges;
  14843. }
  14844. else if (edges instanceof Array) {
  14845. this.edgesData = new DataSet();
  14846. this.edgesData.add(edges);
  14847. }
  14848. else if (!edges) {
  14849. this.edgesData = new DataSet();
  14850. }
  14851. else {
  14852. throw new TypeError('Array or DataSet expected');
  14853. }
  14854. if (oldEdgesData) {
  14855. // unsubscribe from old dataset
  14856. util.forEach(this.edgesListeners, function (callback, event) {
  14857. oldEdgesData.off(event, callback);
  14858. });
  14859. }
  14860. // remove drawn edges
  14861. this.edges = {};
  14862. if (this.edgesData) {
  14863. // subscribe to new dataset
  14864. var me = this;
  14865. util.forEach(this.edgesListeners, function (callback, event) {
  14866. me.edgesData.on(event, callback);
  14867. });
  14868. // draw all new nodes
  14869. var ids = this.edgesData.getIds();
  14870. this._addEdges(ids);
  14871. }
  14872. this._reconnectEdges();
  14873. };
  14874. /**
  14875. * Add edges
  14876. * @param {Number[] | String[]} ids
  14877. * @private
  14878. */
  14879. Graph.prototype._addEdges = function (ids) {
  14880. var edges = this.edges,
  14881. edgesData = this.edgesData;
  14882. for (var i = 0, len = ids.length; i < len; i++) {
  14883. var id = ids[i];
  14884. var oldEdge = edges[id];
  14885. if (oldEdge) {
  14886. oldEdge.disconnect();
  14887. }
  14888. var data = edgesData.get(id, {"showInternalIds" : true});
  14889. edges[id] = new Edge(data, this, this.constants);
  14890. }
  14891. this.moving = true;
  14892. this._updateValueRange(edges);
  14893. this._createBezierNodes();
  14894. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14895. this._resetLevels();
  14896. this._setupHierarchicalLayout();
  14897. }
  14898. this._updateCalculationNodes();
  14899. };
  14900. /**
  14901. * Update existing edges, or create them when not yet existing
  14902. * @param {Number[] | String[]} ids
  14903. * @private
  14904. */
  14905. Graph.prototype._updateEdges = function (ids) {
  14906. var edges = this.edges,
  14907. edgesData = this.edgesData;
  14908. for (var i = 0, len = ids.length; i < len; i++) {
  14909. var id = ids[i];
  14910. var data = edgesData.get(id);
  14911. var edge = edges[id];
  14912. if (edge) {
  14913. // update edge
  14914. edge.disconnect();
  14915. edge.setProperties(data, this.constants);
  14916. edge.connect();
  14917. }
  14918. else {
  14919. // create edge
  14920. edge = new Edge(data, this, this.constants);
  14921. this.edges[id] = edge;
  14922. }
  14923. }
  14924. this._createBezierNodes();
  14925. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14926. this._resetLevels();
  14927. this._setupHierarchicalLayout();
  14928. }
  14929. this.moving = true;
  14930. this._updateValueRange(edges);
  14931. };
  14932. /**
  14933. * Remove existing edges. Non existing ids will be ignored
  14934. * @param {Number[] | String[]} ids
  14935. * @private
  14936. */
  14937. Graph.prototype._removeEdges = function (ids) {
  14938. var edges = this.edges;
  14939. for (var i = 0, len = ids.length; i < len; i++) {
  14940. var id = ids[i];
  14941. var edge = edges[id];
  14942. if (edge) {
  14943. if (edge.via != null) {
  14944. delete this.sectors['support']['nodes'][edge.via.id];
  14945. }
  14946. edge.disconnect();
  14947. delete edges[id];
  14948. }
  14949. }
  14950. this.moving = true;
  14951. this._updateValueRange(edges);
  14952. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14953. this._resetLevels();
  14954. this._setupHierarchicalLayout();
  14955. }
  14956. this._updateCalculationNodes();
  14957. };
  14958. /**
  14959. * Reconnect all edges
  14960. * @private
  14961. */
  14962. Graph.prototype._reconnectEdges = function() {
  14963. var id,
  14964. nodes = this.nodes,
  14965. edges = this.edges;
  14966. for (id in nodes) {
  14967. if (nodes.hasOwnProperty(id)) {
  14968. nodes[id].edges = [];
  14969. }
  14970. }
  14971. for (id in edges) {
  14972. if (edges.hasOwnProperty(id)) {
  14973. var edge = edges[id];
  14974. edge.from = null;
  14975. edge.to = null;
  14976. edge.connect();
  14977. }
  14978. }
  14979. };
  14980. /**
  14981. * Update the values of all object in the given array according to the current
  14982. * value range of the objects in the array.
  14983. * @param {Object} obj An object containing a set of Edges or Nodes
  14984. * The objects must have a method getValue() and
  14985. * setValueRange(min, max).
  14986. * @private
  14987. */
  14988. Graph.prototype._updateValueRange = function(obj) {
  14989. var id;
  14990. // determine the range of the objects
  14991. var valueMin = undefined;
  14992. var valueMax = undefined;
  14993. for (id in obj) {
  14994. if (obj.hasOwnProperty(id)) {
  14995. var value = obj[id].getValue();
  14996. if (value !== undefined) {
  14997. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14998. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14999. }
  15000. }
  15001. }
  15002. // adjust the range of all objects
  15003. if (valueMin !== undefined && valueMax !== undefined) {
  15004. for (id in obj) {
  15005. if (obj.hasOwnProperty(id)) {
  15006. obj[id].setValueRange(valueMin, valueMax);
  15007. }
  15008. }
  15009. }
  15010. };
  15011. /**
  15012. * Redraw the graph with the current data
  15013. * chart will be resized too.
  15014. */
  15015. Graph.prototype.redraw = function() {
  15016. this.setSize(this.width, this.height);
  15017. this._redraw();
  15018. };
  15019. /**
  15020. * Redraw the graph with the current data
  15021. * @private
  15022. */
  15023. Graph.prototype._redraw = function() {
  15024. var ctx = this.frame.canvas.getContext('2d');
  15025. // clear the canvas
  15026. var w = this.frame.canvas.width;
  15027. var h = this.frame.canvas.height;
  15028. ctx.clearRect(0, 0, w, h);
  15029. // set scaling and translation
  15030. ctx.save();
  15031. ctx.translate(this.translation.x, this.translation.y);
  15032. ctx.scale(this.scale, this.scale);
  15033. this.canvasTopLeft = {
  15034. "x": this._canvasToX(0),
  15035. "y": this._canvasToY(0)
  15036. };
  15037. this.canvasBottomRight = {
  15038. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15039. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15040. };
  15041. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15042. this._doInAllSectors("_drawEdges",ctx);
  15043. this._doInAllSectors("_drawNodes",ctx,false);
  15044. // this._doInSupportSector("_drawNodes",ctx,true);
  15045. // this._drawTree(ctx,"#F00F0F");
  15046. // restore original scaling and translation
  15047. ctx.restore();
  15048. };
  15049. /**
  15050. * Set the translation of the graph
  15051. * @param {Number} offsetX Horizontal offset
  15052. * @param {Number} offsetY Vertical offset
  15053. * @private
  15054. */
  15055. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15056. if (this.translation === undefined) {
  15057. this.translation = {
  15058. x: 0,
  15059. y: 0
  15060. };
  15061. }
  15062. if (offsetX !== undefined) {
  15063. this.translation.x = offsetX;
  15064. }
  15065. if (offsetY !== undefined) {
  15066. this.translation.y = offsetY;
  15067. }
  15068. this.emit('viewChanged');
  15069. };
  15070. /**
  15071. * Get the translation of the graph
  15072. * @return {Object} translation An object with parameters x and y, both a number
  15073. * @private
  15074. */
  15075. Graph.prototype._getTranslation = function() {
  15076. return {
  15077. x: this.translation.x,
  15078. y: this.translation.y
  15079. };
  15080. };
  15081. /**
  15082. * Scale the graph
  15083. * @param {Number} scale Scaling factor 1.0 is unscaled
  15084. * @private
  15085. */
  15086. Graph.prototype._setScale = function(scale) {
  15087. this.scale = scale;
  15088. };
  15089. /**
  15090. * Get the current scale of the graph
  15091. * @return {Number} scale Scaling factor 1.0 is unscaled
  15092. * @private
  15093. */
  15094. Graph.prototype._getScale = function() {
  15095. return this.scale;
  15096. };
  15097. /**
  15098. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15099. * @param {number} x
  15100. * @returns {number}
  15101. * @private
  15102. */
  15103. Graph.prototype._canvasToX = function(x) {
  15104. return (x - this.translation.x) / this.scale;
  15105. };
  15106. /**
  15107. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15108. * @param {number} x
  15109. * @returns {number}
  15110. * @private
  15111. */
  15112. Graph.prototype._xToCanvas = function(x) {
  15113. return x * this.scale + this.translation.x;
  15114. };
  15115. /**
  15116. * Convert a vertical point on the HTML canvas to the y-value of the model
  15117. * @param {number} y
  15118. * @returns {number}
  15119. * @private
  15120. */
  15121. Graph.prototype._canvasToY = function(y) {
  15122. return (y - this.translation.y) / this.scale;
  15123. };
  15124. /**
  15125. * Convert an y-value in the model to a vertical point on the HTML canvas
  15126. * @param {number} y
  15127. * @returns {number}
  15128. * @private
  15129. */
  15130. Graph.prototype._yToCanvas = function(y) {
  15131. return y * this.scale + this.translation.y ;
  15132. };
  15133. /**
  15134. *
  15135. * @param {object} pos = {x: number, y: number}
  15136. * @returns {{x: number, y: number}}
  15137. * @constructor
  15138. */
  15139. Graph.prototype.DOMtoCanvas = function(pos) {
  15140. return {x:this._xToCanvas(pos.x),y:this._yToCanvas(pos.y)};
  15141. }
  15142. /**
  15143. *
  15144. * @param {object} pos = {x: number, y: number}
  15145. * @returns {{x: number, y: number}}
  15146. * @constructor
  15147. */
  15148. Graph.prototype.canvasToDOM = function(pos) {
  15149. return {x:this._canvasToX(pos.x),y:this._canvasToY(pos.y)};
  15150. }
  15151. /**
  15152. * Redraw all nodes
  15153. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15154. * @param {CanvasRenderingContext2D} ctx
  15155. * @param {Boolean} [alwaysShow]
  15156. * @private
  15157. */
  15158. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15159. if (alwaysShow === undefined) {
  15160. alwaysShow = false;
  15161. }
  15162. // first draw the unselected nodes
  15163. var nodes = this.nodes;
  15164. var selected = [];
  15165. for (var id in nodes) {
  15166. if (nodes.hasOwnProperty(id)) {
  15167. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15168. if (nodes[id].isSelected()) {
  15169. selected.push(id);
  15170. }
  15171. else {
  15172. if (nodes[id].inArea() || alwaysShow) {
  15173. nodes[id].draw(ctx);
  15174. }
  15175. }
  15176. }
  15177. }
  15178. // draw the selected nodes on top
  15179. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15180. if (nodes[selected[s]].inArea() || alwaysShow) {
  15181. nodes[selected[s]].draw(ctx);
  15182. }
  15183. }
  15184. };
  15185. /**
  15186. * Redraw all edges
  15187. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15188. * @param {CanvasRenderingContext2D} ctx
  15189. * @private
  15190. */
  15191. Graph.prototype._drawEdges = function(ctx) {
  15192. var edges = this.edges;
  15193. for (var id in edges) {
  15194. if (edges.hasOwnProperty(id)) {
  15195. var edge = edges[id];
  15196. edge.setScale(this.scale);
  15197. if (edge.connected) {
  15198. edges[id].draw(ctx);
  15199. }
  15200. }
  15201. }
  15202. };
  15203. /**
  15204. * Find a stable position for all nodes
  15205. * @private
  15206. */
  15207. Graph.prototype._stabilize = function() {
  15208. if (this.constants.freezeForStabilization == true) {
  15209. this._freezeDefinedNodes();
  15210. }
  15211. // find stable position
  15212. var count = 0;
  15213. while (this.moving && count < this.constants.stabilizationIterations) {
  15214. this._physicsTick();
  15215. count++;
  15216. }
  15217. this.zoomExtent(false,true);
  15218. if (this.constants.freezeForStabilization == true) {
  15219. this._restoreFrozenNodes();
  15220. }
  15221. this.emit("stabilized",{iterations:count});
  15222. };
  15223. /**
  15224. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15225. * because only the supportnodes for the smoothCurves have to settle.
  15226. *
  15227. * @private
  15228. */
  15229. Graph.prototype._freezeDefinedNodes = function() {
  15230. var nodes = this.nodes;
  15231. for (var id in nodes) {
  15232. if (nodes.hasOwnProperty(id)) {
  15233. if (nodes[id].x != null && nodes[id].y != null) {
  15234. nodes[id].fixedData.x = nodes[id].xFixed;
  15235. nodes[id].fixedData.y = nodes[id].yFixed;
  15236. nodes[id].xFixed = true;
  15237. nodes[id].yFixed = true;
  15238. }
  15239. }
  15240. }
  15241. };
  15242. /**
  15243. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15244. *
  15245. * @private
  15246. */
  15247. Graph.prototype._restoreFrozenNodes = function() {
  15248. var nodes = this.nodes;
  15249. for (var id in nodes) {
  15250. if (nodes.hasOwnProperty(id)) {
  15251. if (nodes[id].fixedData.x != null) {
  15252. nodes[id].xFixed = nodes[id].fixedData.x;
  15253. nodes[id].yFixed = nodes[id].fixedData.y;
  15254. }
  15255. }
  15256. }
  15257. };
  15258. /**
  15259. * Check if any of the nodes is still moving
  15260. * @param {number} vmin the minimum velocity considered as 'moving'
  15261. * @return {boolean} true if moving, false if non of the nodes is moving
  15262. * @private
  15263. */
  15264. Graph.prototype._isMoving = function(vmin) {
  15265. var nodes = this.nodes;
  15266. for (var id in nodes) {
  15267. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15268. return true;
  15269. }
  15270. }
  15271. return false;
  15272. };
  15273. /**
  15274. * /**
  15275. * Perform one discrete step for all nodes
  15276. *
  15277. * @private
  15278. */
  15279. Graph.prototype._discreteStepNodes = function() {
  15280. var interval = this.physicsDiscreteStepsize;
  15281. var nodes = this.nodes;
  15282. var nodeId;
  15283. var nodesPresent = false;
  15284. if (this.constants.maxVelocity > 0) {
  15285. for (nodeId in nodes) {
  15286. if (nodes.hasOwnProperty(nodeId)) {
  15287. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15288. nodesPresent = true;
  15289. }
  15290. }
  15291. }
  15292. else {
  15293. for (nodeId in nodes) {
  15294. if (nodes.hasOwnProperty(nodeId)) {
  15295. nodes[nodeId].discreteStep(interval);
  15296. nodesPresent = true;
  15297. }
  15298. }
  15299. }
  15300. if (nodesPresent == true) {
  15301. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15302. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15303. this.moving = true;
  15304. }
  15305. else {
  15306. this.moving = this._isMoving(vminCorrected);
  15307. }
  15308. }
  15309. };
  15310. /**
  15311. * A single simulation step (or "tick") in the physics simulation
  15312. *
  15313. * @private
  15314. */
  15315. Graph.prototype._physicsTick = function() {
  15316. if (!this.freezeSimulation) {
  15317. if (this.moving) {
  15318. this._doInAllActiveSectors("_initializeForceCalculation");
  15319. this._doInAllActiveSectors("_discreteStepNodes");
  15320. if (this.constants.smoothCurves) {
  15321. this._doInSupportSector("_discreteStepNodes");
  15322. }
  15323. this._findCenter(this._getRange())
  15324. }
  15325. }
  15326. };
  15327. /**
  15328. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15329. * It reschedules itself at the beginning of the function
  15330. *
  15331. * @private
  15332. */
  15333. Graph.prototype._animationStep = function() {
  15334. // reset the timer so a new scheduled animation step can be set
  15335. this.timer = undefined;
  15336. // handle the keyboad movement
  15337. this._handleNavigation();
  15338. // this schedules a new animation step
  15339. this.start();
  15340. // start the physics simulation
  15341. var calculationTime = Date.now();
  15342. var maxSteps = 1;
  15343. this._physicsTick();
  15344. var timeRequired = Date.now() - calculationTime;
  15345. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15346. this._physicsTick();
  15347. timeRequired = Date.now() - calculationTime;
  15348. maxSteps++;
  15349. }
  15350. // start the rendering process
  15351. var renderTime = Date.now();
  15352. this._redraw();
  15353. this.renderTime = Date.now() - renderTime;
  15354. };
  15355. if (typeof window !== 'undefined') {
  15356. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15357. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15358. }
  15359. /**
  15360. * Schedule a animation step with the refreshrate interval.
  15361. */
  15362. Graph.prototype.start = function() {
  15363. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15364. if (!this.timer) {
  15365. var ua = navigator.userAgent.toLowerCase();
  15366. var requiresTimeout = false;
  15367. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15368. requiresTimeout = true;
  15369. }
  15370. else if (ua.indexOf('safari') != -1) { // safari
  15371. if (ua.indexOf('chrome') <= -1) {
  15372. requiresTimeout = true;
  15373. }
  15374. }
  15375. if (requiresTimeout == true) {
  15376. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15377. }
  15378. else{
  15379. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15380. }
  15381. }
  15382. }
  15383. else {
  15384. this._redraw();
  15385. }
  15386. };
  15387. /**
  15388. * Move the graph according to the keyboard presses.
  15389. *
  15390. * @private
  15391. */
  15392. Graph.prototype._handleNavigation = function() {
  15393. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15394. var translation = this._getTranslation();
  15395. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15396. }
  15397. if (this.zoomIncrement != 0) {
  15398. var center = {
  15399. x: this.frame.canvas.clientWidth / 2,
  15400. y: this.frame.canvas.clientHeight / 2
  15401. };
  15402. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15403. }
  15404. };
  15405. /**
  15406. * Freeze the _animationStep
  15407. */
  15408. Graph.prototype.toggleFreeze = function() {
  15409. if (this.freezeSimulation == false) {
  15410. this.freezeSimulation = true;
  15411. }
  15412. else {
  15413. this.freezeSimulation = false;
  15414. this.start();
  15415. }
  15416. };
  15417. /**
  15418. * This function cleans the support nodes if they are not needed and adds them when they are.
  15419. *
  15420. * @param {boolean} [disableStart]
  15421. * @private
  15422. */
  15423. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15424. if (disableStart === undefined) {
  15425. disableStart = true;
  15426. }
  15427. if (this.constants.smoothCurves == true) {
  15428. this._createBezierNodes();
  15429. }
  15430. else {
  15431. // delete the support nodes
  15432. this.sectors['support']['nodes'] = {};
  15433. for (var edgeId in this.edges) {
  15434. if (this.edges.hasOwnProperty(edgeId)) {
  15435. this.edges[edgeId].smooth = false;
  15436. this.edges[edgeId].via = null;
  15437. }
  15438. }
  15439. }
  15440. this._updateCalculationNodes();
  15441. if (!disableStart) {
  15442. this.moving = true;
  15443. this.start();
  15444. }
  15445. };
  15446. /**
  15447. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  15448. * are used for the force calculation.
  15449. *
  15450. * @private
  15451. */
  15452. Graph.prototype._createBezierNodes = function() {
  15453. if (this.constants.smoothCurves == true) {
  15454. for (var edgeId in this.edges) {
  15455. if (this.edges.hasOwnProperty(edgeId)) {
  15456. var edge = this.edges[edgeId];
  15457. if (edge.via == null) {
  15458. edge.smooth = true;
  15459. var nodeId = "edgeId:".concat(edge.id);
  15460. this.sectors['support']['nodes'][nodeId] = new Node(
  15461. {id:nodeId,
  15462. mass:1,
  15463. shape:'circle',
  15464. image:"",
  15465. internalMultiplier:1
  15466. },{},{},this.constants);
  15467. edge.via = this.sectors['support']['nodes'][nodeId];
  15468. edge.via.parentEdgeId = edge.id;
  15469. edge.positionBezierNode();
  15470. }
  15471. }
  15472. }
  15473. }
  15474. };
  15475. /**
  15476. * load the functions that load the mixins into the prototype.
  15477. *
  15478. * @private
  15479. */
  15480. Graph.prototype._initializeMixinLoaders = function () {
  15481. for (var mixinFunction in graphMixinLoaders) {
  15482. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15483. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15484. }
  15485. }
  15486. };
  15487. /**
  15488. * Load the XY positions of the nodes into the dataset.
  15489. */
  15490. Graph.prototype.storePosition = function() {
  15491. var dataArray = [];
  15492. for (var nodeId in this.nodes) {
  15493. if (this.nodes.hasOwnProperty(nodeId)) {
  15494. var node = this.nodes[nodeId];
  15495. var allowedToMoveX = !this.nodes.xFixed;
  15496. var allowedToMoveY = !this.nodes.yFixed;
  15497. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15498. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15499. }
  15500. }
  15501. }
  15502. this.nodesData.update(dataArray);
  15503. };
  15504. /**
  15505. * vis.js module exports
  15506. */
  15507. var vis = {
  15508. util: util,
  15509. DataSet: DataSet,
  15510. DataView: DataView,
  15511. Range: Range,
  15512. stack: stack,
  15513. TimeStep: TimeStep,
  15514. components: {
  15515. items: {
  15516. Item: Item,
  15517. ItemBox: ItemBox,
  15518. ItemPoint: ItemPoint,
  15519. ItemRange: ItemRange
  15520. },
  15521. Component: Component,
  15522. Panel: Panel,
  15523. RootPanel: RootPanel,
  15524. ItemSet: ItemSet,
  15525. TimeAxis: TimeAxis
  15526. },
  15527. graph: {
  15528. Node: Node,
  15529. Edge: Edge,
  15530. Popup: Popup,
  15531. Groups: Groups,
  15532. Images: Images
  15533. },
  15534. Timeline: Timeline,
  15535. Graph: Graph
  15536. };
  15537. /**
  15538. * CommonJS module exports
  15539. */
  15540. if (typeof exports !== 'undefined') {
  15541. exports = vis;
  15542. }
  15543. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15544. module.exports = vis;
  15545. }
  15546. /**
  15547. * AMD module exports
  15548. */
  15549. if (typeof(define) === 'function') {
  15550. define(function () {
  15551. return vis;
  15552. });
  15553. }
  15554. /**
  15555. * Window exports
  15556. */
  15557. if (typeof window !== 'undefined') {
  15558. // attach the module to the window, load as a regular javascript file
  15559. window['vis'] = vis;
  15560. }
  15561. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15562. /**
  15563. * Expose `Emitter`.
  15564. */
  15565. module.exports = Emitter;
  15566. /**
  15567. * Initialize a new `Emitter`.
  15568. *
  15569. * @api public
  15570. */
  15571. function Emitter(obj) {
  15572. if (obj) return mixin(obj);
  15573. };
  15574. /**
  15575. * Mixin the emitter properties.
  15576. *
  15577. * @param {Object} obj
  15578. * @return {Object}
  15579. * @api private
  15580. */
  15581. function mixin(obj) {
  15582. for (var key in Emitter.prototype) {
  15583. obj[key] = Emitter.prototype[key];
  15584. }
  15585. return obj;
  15586. }
  15587. /**
  15588. * Listen on the given `event` with `fn`.
  15589. *
  15590. * @param {String} event
  15591. * @param {Function} fn
  15592. * @return {Emitter}
  15593. * @api public
  15594. */
  15595. Emitter.prototype.on =
  15596. Emitter.prototype.addEventListener = function(event, fn){
  15597. this._callbacks = this._callbacks || {};
  15598. (this._callbacks[event] = this._callbacks[event] || [])
  15599. .push(fn);
  15600. return this;
  15601. };
  15602. /**
  15603. * Adds an `event` listener that will be invoked a single
  15604. * time then automatically removed.
  15605. *
  15606. * @param {String} event
  15607. * @param {Function} fn
  15608. * @return {Emitter}
  15609. * @api public
  15610. */
  15611. Emitter.prototype.once = function(event, fn){
  15612. var self = this;
  15613. this._callbacks = this._callbacks || {};
  15614. function on() {
  15615. self.off(event, on);
  15616. fn.apply(this, arguments);
  15617. }
  15618. on.fn = fn;
  15619. this.on(event, on);
  15620. return this;
  15621. };
  15622. /**
  15623. * Remove the given callback for `event` or all
  15624. * registered callbacks.
  15625. *
  15626. * @param {String} event
  15627. * @param {Function} fn
  15628. * @return {Emitter}
  15629. * @api public
  15630. */
  15631. Emitter.prototype.off =
  15632. Emitter.prototype.removeListener =
  15633. Emitter.prototype.removeAllListeners =
  15634. Emitter.prototype.removeEventListener = function(event, fn){
  15635. this._callbacks = this._callbacks || {};
  15636. // all
  15637. if (0 == arguments.length) {
  15638. this._callbacks = {};
  15639. return this;
  15640. }
  15641. // specific event
  15642. var callbacks = this._callbacks[event];
  15643. if (!callbacks) return this;
  15644. // remove all handlers
  15645. if (1 == arguments.length) {
  15646. delete this._callbacks[event];
  15647. return this;
  15648. }
  15649. // remove specific handler
  15650. var cb;
  15651. for (var i = 0; i < callbacks.length; i++) {
  15652. cb = callbacks[i];
  15653. if (cb === fn || cb.fn === fn) {
  15654. callbacks.splice(i, 1);
  15655. break;
  15656. }
  15657. }
  15658. return this;
  15659. };
  15660. /**
  15661. * Emit `event` with the given args.
  15662. *
  15663. * @param {String} event
  15664. * @param {Mixed} ...
  15665. * @return {Emitter}
  15666. */
  15667. Emitter.prototype.emit = function(event){
  15668. this._callbacks = this._callbacks || {};
  15669. var args = [].slice.call(arguments, 1)
  15670. , callbacks = this._callbacks[event];
  15671. if (callbacks) {
  15672. callbacks = callbacks.slice(0);
  15673. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15674. callbacks[i].apply(this, args);
  15675. }
  15676. }
  15677. return this;
  15678. };
  15679. /**
  15680. * Return array of callbacks for `event`.
  15681. *
  15682. * @param {String} event
  15683. * @return {Array}
  15684. * @api public
  15685. */
  15686. Emitter.prototype.listeners = function(event){
  15687. this._callbacks = this._callbacks || {};
  15688. return this._callbacks[event] || [];
  15689. };
  15690. /**
  15691. * Check if this emitter has `event` handlers.
  15692. *
  15693. * @param {String} event
  15694. * @return {Boolean}
  15695. * @api public
  15696. */
  15697. Emitter.prototype.hasListeners = function(event){
  15698. return !! this.listeners(event).length;
  15699. };
  15700. },{}],3:[function(require,module,exports){
  15701. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15702. * http://eightmedia.github.com/hammer.js
  15703. *
  15704. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15705. * Licensed under the MIT license */
  15706. (function(window, undefined) {
  15707. 'use strict';
  15708. /**
  15709. * Hammer
  15710. * use this to create instances
  15711. * @param {HTMLElement} element
  15712. * @param {Object} options
  15713. * @returns {Hammer.Instance}
  15714. * @constructor
  15715. */
  15716. var Hammer = function(element, options) {
  15717. return new Hammer.Instance(element, options || {});
  15718. };
  15719. // default settings
  15720. Hammer.defaults = {
  15721. // add styles and attributes to the element to prevent the browser from doing
  15722. // its native behavior. this doesnt prevent the scrolling, but cancels
  15723. // the contextmenu, tap highlighting etc
  15724. // set to false to disable this
  15725. stop_browser_behavior: {
  15726. // this also triggers onselectstart=false for IE
  15727. userSelect: 'none',
  15728. // this makes the element blocking in IE10 >, you could experiment with the value
  15729. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15730. touchAction: 'none',
  15731. touchCallout: 'none',
  15732. contentZooming: 'none',
  15733. userDrag: 'none',
  15734. tapHighlightColor: 'rgba(0,0,0,0)'
  15735. }
  15736. // more settings are defined per gesture at gestures.js
  15737. };
  15738. // detect touchevents
  15739. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15740. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15741. // dont use mouseevents on mobile devices
  15742. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15743. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15744. // eventtypes per touchevent (start, move, end)
  15745. // are filled by Hammer.event.determineEventTypes on setup
  15746. Hammer.EVENT_TYPES = {};
  15747. // direction defines
  15748. Hammer.DIRECTION_DOWN = 'down';
  15749. Hammer.DIRECTION_LEFT = 'left';
  15750. Hammer.DIRECTION_UP = 'up';
  15751. Hammer.DIRECTION_RIGHT = 'right';
  15752. // pointer type
  15753. Hammer.POINTER_MOUSE = 'mouse';
  15754. Hammer.POINTER_TOUCH = 'touch';
  15755. Hammer.POINTER_PEN = 'pen';
  15756. // touch event defines
  15757. Hammer.EVENT_START = 'start';
  15758. Hammer.EVENT_MOVE = 'move';
  15759. Hammer.EVENT_END = 'end';
  15760. // hammer document where the base events are added at
  15761. Hammer.DOCUMENT = document;
  15762. // plugins namespace
  15763. Hammer.plugins = {};
  15764. // if the window events are set...
  15765. Hammer.READY = false;
  15766. /**
  15767. * setup events to detect gestures on the document
  15768. */
  15769. function setup() {
  15770. if(Hammer.READY) {
  15771. return;
  15772. }
  15773. // find what eventtypes we add listeners to
  15774. Hammer.event.determineEventTypes();
  15775. // Register all gestures inside Hammer.gestures
  15776. for(var name in Hammer.gestures) {
  15777. if(Hammer.gestures.hasOwnProperty(name)) {
  15778. Hammer.detection.register(Hammer.gestures[name]);
  15779. }
  15780. }
  15781. // Add touch events on the document
  15782. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15783. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15784. // Hammer is ready...!
  15785. Hammer.READY = true;
  15786. }
  15787. /**
  15788. * create new hammer instance
  15789. * all methods should return the instance itself, so it is chainable.
  15790. * @param {HTMLElement} element
  15791. * @param {Object} [options={}]
  15792. * @returns {Hammer.Instance}
  15793. * @constructor
  15794. */
  15795. Hammer.Instance = function(element, options) {
  15796. var self = this;
  15797. // setup HammerJS window events and register all gestures
  15798. // this also sets up the default options
  15799. setup();
  15800. this.element = element;
  15801. // start/stop detection option
  15802. this.enabled = true;
  15803. // merge options
  15804. this.options = Hammer.utils.extend(
  15805. Hammer.utils.extend({}, Hammer.defaults),
  15806. options || {});
  15807. // add some css to the element to prevent the browser from doing its native behavoir
  15808. if(this.options.stop_browser_behavior) {
  15809. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15810. }
  15811. // start detection on touchstart
  15812. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15813. if(self.enabled) {
  15814. Hammer.detection.startDetect(self, ev);
  15815. }
  15816. });
  15817. // return instance
  15818. return this;
  15819. };
  15820. Hammer.Instance.prototype = {
  15821. /**
  15822. * bind events to the instance
  15823. * @param {String} gesture
  15824. * @param {Function} handler
  15825. * @returns {Hammer.Instance}
  15826. */
  15827. on: function onEvent(gesture, handler){
  15828. var gestures = gesture.split(' ');
  15829. for(var t=0; t<gestures.length; t++) {
  15830. this.element.addEventListener(gestures[t], handler, false);
  15831. }
  15832. return this;
  15833. },
  15834. /**
  15835. * unbind events to the instance
  15836. * @param {String} gesture
  15837. * @param {Function} handler
  15838. * @returns {Hammer.Instance}
  15839. */
  15840. off: function offEvent(gesture, handler){
  15841. var gestures = gesture.split(' ');
  15842. for(var t=0; t<gestures.length; t++) {
  15843. this.element.removeEventListener(gestures[t], handler, false);
  15844. }
  15845. return this;
  15846. },
  15847. /**
  15848. * trigger gesture event
  15849. * @param {String} gesture
  15850. * @param {Object} eventData
  15851. * @returns {Hammer.Instance}
  15852. */
  15853. trigger: function triggerEvent(gesture, eventData){
  15854. // create DOM event
  15855. var event = Hammer.DOCUMENT.createEvent('Event');
  15856. event.initEvent(gesture, true, true);
  15857. event.gesture = eventData;
  15858. // trigger on the target if it is in the instance element,
  15859. // this is for event delegation tricks
  15860. var element = this.element;
  15861. if(Hammer.utils.hasParent(eventData.target, element)) {
  15862. element = eventData.target;
  15863. }
  15864. element.dispatchEvent(event);
  15865. return this;
  15866. },
  15867. /**
  15868. * enable of disable hammer.js detection
  15869. * @param {Boolean} state
  15870. * @returns {Hammer.Instance}
  15871. */
  15872. enable: function enable(state) {
  15873. this.enabled = state;
  15874. return this;
  15875. }
  15876. };
  15877. /**
  15878. * this holds the last move event,
  15879. * used to fix empty touchend issue
  15880. * see the onTouch event for an explanation
  15881. * @type {Object}
  15882. */
  15883. var last_move_event = null;
  15884. /**
  15885. * when the mouse is hold down, this is true
  15886. * @type {Boolean}
  15887. */
  15888. var enable_detect = false;
  15889. /**
  15890. * when touch events have been fired, this is true
  15891. * @type {Boolean}
  15892. */
  15893. var touch_triggered = false;
  15894. Hammer.event = {
  15895. /**
  15896. * simple addEventListener
  15897. * @param {HTMLElement} element
  15898. * @param {String} type
  15899. * @param {Function} handler
  15900. */
  15901. bindDom: function(element, type, handler) {
  15902. var types = type.split(' ');
  15903. for(var t=0; t<types.length; t++) {
  15904. element.addEventListener(types[t], handler, false);
  15905. }
  15906. },
  15907. /**
  15908. * touch events with mouse fallback
  15909. * @param {HTMLElement} element
  15910. * @param {String} eventType like Hammer.EVENT_MOVE
  15911. * @param {Function} handler
  15912. */
  15913. onTouch: function onTouch(element, eventType, handler) {
  15914. var self = this;
  15915. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15916. var sourceEventType = ev.type.toLowerCase();
  15917. // onmouseup, but when touchend has been fired we do nothing.
  15918. // this is for touchdevices which also fire a mouseup on touchend
  15919. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15920. return;
  15921. }
  15922. // mousebutton must be down or a touch event
  15923. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15924. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15925. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15926. ){
  15927. enable_detect = true;
  15928. }
  15929. // we are in a touch event, set the touch triggered bool to true,
  15930. // this for the conflicts that may occur on ios and android
  15931. if(sourceEventType.match(/touch|pointer/)) {
  15932. touch_triggered = true;
  15933. }
  15934. // count the total touches on the screen
  15935. var count_touches = 0;
  15936. // when touch has been triggered in this detection session
  15937. // and we are now handling a mouse event, we stop that to prevent conflicts
  15938. if(enable_detect) {
  15939. // update pointerevent
  15940. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15941. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15942. }
  15943. // touch
  15944. else if(sourceEventType.match(/touch/)) {
  15945. count_touches = ev.touches.length;
  15946. }
  15947. // mouse
  15948. else if(!touch_triggered) {
  15949. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15950. }
  15951. // if we are in a end event, but when we remove one touch and
  15952. // we still have enough, set eventType to move
  15953. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15954. eventType = Hammer.EVENT_MOVE;
  15955. }
  15956. // no touches, force the end event
  15957. else if(!count_touches) {
  15958. eventType = Hammer.EVENT_END;
  15959. }
  15960. // because touchend has no touches, and we often want to use these in our gestures,
  15961. // we send the last move event as our eventData in touchend
  15962. if(!count_touches && last_move_event !== null) {
  15963. ev = last_move_event;
  15964. }
  15965. // store the last move event
  15966. else {
  15967. last_move_event = ev;
  15968. }
  15969. // trigger the handler
  15970. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15971. // remove pointerevent from list
  15972. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15973. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15974. }
  15975. }
  15976. //debug(sourceEventType +" "+ eventType);
  15977. // on the end we reset everything
  15978. if(!count_touches) {
  15979. last_move_event = null;
  15980. enable_detect = false;
  15981. touch_triggered = false;
  15982. Hammer.PointerEvent.reset();
  15983. }
  15984. });
  15985. },
  15986. /**
  15987. * we have different events for each device/browser
  15988. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15989. */
  15990. determineEventTypes: function determineEventTypes() {
  15991. // determine the eventtype we want to set
  15992. var types;
  15993. // pointerEvents magic
  15994. if(Hammer.HAS_POINTEREVENTS) {
  15995. types = Hammer.PointerEvent.getEvents();
  15996. }
  15997. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15998. else if(Hammer.NO_MOUSEEVENTS) {
  15999. types = [
  16000. 'touchstart',
  16001. 'touchmove',
  16002. 'touchend touchcancel'];
  16003. }
  16004. // for non pointer events browsers and mixed browsers,
  16005. // like chrome on windows8 touch laptop
  16006. else {
  16007. types = [
  16008. 'touchstart mousedown',
  16009. 'touchmove mousemove',
  16010. 'touchend touchcancel mouseup'];
  16011. }
  16012. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16013. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16014. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16015. },
  16016. /**
  16017. * create touchlist depending on the event
  16018. * @param {Object} ev
  16019. * @param {String} eventType used by the fakemultitouch plugin
  16020. */
  16021. getTouchList: function getTouchList(ev/*, eventType*/) {
  16022. // get the fake pointerEvent touchlist
  16023. if(Hammer.HAS_POINTEREVENTS) {
  16024. return Hammer.PointerEvent.getTouchList();
  16025. }
  16026. // get the touchlist
  16027. else if(ev.touches) {
  16028. return ev.touches;
  16029. }
  16030. // make fake touchlist from mouse position
  16031. else {
  16032. return [{
  16033. identifier: 1,
  16034. pageX: ev.pageX,
  16035. pageY: ev.pageY,
  16036. target: ev.target
  16037. }];
  16038. }
  16039. },
  16040. /**
  16041. * collect event data for Hammer js
  16042. * @param {HTMLElement} element
  16043. * @param {String} eventType like Hammer.EVENT_MOVE
  16044. * @param {Object} eventData
  16045. */
  16046. collectEventData: function collectEventData(element, eventType, ev) {
  16047. var touches = this.getTouchList(ev, eventType);
  16048. // find out pointerType
  16049. var pointerType = Hammer.POINTER_TOUCH;
  16050. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16051. pointerType = Hammer.POINTER_MOUSE;
  16052. }
  16053. return {
  16054. center : Hammer.utils.getCenter(touches),
  16055. timeStamp : new Date().getTime(),
  16056. target : ev.target,
  16057. touches : touches,
  16058. eventType : eventType,
  16059. pointerType : pointerType,
  16060. srcEvent : ev,
  16061. /**
  16062. * prevent the browser default actions
  16063. * mostly used to disable scrolling of the browser
  16064. */
  16065. preventDefault: function() {
  16066. if(this.srcEvent.preventManipulation) {
  16067. this.srcEvent.preventManipulation();
  16068. }
  16069. if(this.srcEvent.preventDefault) {
  16070. this.srcEvent.preventDefault();
  16071. }
  16072. },
  16073. /**
  16074. * stop bubbling the event up to its parents
  16075. */
  16076. stopPropagation: function() {
  16077. this.srcEvent.stopPropagation();
  16078. },
  16079. /**
  16080. * immediately stop gesture detection
  16081. * might be useful after a swipe was detected
  16082. * @return {*}
  16083. */
  16084. stopDetect: function() {
  16085. return Hammer.detection.stopDetect();
  16086. }
  16087. };
  16088. }
  16089. };
  16090. Hammer.PointerEvent = {
  16091. /**
  16092. * holds all pointers
  16093. * @type {Object}
  16094. */
  16095. pointers: {},
  16096. /**
  16097. * get a list of pointers
  16098. * @returns {Array} touchlist
  16099. */
  16100. getTouchList: function() {
  16101. var self = this;
  16102. var touchlist = [];
  16103. // we can use forEach since pointerEvents only is in IE10
  16104. Object.keys(self.pointers).sort().forEach(function(id) {
  16105. touchlist.push(self.pointers[id]);
  16106. });
  16107. return touchlist;
  16108. },
  16109. /**
  16110. * update the position of a pointer
  16111. * @param {String} type Hammer.EVENT_END
  16112. * @param {Object} pointerEvent
  16113. */
  16114. updatePointer: function(type, pointerEvent) {
  16115. if(type == Hammer.EVENT_END) {
  16116. this.pointers = {};
  16117. }
  16118. else {
  16119. pointerEvent.identifier = pointerEvent.pointerId;
  16120. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16121. }
  16122. return Object.keys(this.pointers).length;
  16123. },
  16124. /**
  16125. * check if ev matches pointertype
  16126. * @param {String} pointerType Hammer.POINTER_MOUSE
  16127. * @param {PointerEvent} ev
  16128. */
  16129. matchType: function(pointerType, ev) {
  16130. if(!ev.pointerType) {
  16131. return false;
  16132. }
  16133. var types = {};
  16134. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16135. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16136. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16137. return types[pointerType];
  16138. },
  16139. /**
  16140. * get events
  16141. */
  16142. getEvents: function() {
  16143. return [
  16144. 'pointerdown MSPointerDown',
  16145. 'pointermove MSPointerMove',
  16146. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16147. ];
  16148. },
  16149. /**
  16150. * reset the list
  16151. */
  16152. reset: function() {
  16153. this.pointers = {};
  16154. }
  16155. };
  16156. Hammer.utils = {
  16157. /**
  16158. * extend method,
  16159. * also used for cloning when dest is an empty object
  16160. * @param {Object} dest
  16161. * @param {Object} src
  16162. * @parm {Boolean} merge do a merge
  16163. * @returns {Object} dest
  16164. */
  16165. extend: function extend(dest, src, merge) {
  16166. for (var key in src) {
  16167. if(dest[key] !== undefined && merge) {
  16168. continue;
  16169. }
  16170. dest[key] = src[key];
  16171. }
  16172. return dest;
  16173. },
  16174. /**
  16175. * find if a node is in the given parent
  16176. * used for event delegation tricks
  16177. * @param {HTMLElement} node
  16178. * @param {HTMLElement} parent
  16179. * @returns {boolean} has_parent
  16180. */
  16181. hasParent: function(node, parent) {
  16182. while(node){
  16183. if(node == parent) {
  16184. return true;
  16185. }
  16186. node = node.parentNode;
  16187. }
  16188. return false;
  16189. },
  16190. /**
  16191. * get the center of all the touches
  16192. * @param {Array} touches
  16193. * @returns {Object} center
  16194. */
  16195. getCenter: function getCenter(touches) {
  16196. var valuesX = [], valuesY = [];
  16197. for(var t= 0,len=touches.length; t<len; t++) {
  16198. valuesX.push(touches[t].pageX);
  16199. valuesY.push(touches[t].pageY);
  16200. }
  16201. return {
  16202. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16203. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16204. };
  16205. },
  16206. /**
  16207. * calculate the velocity between two points
  16208. * @param {Number} delta_time
  16209. * @param {Number} delta_x
  16210. * @param {Number} delta_y
  16211. * @returns {Object} velocity
  16212. */
  16213. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16214. return {
  16215. x: Math.abs(delta_x / delta_time) || 0,
  16216. y: Math.abs(delta_y / delta_time) || 0
  16217. };
  16218. },
  16219. /**
  16220. * calculate the angle between two coordinates
  16221. * @param {Touch} touch1
  16222. * @param {Touch} touch2
  16223. * @returns {Number} angle
  16224. */
  16225. getAngle: function getAngle(touch1, touch2) {
  16226. var y = touch2.pageY - touch1.pageY,
  16227. x = touch2.pageX - touch1.pageX;
  16228. return Math.atan2(y, x) * 180 / Math.PI;
  16229. },
  16230. /**
  16231. * angle to direction define
  16232. * @param {Touch} touch1
  16233. * @param {Touch} touch2
  16234. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16235. */
  16236. getDirection: function getDirection(touch1, touch2) {
  16237. var x = Math.abs(touch1.pageX - touch2.pageX),
  16238. y = Math.abs(touch1.pageY - touch2.pageY);
  16239. if(x >= y) {
  16240. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16241. }
  16242. else {
  16243. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16244. }
  16245. },
  16246. /**
  16247. * calculate the distance between two touches
  16248. * @param {Touch} touch1
  16249. * @param {Touch} touch2
  16250. * @returns {Number} distance
  16251. */
  16252. getDistance: function getDistance(touch1, touch2) {
  16253. var x = touch2.pageX - touch1.pageX,
  16254. y = touch2.pageY - touch1.pageY;
  16255. return Math.sqrt((x*x) + (y*y));
  16256. },
  16257. /**
  16258. * calculate the scale factor between two touchLists (fingers)
  16259. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16260. * @param {Array} start
  16261. * @param {Array} end
  16262. * @returns {Number} scale
  16263. */
  16264. getScale: function getScale(start, end) {
  16265. // need two fingers...
  16266. if(start.length >= 2 && end.length >= 2) {
  16267. return this.getDistance(end[0], end[1]) /
  16268. this.getDistance(start[0], start[1]);
  16269. }
  16270. return 1;
  16271. },
  16272. /**
  16273. * calculate the rotation degrees between two touchLists (fingers)
  16274. * @param {Array} start
  16275. * @param {Array} end
  16276. * @returns {Number} rotation
  16277. */
  16278. getRotation: function getRotation(start, end) {
  16279. // need two fingers
  16280. if(start.length >= 2 && end.length >= 2) {
  16281. return this.getAngle(end[1], end[0]) -
  16282. this.getAngle(start[1], start[0]);
  16283. }
  16284. return 0;
  16285. },
  16286. /**
  16287. * boolean if the direction is vertical
  16288. * @param {String} direction
  16289. * @returns {Boolean} is_vertical
  16290. */
  16291. isVertical: function isVertical(direction) {
  16292. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16293. },
  16294. /**
  16295. * stop browser default behavior with css props
  16296. * @param {HtmlElement} element
  16297. * @param {Object} css_props
  16298. */
  16299. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16300. var prop,
  16301. vendors = ['webkit','khtml','moz','ms','o',''];
  16302. if(!css_props || !element.style) {
  16303. return;
  16304. }
  16305. // with css properties for modern browsers
  16306. for(var i = 0; i < vendors.length; i++) {
  16307. for(var p in css_props) {
  16308. if(css_props.hasOwnProperty(p)) {
  16309. prop = p;
  16310. // vender prefix at the property
  16311. if(vendors[i]) {
  16312. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16313. }
  16314. // set the style
  16315. element.style[prop] = css_props[p];
  16316. }
  16317. }
  16318. }
  16319. // also the disable onselectstart
  16320. if(css_props.userSelect == 'none') {
  16321. element.onselectstart = function() {
  16322. return false;
  16323. };
  16324. }
  16325. }
  16326. };
  16327. Hammer.detection = {
  16328. // contains all registred Hammer.gestures in the correct order
  16329. gestures: [],
  16330. // data of the current Hammer.gesture detection session
  16331. current: null,
  16332. // the previous Hammer.gesture session data
  16333. // is a full clone of the previous gesture.current object
  16334. previous: null,
  16335. // when this becomes true, no gestures are fired
  16336. stopped: false,
  16337. /**
  16338. * start Hammer.gesture detection
  16339. * @param {Hammer.Instance} inst
  16340. * @param {Object} eventData
  16341. */
  16342. startDetect: function startDetect(inst, eventData) {
  16343. // already busy with a Hammer.gesture detection on an element
  16344. if(this.current) {
  16345. return;
  16346. }
  16347. this.stopped = false;
  16348. this.current = {
  16349. inst : inst, // reference to HammerInstance we're working for
  16350. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16351. lastEvent : false, // last eventData
  16352. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16353. };
  16354. this.detect(eventData);
  16355. },
  16356. /**
  16357. * Hammer.gesture detection
  16358. * @param {Object} eventData
  16359. * @param {Object} eventData
  16360. */
  16361. detect: function detect(eventData) {
  16362. if(!this.current || this.stopped) {
  16363. return;
  16364. }
  16365. // extend event data with calculations about scale, distance etc
  16366. eventData = this.extendEventData(eventData);
  16367. // instance options
  16368. var inst_options = this.current.inst.options;
  16369. // call Hammer.gesture handlers
  16370. for(var g=0,len=this.gestures.length; g<len; g++) {
  16371. var gesture = this.gestures[g];
  16372. // only when the instance options have enabled this gesture
  16373. if(!this.stopped && inst_options[gesture.name] !== false) {
  16374. // if a handler returns false, we stop with the detection
  16375. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16376. this.stopDetect();
  16377. break;
  16378. }
  16379. }
  16380. }
  16381. // store as previous event event
  16382. if(this.current) {
  16383. this.current.lastEvent = eventData;
  16384. }
  16385. // endevent, but not the last touch, so dont stop
  16386. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16387. this.stopDetect();
  16388. }
  16389. return eventData;
  16390. },
  16391. /**
  16392. * clear the Hammer.gesture vars
  16393. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16394. * to stop other Hammer.gestures from being fired
  16395. */
  16396. stopDetect: function stopDetect() {
  16397. // clone current data to the store as the previous gesture
  16398. // used for the double tap gesture, since this is an other gesture detect session
  16399. this.previous = Hammer.utils.extend({}, this.current);
  16400. // reset the current
  16401. this.current = null;
  16402. // stopped!
  16403. this.stopped = true;
  16404. },
  16405. /**
  16406. * extend eventData for Hammer.gestures
  16407. * @param {Object} ev
  16408. * @returns {Object} ev
  16409. */
  16410. extendEventData: function extendEventData(ev) {
  16411. var startEv = this.current.startEvent;
  16412. // if the touches change, set the new touches over the startEvent touches
  16413. // this because touchevents don't have all the touches on touchstart, or the
  16414. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16415. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16416. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16417. // extend 1 level deep to get the touchlist with the touch objects
  16418. startEv.touches = [];
  16419. for(var i=0,len=ev.touches.length; i<len; i++) {
  16420. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16421. }
  16422. }
  16423. var delta_time = ev.timeStamp - startEv.timeStamp,
  16424. delta_x = ev.center.pageX - startEv.center.pageX,
  16425. delta_y = ev.center.pageY - startEv.center.pageY,
  16426. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16427. Hammer.utils.extend(ev, {
  16428. deltaTime : delta_time,
  16429. deltaX : delta_x,
  16430. deltaY : delta_y,
  16431. velocityX : velocity.x,
  16432. velocityY : velocity.y,
  16433. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16434. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16435. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16436. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16437. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16438. startEvent : startEv
  16439. });
  16440. return ev;
  16441. },
  16442. /**
  16443. * register new gesture
  16444. * @param {Object} gesture object, see gestures.js for documentation
  16445. * @returns {Array} gestures
  16446. */
  16447. register: function register(gesture) {
  16448. // add an enable gesture options if there is no given
  16449. var options = gesture.defaults || {};
  16450. if(options[gesture.name] === undefined) {
  16451. options[gesture.name] = true;
  16452. }
  16453. // extend Hammer default options with the Hammer.gesture options
  16454. Hammer.utils.extend(Hammer.defaults, options, true);
  16455. // set its index
  16456. gesture.index = gesture.index || 1000;
  16457. // add Hammer.gesture to the list
  16458. this.gestures.push(gesture);
  16459. // sort the list by index
  16460. this.gestures.sort(function(a, b) {
  16461. if (a.index < b.index) {
  16462. return -1;
  16463. }
  16464. if (a.index > b.index) {
  16465. return 1;
  16466. }
  16467. return 0;
  16468. });
  16469. return this.gestures;
  16470. }
  16471. };
  16472. Hammer.gestures = Hammer.gestures || {};
  16473. /**
  16474. * Custom gestures
  16475. * ==============================
  16476. *
  16477. * Gesture object
  16478. * --------------------
  16479. * The object structure of a gesture:
  16480. *
  16481. * { name: 'mygesture',
  16482. * index: 1337,
  16483. * defaults: {
  16484. * mygesture_option: true
  16485. * }
  16486. * handler: function(type, ev, inst) {
  16487. * // trigger gesture event
  16488. * inst.trigger(this.name, ev);
  16489. * }
  16490. * }
  16491. * @param {String} name
  16492. * this should be the name of the gesture, lowercase
  16493. * it is also being used to disable/enable the gesture per instance config.
  16494. *
  16495. * @param {Number} [index=1000]
  16496. * the index of the gesture, where it is going to be in the stack of gestures detection
  16497. * like when you build an gesture that depends on the drag gesture, it is a good
  16498. * idea to place it after the index of the drag gesture.
  16499. *
  16500. * @param {Object} [defaults={}]
  16501. * the default settings of the gesture. these are added to the instance settings,
  16502. * and can be overruled per instance. you can also add the name of the gesture,
  16503. * but this is also added by default (and set to true).
  16504. *
  16505. * @param {Function} handler
  16506. * this handles the gesture detection of your custom gesture and receives the
  16507. * following arguments:
  16508. *
  16509. * @param {Object} eventData
  16510. * event data containing the following properties:
  16511. * timeStamp {Number} time the event occurred
  16512. * target {HTMLElement} target element
  16513. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16514. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16515. * center {Object} center position of the touches. contains pageX and pageY
  16516. * deltaTime {Number} the total time of the touches in the screen
  16517. * deltaX {Number} the delta on x axis we haved moved
  16518. * deltaY {Number} the delta on y axis we haved moved
  16519. * velocityX {Number} the velocity on the x
  16520. * velocityY {Number} the velocity on y
  16521. * angle {Number} the angle we are moving
  16522. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16523. * distance {Number} the distance we haved moved
  16524. * scale {Number} scaling of the touches, needs 2 touches
  16525. * rotation {Number} rotation of the touches, needs 2 touches *
  16526. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16527. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16528. * startEvent {Object} contains the same properties as above,
  16529. * but from the first touch. this is used to calculate
  16530. * distances, deltaTime, scaling etc
  16531. *
  16532. * @param {Hammer.Instance} inst
  16533. * the instance we are doing the detection for. you can get the options from
  16534. * the inst.options object and trigger the gesture event by calling inst.trigger
  16535. *
  16536. *
  16537. * Handle gestures
  16538. * --------------------
  16539. * inside the handler you can get/set Hammer.detection.current. This is the current
  16540. * detection session. It has the following properties
  16541. * @param {String} name
  16542. * contains the name of the gesture we have detected. it has not a real function,
  16543. * only to check in other gestures if something is detected.
  16544. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16545. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16546. *
  16547. * @readonly
  16548. * @param {Hammer.Instance} inst
  16549. * the instance we do the detection for
  16550. *
  16551. * @readonly
  16552. * @param {Object} startEvent
  16553. * contains the properties of the first gesture detection in this session.
  16554. * Used for calculations about timing, distance, etc.
  16555. *
  16556. * @readonly
  16557. * @param {Object} lastEvent
  16558. * contains all the properties of the last gesture detect in this session.
  16559. *
  16560. * after the gesture detection session has been completed (user has released the screen)
  16561. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16562. * this is usefull for gestures like doubletap, where you need to know if the
  16563. * previous gesture was a tap
  16564. *
  16565. * options that have been set by the instance can be received by calling inst.options
  16566. *
  16567. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16568. * The first param is the name of your gesture, the second the event argument
  16569. *
  16570. *
  16571. * Register gestures
  16572. * --------------------
  16573. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16574. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16575. * manually and pass your gesture object as a param
  16576. *
  16577. */
  16578. /**
  16579. * Hold
  16580. * Touch stays at the same place for x time
  16581. * @events hold
  16582. */
  16583. Hammer.gestures.Hold = {
  16584. name: 'hold',
  16585. index: 10,
  16586. defaults: {
  16587. hold_timeout : 500,
  16588. hold_threshold : 1
  16589. },
  16590. timer: null,
  16591. handler: function holdGesture(ev, inst) {
  16592. switch(ev.eventType) {
  16593. case Hammer.EVENT_START:
  16594. // clear any running timers
  16595. clearTimeout(this.timer);
  16596. // set the gesture so we can check in the timeout if it still is
  16597. Hammer.detection.current.name = this.name;
  16598. // set timer and if after the timeout it still is hold,
  16599. // we trigger the hold event
  16600. this.timer = setTimeout(function() {
  16601. if(Hammer.detection.current.name == 'hold') {
  16602. inst.trigger('hold', ev);
  16603. }
  16604. }, inst.options.hold_timeout);
  16605. break;
  16606. // when you move or end we clear the timer
  16607. case Hammer.EVENT_MOVE:
  16608. if(ev.distance > inst.options.hold_threshold) {
  16609. clearTimeout(this.timer);
  16610. }
  16611. break;
  16612. case Hammer.EVENT_END:
  16613. clearTimeout(this.timer);
  16614. break;
  16615. }
  16616. }
  16617. };
  16618. /**
  16619. * Tap/DoubleTap
  16620. * Quick touch at a place or double at the same place
  16621. * @events tap, doubletap
  16622. */
  16623. Hammer.gestures.Tap = {
  16624. name: 'tap',
  16625. index: 100,
  16626. defaults: {
  16627. tap_max_touchtime : 250,
  16628. tap_max_distance : 10,
  16629. tap_always : true,
  16630. doubletap_distance : 20,
  16631. doubletap_interval : 300
  16632. },
  16633. handler: function tapGesture(ev, inst) {
  16634. if(ev.eventType == Hammer.EVENT_END) {
  16635. // previous gesture, for the double tap since these are two different gesture detections
  16636. var prev = Hammer.detection.previous,
  16637. did_doubletap = false;
  16638. // when the touchtime is higher then the max touch time
  16639. // or when the moving distance is too much
  16640. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16641. ev.distance > inst.options.tap_max_distance) {
  16642. return;
  16643. }
  16644. // check if double tap
  16645. if(prev && prev.name == 'tap' &&
  16646. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16647. ev.distance < inst.options.doubletap_distance) {
  16648. inst.trigger('doubletap', ev);
  16649. did_doubletap = true;
  16650. }
  16651. // do a single tap
  16652. if(!did_doubletap || inst.options.tap_always) {
  16653. Hammer.detection.current.name = 'tap';
  16654. inst.trigger(Hammer.detection.current.name, ev);
  16655. }
  16656. }
  16657. }
  16658. };
  16659. /**
  16660. * Swipe
  16661. * triggers swipe events when the end velocity is above the threshold
  16662. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16663. */
  16664. Hammer.gestures.Swipe = {
  16665. name: 'swipe',
  16666. index: 40,
  16667. defaults: {
  16668. // set 0 for unlimited, but this can conflict with transform
  16669. swipe_max_touches : 1,
  16670. swipe_velocity : 0.7
  16671. },
  16672. handler: function swipeGesture(ev, inst) {
  16673. if(ev.eventType == Hammer.EVENT_END) {
  16674. // max touches
  16675. if(inst.options.swipe_max_touches > 0 &&
  16676. ev.touches.length > inst.options.swipe_max_touches) {
  16677. return;
  16678. }
  16679. // when the distance we moved is too small we skip this gesture
  16680. // or we can be already in dragging
  16681. if(ev.velocityX > inst.options.swipe_velocity ||
  16682. ev.velocityY > inst.options.swipe_velocity) {
  16683. // trigger swipe events
  16684. inst.trigger(this.name, ev);
  16685. inst.trigger(this.name + ev.direction, ev);
  16686. }
  16687. }
  16688. }
  16689. };
  16690. /**
  16691. * Drag
  16692. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16693. * moving left and right is a good practice. When all the drag events are blocking
  16694. * you disable scrolling on that area.
  16695. * @events drag, drapleft, dragright, dragup, dragdown
  16696. */
  16697. Hammer.gestures.Drag = {
  16698. name: 'drag',
  16699. index: 50,
  16700. defaults: {
  16701. drag_min_distance : 10,
  16702. // set 0 for unlimited, but this can conflict with transform
  16703. drag_max_touches : 1,
  16704. // prevent default browser behavior when dragging occurs
  16705. // be careful with it, it makes the element a blocking element
  16706. // when you are using the drag gesture, it is a good practice to set this true
  16707. drag_block_horizontal : false,
  16708. drag_block_vertical : false,
  16709. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16710. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16711. drag_lock_to_axis : false,
  16712. // drag lock only kicks in when distance > drag_lock_min_distance
  16713. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16714. drag_lock_min_distance : 25
  16715. },
  16716. triggered: false,
  16717. handler: function dragGesture(ev, inst) {
  16718. // current gesture isnt drag, but dragged is true
  16719. // this means an other gesture is busy. now call dragend
  16720. if(Hammer.detection.current.name != this.name && this.triggered) {
  16721. inst.trigger(this.name +'end', ev);
  16722. this.triggered = false;
  16723. return;
  16724. }
  16725. // max touches
  16726. if(inst.options.drag_max_touches > 0 &&
  16727. ev.touches.length > inst.options.drag_max_touches) {
  16728. return;
  16729. }
  16730. switch(ev.eventType) {
  16731. case Hammer.EVENT_START:
  16732. this.triggered = false;
  16733. break;
  16734. case Hammer.EVENT_MOVE:
  16735. // when the distance we moved is too small we skip this gesture
  16736. // or we can be already in dragging
  16737. if(ev.distance < inst.options.drag_min_distance &&
  16738. Hammer.detection.current.name != this.name) {
  16739. return;
  16740. }
  16741. // we are dragging!
  16742. Hammer.detection.current.name = this.name;
  16743. // lock drag to axis?
  16744. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16745. ev.drag_locked_to_axis = true;
  16746. }
  16747. var last_direction = Hammer.detection.current.lastEvent.direction;
  16748. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16749. // keep direction on the axis that the drag gesture started on
  16750. if(Hammer.utils.isVertical(last_direction)) {
  16751. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16752. }
  16753. else {
  16754. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16755. }
  16756. }
  16757. // first time, trigger dragstart event
  16758. if(!this.triggered) {
  16759. inst.trigger(this.name +'start', ev);
  16760. this.triggered = true;
  16761. }
  16762. // trigger normal event
  16763. inst.trigger(this.name, ev);
  16764. // direction event, like dragdown
  16765. inst.trigger(this.name + ev.direction, ev);
  16766. // block the browser events
  16767. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16768. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16769. ev.preventDefault();
  16770. }
  16771. break;
  16772. case Hammer.EVENT_END:
  16773. // trigger dragend
  16774. if(this.triggered) {
  16775. inst.trigger(this.name +'end', ev);
  16776. }
  16777. this.triggered = false;
  16778. break;
  16779. }
  16780. }
  16781. };
  16782. /**
  16783. * Transform
  16784. * User want to scale or rotate with 2 fingers
  16785. * @events transform, pinch, pinchin, pinchout, rotate
  16786. */
  16787. Hammer.gestures.Transform = {
  16788. name: 'transform',
  16789. index: 45,
  16790. defaults: {
  16791. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16792. transform_min_scale : 0.01,
  16793. // rotation in degrees
  16794. transform_min_rotation : 1,
  16795. // prevent default browser behavior when two touches are on the screen
  16796. // but it makes the element a blocking element
  16797. // when you are using the transform gesture, it is a good practice to set this true
  16798. transform_always_block : false
  16799. },
  16800. triggered: false,
  16801. handler: function transformGesture(ev, inst) {
  16802. // current gesture isnt drag, but dragged is true
  16803. // this means an other gesture is busy. now call dragend
  16804. if(Hammer.detection.current.name != this.name && this.triggered) {
  16805. inst.trigger(this.name +'end', ev);
  16806. this.triggered = false;
  16807. return;
  16808. }
  16809. // atleast multitouch
  16810. if(ev.touches.length < 2) {
  16811. return;
  16812. }
  16813. // prevent default when two fingers are on the screen
  16814. if(inst.options.transform_always_block) {
  16815. ev.preventDefault();
  16816. }
  16817. switch(ev.eventType) {
  16818. case Hammer.EVENT_START:
  16819. this.triggered = false;
  16820. break;
  16821. case Hammer.EVENT_MOVE:
  16822. var scale_threshold = Math.abs(1-ev.scale);
  16823. var rotation_threshold = Math.abs(ev.rotation);
  16824. // when the distance we moved is too small we skip this gesture
  16825. // or we can be already in dragging
  16826. if(scale_threshold < inst.options.transform_min_scale &&
  16827. rotation_threshold < inst.options.transform_min_rotation) {
  16828. return;
  16829. }
  16830. // we are transforming!
  16831. Hammer.detection.current.name = this.name;
  16832. // first time, trigger dragstart event
  16833. if(!this.triggered) {
  16834. inst.trigger(this.name +'start', ev);
  16835. this.triggered = true;
  16836. }
  16837. inst.trigger(this.name, ev); // basic transform event
  16838. // trigger rotate event
  16839. if(rotation_threshold > inst.options.transform_min_rotation) {
  16840. inst.trigger('rotate', ev);
  16841. }
  16842. // trigger pinch event
  16843. if(scale_threshold > inst.options.transform_min_scale) {
  16844. inst.trigger('pinch', ev);
  16845. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16846. }
  16847. break;
  16848. case Hammer.EVENT_END:
  16849. // trigger dragend
  16850. if(this.triggered) {
  16851. inst.trigger(this.name +'end', ev);
  16852. }
  16853. this.triggered = false;
  16854. break;
  16855. }
  16856. }
  16857. };
  16858. /**
  16859. * Touch
  16860. * Called as first, tells the user has touched the screen
  16861. * @events touch
  16862. */
  16863. Hammer.gestures.Touch = {
  16864. name: 'touch',
  16865. index: -Infinity,
  16866. defaults: {
  16867. // call preventDefault at touchstart, and makes the element blocking by
  16868. // disabling the scrolling of the page, but it improves gestures like
  16869. // transforming and dragging.
  16870. // be careful with using this, it can be very annoying for users to be stuck
  16871. // on the page
  16872. prevent_default: false,
  16873. // disable mouse events, so only touch (or pen!) input triggers events
  16874. prevent_mouseevents: false
  16875. },
  16876. handler: function touchGesture(ev, inst) {
  16877. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16878. ev.stopDetect();
  16879. return;
  16880. }
  16881. if(inst.options.prevent_default) {
  16882. ev.preventDefault();
  16883. }
  16884. if(ev.eventType == Hammer.EVENT_START) {
  16885. inst.trigger(this.name, ev);
  16886. }
  16887. }
  16888. };
  16889. /**
  16890. * Release
  16891. * Called as last, tells the user has released the screen
  16892. * @events release
  16893. */
  16894. Hammer.gestures.Release = {
  16895. name: 'release',
  16896. index: Infinity,
  16897. handler: function releaseGesture(ev, inst) {
  16898. if(ev.eventType == Hammer.EVENT_END) {
  16899. inst.trigger(this.name, ev);
  16900. }
  16901. }
  16902. };
  16903. // node export
  16904. if(typeof module === 'object' && typeof module.exports === 'object'){
  16905. module.exports = Hammer;
  16906. }
  16907. // just window export
  16908. else {
  16909. window.Hammer = Hammer;
  16910. // requireJS module definition
  16911. if(typeof window.define === 'function' && window.define.amd) {
  16912. window.define('hammer', [], function() {
  16913. return Hammer;
  16914. });
  16915. }
  16916. }
  16917. })(this);
  16918. },{}],4:[function(require,module,exports){
  16919. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  16920. //! version : 2.6.0
  16921. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16922. //! license : MIT
  16923. //! momentjs.com
  16924. (function (undefined) {
  16925. /************************************
  16926. Constants
  16927. ************************************/
  16928. var moment,
  16929. VERSION = "2.6.0",
  16930. // the global-scope this is NOT the global object in Node.js
  16931. globalScope = typeof global !== 'undefined' ? global : this,
  16932. oldGlobalMoment,
  16933. round = Math.round,
  16934. i,
  16935. YEAR = 0,
  16936. MONTH = 1,
  16937. DATE = 2,
  16938. HOUR = 3,
  16939. MINUTE = 4,
  16940. SECOND = 5,
  16941. MILLISECOND = 6,
  16942. // internal storage for language config files
  16943. languages = {},
  16944. // moment internal properties
  16945. momentProperties = {
  16946. _isAMomentObject: null,
  16947. _i : null,
  16948. _f : null,
  16949. _l : null,
  16950. _strict : null,
  16951. _isUTC : null,
  16952. _offset : null, // optional. Combine with _isUTC
  16953. _pf : null,
  16954. _lang : null // optional
  16955. },
  16956. // check for nodeJS
  16957. hasModule = (typeof module !== 'undefined' && module.exports),
  16958. // ASP.NET json date format regex
  16959. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16960. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16961. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16962. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16963. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16964. // format tokens
  16965. 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,
  16966. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16967. // parsing token regexes
  16968. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16969. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16970. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16971. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16972. parseTokenDigits = /\d+/, // nonzero number of digits
  16973. 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.
  16974. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16975. parseTokenT = /T/i, // T (ISO separator)
  16976. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16977. parseTokenOrdinal = /\d{1,2}/,
  16978. //strict parsing regexes
  16979. parseTokenOneDigit = /\d/, // 0 - 9
  16980. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16981. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16982. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16983. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16984. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16985. // iso 8601 regex
  16986. // 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)
  16987. 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)?)?$/,
  16988. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16989. isoDates = [
  16990. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16991. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16992. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16993. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16994. ['YYYY-DDD', /\d{4}-\d{3}/]
  16995. ],
  16996. // iso time formats and regexes
  16997. isoTimes = [
  16998. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  16999. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17000. ['HH:mm', /(T| )\d\d:\d\d/],
  17001. ['HH', /(T| )\d\d/]
  17002. ],
  17003. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17004. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17005. // getter and setter names
  17006. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17007. unitMillisecondFactors = {
  17008. 'Milliseconds' : 1,
  17009. 'Seconds' : 1e3,
  17010. 'Minutes' : 6e4,
  17011. 'Hours' : 36e5,
  17012. 'Days' : 864e5,
  17013. 'Months' : 2592e6,
  17014. 'Years' : 31536e6
  17015. },
  17016. unitAliases = {
  17017. ms : 'millisecond',
  17018. s : 'second',
  17019. m : 'minute',
  17020. h : 'hour',
  17021. d : 'day',
  17022. D : 'date',
  17023. w : 'week',
  17024. W : 'isoWeek',
  17025. M : 'month',
  17026. Q : 'quarter',
  17027. y : 'year',
  17028. DDD : 'dayOfYear',
  17029. e : 'weekday',
  17030. E : 'isoWeekday',
  17031. gg: 'weekYear',
  17032. GG: 'isoWeekYear'
  17033. },
  17034. camelFunctions = {
  17035. dayofyear : 'dayOfYear',
  17036. isoweekday : 'isoWeekday',
  17037. isoweek : 'isoWeek',
  17038. weekyear : 'weekYear',
  17039. isoweekyear : 'isoWeekYear'
  17040. },
  17041. // format function strings
  17042. formatFunctions = {},
  17043. // tokens to ordinalize and pad
  17044. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17045. paddedTokens = 'M D H h m s w W'.split(' '),
  17046. formatTokenFunctions = {
  17047. M : function () {
  17048. return this.month() + 1;
  17049. },
  17050. MMM : function (format) {
  17051. return this.lang().monthsShort(this, format);
  17052. },
  17053. MMMM : function (format) {
  17054. return this.lang().months(this, format);
  17055. },
  17056. D : function () {
  17057. return this.date();
  17058. },
  17059. DDD : function () {
  17060. return this.dayOfYear();
  17061. },
  17062. d : function () {
  17063. return this.day();
  17064. },
  17065. dd : function (format) {
  17066. return this.lang().weekdaysMin(this, format);
  17067. },
  17068. ddd : function (format) {
  17069. return this.lang().weekdaysShort(this, format);
  17070. },
  17071. dddd : function (format) {
  17072. return this.lang().weekdays(this, format);
  17073. },
  17074. w : function () {
  17075. return this.week();
  17076. },
  17077. W : function () {
  17078. return this.isoWeek();
  17079. },
  17080. YY : function () {
  17081. return leftZeroFill(this.year() % 100, 2);
  17082. },
  17083. YYYY : function () {
  17084. return leftZeroFill(this.year(), 4);
  17085. },
  17086. YYYYY : function () {
  17087. return leftZeroFill(this.year(), 5);
  17088. },
  17089. YYYYYY : function () {
  17090. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17091. return sign + leftZeroFill(Math.abs(y), 6);
  17092. },
  17093. gg : function () {
  17094. return leftZeroFill(this.weekYear() % 100, 2);
  17095. },
  17096. gggg : function () {
  17097. return leftZeroFill(this.weekYear(), 4);
  17098. },
  17099. ggggg : function () {
  17100. return leftZeroFill(this.weekYear(), 5);
  17101. },
  17102. GG : function () {
  17103. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17104. },
  17105. GGGG : function () {
  17106. return leftZeroFill(this.isoWeekYear(), 4);
  17107. },
  17108. GGGGG : function () {
  17109. return leftZeroFill(this.isoWeekYear(), 5);
  17110. },
  17111. e : function () {
  17112. return this.weekday();
  17113. },
  17114. E : function () {
  17115. return this.isoWeekday();
  17116. },
  17117. a : function () {
  17118. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17119. },
  17120. A : function () {
  17121. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17122. },
  17123. H : function () {
  17124. return this.hours();
  17125. },
  17126. h : function () {
  17127. return this.hours() % 12 || 12;
  17128. },
  17129. m : function () {
  17130. return this.minutes();
  17131. },
  17132. s : function () {
  17133. return this.seconds();
  17134. },
  17135. S : function () {
  17136. return toInt(this.milliseconds() / 100);
  17137. },
  17138. SS : function () {
  17139. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17140. },
  17141. SSS : function () {
  17142. return leftZeroFill(this.milliseconds(), 3);
  17143. },
  17144. SSSS : function () {
  17145. return leftZeroFill(this.milliseconds(), 3);
  17146. },
  17147. Z : function () {
  17148. var a = -this.zone(),
  17149. b = "+";
  17150. if (a < 0) {
  17151. a = -a;
  17152. b = "-";
  17153. }
  17154. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17155. },
  17156. ZZ : function () {
  17157. var a = -this.zone(),
  17158. b = "+";
  17159. if (a < 0) {
  17160. a = -a;
  17161. b = "-";
  17162. }
  17163. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17164. },
  17165. z : function () {
  17166. return this.zoneAbbr();
  17167. },
  17168. zz : function () {
  17169. return this.zoneName();
  17170. },
  17171. X : function () {
  17172. return this.unix();
  17173. },
  17174. Q : function () {
  17175. return this.quarter();
  17176. }
  17177. },
  17178. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17179. function defaultParsingFlags() {
  17180. // We need to deep clone this object, and es5 standard is not very
  17181. // helpful.
  17182. return {
  17183. empty : false,
  17184. unusedTokens : [],
  17185. unusedInput : [],
  17186. overflow : -2,
  17187. charsLeftOver : 0,
  17188. nullInput : false,
  17189. invalidMonth : null,
  17190. invalidFormat : false,
  17191. userInvalidated : false,
  17192. iso: false
  17193. };
  17194. }
  17195. function deprecate(msg, fn) {
  17196. var firstTime = true;
  17197. function printMsg() {
  17198. if (moment.suppressDeprecationWarnings === false &&
  17199. typeof console !== 'undefined' && console.warn) {
  17200. console.warn("Deprecation warning: " + msg);
  17201. }
  17202. }
  17203. return extend(function () {
  17204. if (firstTime) {
  17205. printMsg();
  17206. firstTime = false;
  17207. }
  17208. return fn.apply(this, arguments);
  17209. }, fn);
  17210. }
  17211. function padToken(func, count) {
  17212. return function (a) {
  17213. return leftZeroFill(func.call(this, a), count);
  17214. };
  17215. }
  17216. function ordinalizeToken(func, period) {
  17217. return function (a) {
  17218. return this.lang().ordinal(func.call(this, a), period);
  17219. };
  17220. }
  17221. while (ordinalizeTokens.length) {
  17222. i = ordinalizeTokens.pop();
  17223. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17224. }
  17225. while (paddedTokens.length) {
  17226. i = paddedTokens.pop();
  17227. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17228. }
  17229. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17230. /************************************
  17231. Constructors
  17232. ************************************/
  17233. function Language() {
  17234. }
  17235. // Moment prototype object
  17236. function Moment(config) {
  17237. checkOverflow(config);
  17238. extend(this, config);
  17239. }
  17240. // Duration Constructor
  17241. function Duration(duration) {
  17242. var normalizedInput = normalizeObjectUnits(duration),
  17243. years = normalizedInput.year || 0,
  17244. quarters = normalizedInput.quarter || 0,
  17245. months = normalizedInput.month || 0,
  17246. weeks = normalizedInput.week || 0,
  17247. days = normalizedInput.day || 0,
  17248. hours = normalizedInput.hour || 0,
  17249. minutes = normalizedInput.minute || 0,
  17250. seconds = normalizedInput.second || 0,
  17251. milliseconds = normalizedInput.millisecond || 0;
  17252. // representation for dateAddRemove
  17253. this._milliseconds = +milliseconds +
  17254. seconds * 1e3 + // 1000
  17255. minutes * 6e4 + // 1000 * 60
  17256. hours * 36e5; // 1000 * 60 * 60
  17257. // Because of dateAddRemove treats 24 hours as different from a
  17258. // day when working around DST, we need to store them separately
  17259. this._days = +days +
  17260. weeks * 7;
  17261. // It is impossible translate months into days without knowing
  17262. // which months you are are talking about, so we have to store
  17263. // it separately.
  17264. this._months = +months +
  17265. quarters * 3 +
  17266. years * 12;
  17267. this._data = {};
  17268. this._bubble();
  17269. }
  17270. /************************************
  17271. Helpers
  17272. ************************************/
  17273. function extend(a, b) {
  17274. for (var i in b) {
  17275. if (b.hasOwnProperty(i)) {
  17276. a[i] = b[i];
  17277. }
  17278. }
  17279. if (b.hasOwnProperty("toString")) {
  17280. a.toString = b.toString;
  17281. }
  17282. if (b.hasOwnProperty("valueOf")) {
  17283. a.valueOf = b.valueOf;
  17284. }
  17285. return a;
  17286. }
  17287. function cloneMoment(m) {
  17288. var result = {}, i;
  17289. for (i in m) {
  17290. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17291. result[i] = m[i];
  17292. }
  17293. }
  17294. return result;
  17295. }
  17296. function absRound(number) {
  17297. if (number < 0) {
  17298. return Math.ceil(number);
  17299. } else {
  17300. return Math.floor(number);
  17301. }
  17302. }
  17303. // left zero fill a number
  17304. // see http://jsperf.com/left-zero-filling for performance comparison
  17305. function leftZeroFill(number, targetLength, forceSign) {
  17306. var output = '' + Math.abs(number),
  17307. sign = number >= 0;
  17308. while (output.length < targetLength) {
  17309. output = '0' + output;
  17310. }
  17311. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17312. }
  17313. // helper function for _.addTime and _.subtractTime
  17314. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17315. var milliseconds = duration._milliseconds,
  17316. days = duration._days,
  17317. months = duration._months;
  17318. updateOffset = updateOffset == null ? true : updateOffset;
  17319. if (milliseconds) {
  17320. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17321. }
  17322. if (days) {
  17323. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17324. }
  17325. if (months) {
  17326. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17327. }
  17328. if (updateOffset) {
  17329. moment.updateOffset(mom, days || months);
  17330. }
  17331. }
  17332. // check if is an array
  17333. function isArray(input) {
  17334. return Object.prototype.toString.call(input) === '[object Array]';
  17335. }
  17336. function isDate(input) {
  17337. return Object.prototype.toString.call(input) === '[object Date]' ||
  17338. input instanceof Date;
  17339. }
  17340. // compare two arrays, return the number of differences
  17341. function compareArrays(array1, array2, dontConvert) {
  17342. var len = Math.min(array1.length, array2.length),
  17343. lengthDiff = Math.abs(array1.length - array2.length),
  17344. diffs = 0,
  17345. i;
  17346. for (i = 0; i < len; i++) {
  17347. if ((dontConvert && array1[i] !== array2[i]) ||
  17348. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17349. diffs++;
  17350. }
  17351. }
  17352. return diffs + lengthDiff;
  17353. }
  17354. function normalizeUnits(units) {
  17355. if (units) {
  17356. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17357. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17358. }
  17359. return units;
  17360. }
  17361. function normalizeObjectUnits(inputObject) {
  17362. var normalizedInput = {},
  17363. normalizedProp,
  17364. prop;
  17365. for (prop in inputObject) {
  17366. if (inputObject.hasOwnProperty(prop)) {
  17367. normalizedProp = normalizeUnits(prop);
  17368. if (normalizedProp) {
  17369. normalizedInput[normalizedProp] = inputObject[prop];
  17370. }
  17371. }
  17372. }
  17373. return normalizedInput;
  17374. }
  17375. function makeList(field) {
  17376. var count, setter;
  17377. if (field.indexOf('week') === 0) {
  17378. count = 7;
  17379. setter = 'day';
  17380. }
  17381. else if (field.indexOf('month') === 0) {
  17382. count = 12;
  17383. setter = 'month';
  17384. }
  17385. else {
  17386. return;
  17387. }
  17388. moment[field] = function (format, index) {
  17389. var i, getter,
  17390. method = moment.fn._lang[field],
  17391. results = [];
  17392. if (typeof format === 'number') {
  17393. index = format;
  17394. format = undefined;
  17395. }
  17396. getter = function (i) {
  17397. var m = moment().utc().set(setter, i);
  17398. return method.call(moment.fn._lang, m, format || '');
  17399. };
  17400. if (index != null) {
  17401. return getter(index);
  17402. }
  17403. else {
  17404. for (i = 0; i < count; i++) {
  17405. results.push(getter(i));
  17406. }
  17407. return results;
  17408. }
  17409. };
  17410. }
  17411. function toInt(argumentForCoercion) {
  17412. var coercedNumber = +argumentForCoercion,
  17413. value = 0;
  17414. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17415. if (coercedNumber >= 0) {
  17416. value = Math.floor(coercedNumber);
  17417. } else {
  17418. value = Math.ceil(coercedNumber);
  17419. }
  17420. }
  17421. return value;
  17422. }
  17423. function daysInMonth(year, month) {
  17424. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17425. }
  17426. function weeksInYear(year, dow, doy) {
  17427. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17428. }
  17429. function daysInYear(year) {
  17430. return isLeapYear(year) ? 366 : 365;
  17431. }
  17432. function isLeapYear(year) {
  17433. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17434. }
  17435. function checkOverflow(m) {
  17436. var overflow;
  17437. if (m._a && m._pf.overflow === -2) {
  17438. overflow =
  17439. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17440. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17441. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17442. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17443. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17444. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17445. -1;
  17446. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17447. overflow = DATE;
  17448. }
  17449. m._pf.overflow = overflow;
  17450. }
  17451. }
  17452. function isValid(m) {
  17453. if (m._isValid == null) {
  17454. m._isValid = !isNaN(m._d.getTime()) &&
  17455. m._pf.overflow < 0 &&
  17456. !m._pf.empty &&
  17457. !m._pf.invalidMonth &&
  17458. !m._pf.nullInput &&
  17459. !m._pf.invalidFormat &&
  17460. !m._pf.userInvalidated;
  17461. if (m._strict) {
  17462. m._isValid = m._isValid &&
  17463. m._pf.charsLeftOver === 0 &&
  17464. m._pf.unusedTokens.length === 0;
  17465. }
  17466. }
  17467. return m._isValid;
  17468. }
  17469. function normalizeLanguage(key) {
  17470. return key ? key.toLowerCase().replace('_', '-') : key;
  17471. }
  17472. // Return a moment from input, that is local/utc/zone equivalent to model.
  17473. function makeAs(input, model) {
  17474. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17475. moment(input).local();
  17476. }
  17477. /************************************
  17478. Languages
  17479. ************************************/
  17480. extend(Language.prototype, {
  17481. set : function (config) {
  17482. var prop, i;
  17483. for (i in config) {
  17484. prop = config[i];
  17485. if (typeof prop === 'function') {
  17486. this[i] = prop;
  17487. } else {
  17488. this['_' + i] = prop;
  17489. }
  17490. }
  17491. },
  17492. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17493. months : function (m) {
  17494. return this._months[m.month()];
  17495. },
  17496. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17497. monthsShort : function (m) {
  17498. return this._monthsShort[m.month()];
  17499. },
  17500. monthsParse : function (monthName) {
  17501. var i, mom, regex;
  17502. if (!this._monthsParse) {
  17503. this._monthsParse = [];
  17504. }
  17505. for (i = 0; i < 12; i++) {
  17506. // make the regex if we don't have it already
  17507. if (!this._monthsParse[i]) {
  17508. mom = moment.utc([2000, i]);
  17509. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17510. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17511. }
  17512. // test the regex
  17513. if (this._monthsParse[i].test(monthName)) {
  17514. return i;
  17515. }
  17516. }
  17517. },
  17518. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17519. weekdays : function (m) {
  17520. return this._weekdays[m.day()];
  17521. },
  17522. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17523. weekdaysShort : function (m) {
  17524. return this._weekdaysShort[m.day()];
  17525. },
  17526. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17527. weekdaysMin : function (m) {
  17528. return this._weekdaysMin[m.day()];
  17529. },
  17530. weekdaysParse : function (weekdayName) {
  17531. var i, mom, regex;
  17532. if (!this._weekdaysParse) {
  17533. this._weekdaysParse = [];
  17534. }
  17535. for (i = 0; i < 7; i++) {
  17536. // make the regex if we don't have it already
  17537. if (!this._weekdaysParse[i]) {
  17538. mom = moment([2000, 1]).day(i);
  17539. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17540. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17541. }
  17542. // test the regex
  17543. if (this._weekdaysParse[i].test(weekdayName)) {
  17544. return i;
  17545. }
  17546. }
  17547. },
  17548. _longDateFormat : {
  17549. LT : "h:mm A",
  17550. L : "MM/DD/YYYY",
  17551. LL : "MMMM D YYYY",
  17552. LLL : "MMMM D YYYY LT",
  17553. LLLL : "dddd, MMMM D YYYY LT"
  17554. },
  17555. longDateFormat : function (key) {
  17556. var output = this._longDateFormat[key];
  17557. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17558. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17559. return val.slice(1);
  17560. });
  17561. this._longDateFormat[key] = output;
  17562. }
  17563. return output;
  17564. },
  17565. isPM : function (input) {
  17566. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17567. // Using charAt should be more compatible.
  17568. return ((input + '').toLowerCase().charAt(0) === 'p');
  17569. },
  17570. _meridiemParse : /[ap]\.?m?\.?/i,
  17571. meridiem : function (hours, minutes, isLower) {
  17572. if (hours > 11) {
  17573. return isLower ? 'pm' : 'PM';
  17574. } else {
  17575. return isLower ? 'am' : 'AM';
  17576. }
  17577. },
  17578. _calendar : {
  17579. sameDay : '[Today at] LT',
  17580. nextDay : '[Tomorrow at] LT',
  17581. nextWeek : 'dddd [at] LT',
  17582. lastDay : '[Yesterday at] LT',
  17583. lastWeek : '[Last] dddd [at] LT',
  17584. sameElse : 'L'
  17585. },
  17586. calendar : function (key, mom) {
  17587. var output = this._calendar[key];
  17588. return typeof output === 'function' ? output.apply(mom) : output;
  17589. },
  17590. _relativeTime : {
  17591. future : "in %s",
  17592. past : "%s ago",
  17593. s : "a few seconds",
  17594. m : "a minute",
  17595. mm : "%d minutes",
  17596. h : "an hour",
  17597. hh : "%d hours",
  17598. d : "a day",
  17599. dd : "%d days",
  17600. M : "a month",
  17601. MM : "%d months",
  17602. y : "a year",
  17603. yy : "%d years"
  17604. },
  17605. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17606. var output = this._relativeTime[string];
  17607. return (typeof output === 'function') ?
  17608. output(number, withoutSuffix, string, isFuture) :
  17609. output.replace(/%d/i, number);
  17610. },
  17611. pastFuture : function (diff, output) {
  17612. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17613. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17614. },
  17615. ordinal : function (number) {
  17616. return this._ordinal.replace("%d", number);
  17617. },
  17618. _ordinal : "%d",
  17619. preparse : function (string) {
  17620. return string;
  17621. },
  17622. postformat : function (string) {
  17623. return string;
  17624. },
  17625. week : function (mom) {
  17626. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17627. },
  17628. _week : {
  17629. dow : 0, // Sunday is the first day of the week.
  17630. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17631. },
  17632. _invalidDate: 'Invalid date',
  17633. invalidDate: function () {
  17634. return this._invalidDate;
  17635. }
  17636. });
  17637. // Loads a language definition into the `languages` cache. The function
  17638. // takes a key and optionally values. If not in the browser and no values
  17639. // are provided, it will load the language file module. As a convenience,
  17640. // this function also returns the language values.
  17641. function loadLang(key, values) {
  17642. values.abbr = key;
  17643. if (!languages[key]) {
  17644. languages[key] = new Language();
  17645. }
  17646. languages[key].set(values);
  17647. return languages[key];
  17648. }
  17649. // Remove a language from the `languages` cache. Mostly useful in tests.
  17650. function unloadLang(key) {
  17651. delete languages[key];
  17652. }
  17653. // Determines which language definition to use and returns it.
  17654. //
  17655. // With no parameters, it will return the global language. If you
  17656. // pass in a language key, such as 'en', it will return the
  17657. // definition for 'en', so long as 'en' has already been loaded using
  17658. // moment.lang.
  17659. function getLangDefinition(key) {
  17660. var i = 0, j, lang, next, split,
  17661. get = function (k) {
  17662. if (!languages[k] && hasModule) {
  17663. try {
  17664. require('./lang/' + k);
  17665. } catch (e) { }
  17666. }
  17667. return languages[k];
  17668. };
  17669. if (!key) {
  17670. return moment.fn._lang;
  17671. }
  17672. if (!isArray(key)) {
  17673. //short-circuit everything else
  17674. lang = get(key);
  17675. if (lang) {
  17676. return lang;
  17677. }
  17678. key = [key];
  17679. }
  17680. //pick the language from the array
  17681. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17682. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17683. while (i < key.length) {
  17684. split = normalizeLanguage(key[i]).split('-');
  17685. j = split.length;
  17686. next = normalizeLanguage(key[i + 1]);
  17687. next = next ? next.split('-') : null;
  17688. while (j > 0) {
  17689. lang = get(split.slice(0, j).join('-'));
  17690. if (lang) {
  17691. return lang;
  17692. }
  17693. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17694. //the next array item is better than a shallower substring of this one
  17695. break;
  17696. }
  17697. j--;
  17698. }
  17699. i++;
  17700. }
  17701. return moment.fn._lang;
  17702. }
  17703. /************************************
  17704. Formatting
  17705. ************************************/
  17706. function removeFormattingTokens(input) {
  17707. if (input.match(/\[[\s\S]/)) {
  17708. return input.replace(/^\[|\]$/g, "");
  17709. }
  17710. return input.replace(/\\/g, "");
  17711. }
  17712. function makeFormatFunction(format) {
  17713. var array = format.match(formattingTokens), i, length;
  17714. for (i = 0, length = array.length; i < length; i++) {
  17715. if (formatTokenFunctions[array[i]]) {
  17716. array[i] = formatTokenFunctions[array[i]];
  17717. } else {
  17718. array[i] = removeFormattingTokens(array[i]);
  17719. }
  17720. }
  17721. return function (mom) {
  17722. var output = "";
  17723. for (i = 0; i < length; i++) {
  17724. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17725. }
  17726. return output;
  17727. };
  17728. }
  17729. // format date using native date object
  17730. function formatMoment(m, format) {
  17731. if (!m.isValid()) {
  17732. return m.lang().invalidDate();
  17733. }
  17734. format = expandFormat(format, m.lang());
  17735. if (!formatFunctions[format]) {
  17736. formatFunctions[format] = makeFormatFunction(format);
  17737. }
  17738. return formatFunctions[format](m);
  17739. }
  17740. function expandFormat(format, lang) {
  17741. var i = 5;
  17742. function replaceLongDateFormatTokens(input) {
  17743. return lang.longDateFormat(input) || input;
  17744. }
  17745. localFormattingTokens.lastIndex = 0;
  17746. while (i >= 0 && localFormattingTokens.test(format)) {
  17747. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17748. localFormattingTokens.lastIndex = 0;
  17749. i -= 1;
  17750. }
  17751. return format;
  17752. }
  17753. /************************************
  17754. Parsing
  17755. ************************************/
  17756. // get the regex to find the next token
  17757. function getParseRegexForToken(token, config) {
  17758. var a, strict = config._strict;
  17759. switch (token) {
  17760. case 'Q':
  17761. return parseTokenOneDigit;
  17762. case 'DDDD':
  17763. return parseTokenThreeDigits;
  17764. case 'YYYY':
  17765. case 'GGGG':
  17766. case 'gggg':
  17767. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17768. case 'Y':
  17769. case 'G':
  17770. case 'g':
  17771. return parseTokenSignedNumber;
  17772. case 'YYYYYY':
  17773. case 'YYYYY':
  17774. case 'GGGGG':
  17775. case 'ggggg':
  17776. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17777. case 'S':
  17778. if (strict) { return parseTokenOneDigit; }
  17779. /* falls through */
  17780. case 'SS':
  17781. if (strict) { return parseTokenTwoDigits; }
  17782. /* falls through */
  17783. case 'SSS':
  17784. if (strict) { return parseTokenThreeDigits; }
  17785. /* falls through */
  17786. case 'DDD':
  17787. return parseTokenOneToThreeDigits;
  17788. case 'MMM':
  17789. case 'MMMM':
  17790. case 'dd':
  17791. case 'ddd':
  17792. case 'dddd':
  17793. return parseTokenWord;
  17794. case 'a':
  17795. case 'A':
  17796. return getLangDefinition(config._l)._meridiemParse;
  17797. case 'X':
  17798. return parseTokenTimestampMs;
  17799. case 'Z':
  17800. case 'ZZ':
  17801. return parseTokenTimezone;
  17802. case 'T':
  17803. return parseTokenT;
  17804. case 'SSSS':
  17805. return parseTokenDigits;
  17806. case 'MM':
  17807. case 'DD':
  17808. case 'YY':
  17809. case 'GG':
  17810. case 'gg':
  17811. case 'HH':
  17812. case 'hh':
  17813. case 'mm':
  17814. case 'ss':
  17815. case 'ww':
  17816. case 'WW':
  17817. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17818. case 'M':
  17819. case 'D':
  17820. case 'd':
  17821. case 'H':
  17822. case 'h':
  17823. case 'm':
  17824. case 's':
  17825. case 'w':
  17826. case 'W':
  17827. case 'e':
  17828. case 'E':
  17829. return parseTokenOneOrTwoDigits;
  17830. case 'Do':
  17831. return parseTokenOrdinal;
  17832. default :
  17833. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17834. return a;
  17835. }
  17836. }
  17837. function timezoneMinutesFromString(string) {
  17838. string = string || "";
  17839. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17840. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17841. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17842. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17843. return parts[0] === '+' ? -minutes : minutes;
  17844. }
  17845. // function to convert string input to date
  17846. function addTimeToArrayFromToken(token, input, config) {
  17847. var a, datePartArray = config._a;
  17848. switch (token) {
  17849. // QUARTER
  17850. case 'Q':
  17851. if (input != null) {
  17852. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  17853. }
  17854. break;
  17855. // MONTH
  17856. case 'M' : // fall through to MM
  17857. case 'MM' :
  17858. if (input != null) {
  17859. datePartArray[MONTH] = toInt(input) - 1;
  17860. }
  17861. break;
  17862. case 'MMM' : // fall through to MMMM
  17863. case 'MMMM' :
  17864. a = getLangDefinition(config._l).monthsParse(input);
  17865. // if we didn't find a month name, mark the date as invalid.
  17866. if (a != null) {
  17867. datePartArray[MONTH] = a;
  17868. } else {
  17869. config._pf.invalidMonth = input;
  17870. }
  17871. break;
  17872. // DAY OF MONTH
  17873. case 'D' : // fall through to DD
  17874. case 'DD' :
  17875. if (input != null) {
  17876. datePartArray[DATE] = toInt(input);
  17877. }
  17878. break;
  17879. case 'Do' :
  17880. if (input != null) {
  17881. datePartArray[DATE] = toInt(parseInt(input, 10));
  17882. }
  17883. break;
  17884. // DAY OF YEAR
  17885. case 'DDD' : // fall through to DDDD
  17886. case 'DDDD' :
  17887. if (input != null) {
  17888. config._dayOfYear = toInt(input);
  17889. }
  17890. break;
  17891. // YEAR
  17892. case 'YY' :
  17893. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  17894. break;
  17895. case 'YYYY' :
  17896. case 'YYYYY' :
  17897. case 'YYYYYY' :
  17898. datePartArray[YEAR] = toInt(input);
  17899. break;
  17900. // AM / PM
  17901. case 'a' : // fall through to A
  17902. case 'A' :
  17903. config._isPm = getLangDefinition(config._l).isPM(input);
  17904. break;
  17905. // 24 HOUR
  17906. case 'H' : // fall through to hh
  17907. case 'HH' : // fall through to hh
  17908. case 'h' : // fall through to hh
  17909. case 'hh' :
  17910. datePartArray[HOUR] = toInt(input);
  17911. break;
  17912. // MINUTE
  17913. case 'm' : // fall through to mm
  17914. case 'mm' :
  17915. datePartArray[MINUTE] = toInt(input);
  17916. break;
  17917. // SECOND
  17918. case 's' : // fall through to ss
  17919. case 'ss' :
  17920. datePartArray[SECOND] = toInt(input);
  17921. break;
  17922. // MILLISECOND
  17923. case 'S' :
  17924. case 'SS' :
  17925. case 'SSS' :
  17926. case 'SSSS' :
  17927. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17928. break;
  17929. // UNIX TIMESTAMP WITH MS
  17930. case 'X':
  17931. config._d = new Date(parseFloat(input) * 1000);
  17932. break;
  17933. // TIMEZONE
  17934. case 'Z' : // fall through to ZZ
  17935. case 'ZZ' :
  17936. config._useUTC = true;
  17937. config._tzm = timezoneMinutesFromString(input);
  17938. break;
  17939. case 'w':
  17940. case 'ww':
  17941. case 'W':
  17942. case 'WW':
  17943. case 'd':
  17944. case 'dd':
  17945. case 'ddd':
  17946. case 'dddd':
  17947. case 'e':
  17948. case 'E':
  17949. token = token.substr(0, 1);
  17950. /* falls through */
  17951. case 'gg':
  17952. case 'gggg':
  17953. case 'GG':
  17954. case 'GGGG':
  17955. case 'GGGGG':
  17956. token = token.substr(0, 2);
  17957. if (input) {
  17958. config._w = config._w || {};
  17959. config._w[token] = input;
  17960. }
  17961. break;
  17962. }
  17963. }
  17964. // convert an array to a date.
  17965. // the array should mirror the parameters below
  17966. // note: all values past the year are optional and will default to the lowest possible value.
  17967. // [year, month, day , hour, minute, second, millisecond]
  17968. function dateFromConfig(config) {
  17969. var i, date, input = [], currentDate,
  17970. yearToUse, fixYear, w, temp, lang, weekday, week;
  17971. if (config._d) {
  17972. return;
  17973. }
  17974. currentDate = currentDateArray(config);
  17975. //compute day of the year from weeks and weekdays
  17976. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17977. fixYear = function (val) {
  17978. var intVal = parseInt(val, 10);
  17979. return val ?
  17980. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  17981. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17982. };
  17983. w = config._w;
  17984. if (w.GG != null || w.W != null || w.E != null) {
  17985. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17986. }
  17987. else {
  17988. lang = getLangDefinition(config._l);
  17989. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17990. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17991. week = parseInt(w.w, 10) || 1;
  17992. //if we're parsing 'd', then the low day numbers may be next week
  17993. if (w.d != null && weekday < lang._week.dow) {
  17994. week++;
  17995. }
  17996. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17997. }
  17998. config._a[YEAR] = temp.year;
  17999. config._dayOfYear = temp.dayOfYear;
  18000. }
  18001. //if the day of the year is set, figure out what it is
  18002. if (config._dayOfYear) {
  18003. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18004. if (config._dayOfYear > daysInYear(yearToUse)) {
  18005. config._pf._overflowDayOfYear = true;
  18006. }
  18007. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18008. config._a[MONTH] = date.getUTCMonth();
  18009. config._a[DATE] = date.getUTCDate();
  18010. }
  18011. // Default to current date.
  18012. // * if no year, month, day of month are given, default to today
  18013. // * if day of month is given, default month and year
  18014. // * if month is given, default only year
  18015. // * if year is given, don't default anything
  18016. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18017. config._a[i] = input[i] = currentDate[i];
  18018. }
  18019. // Zero out whatever was not defaulted, including time
  18020. for (; i < 7; i++) {
  18021. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18022. }
  18023. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18024. input[HOUR] += toInt((config._tzm || 0) / 60);
  18025. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18026. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18027. }
  18028. function dateFromObject(config) {
  18029. var normalizedInput;
  18030. if (config._d) {
  18031. return;
  18032. }
  18033. normalizedInput = normalizeObjectUnits(config._i);
  18034. config._a = [
  18035. normalizedInput.year,
  18036. normalizedInput.month,
  18037. normalizedInput.day,
  18038. normalizedInput.hour,
  18039. normalizedInput.minute,
  18040. normalizedInput.second,
  18041. normalizedInput.millisecond
  18042. ];
  18043. dateFromConfig(config);
  18044. }
  18045. function currentDateArray(config) {
  18046. var now = new Date();
  18047. if (config._useUTC) {
  18048. return [
  18049. now.getUTCFullYear(),
  18050. now.getUTCMonth(),
  18051. now.getUTCDate()
  18052. ];
  18053. } else {
  18054. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18055. }
  18056. }
  18057. // date from string and format string
  18058. function makeDateFromStringAndFormat(config) {
  18059. config._a = [];
  18060. config._pf.empty = true;
  18061. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18062. var lang = getLangDefinition(config._l),
  18063. string = '' + config._i,
  18064. i, parsedInput, tokens, token, skipped,
  18065. stringLength = string.length,
  18066. totalParsedInputLength = 0;
  18067. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18068. for (i = 0; i < tokens.length; i++) {
  18069. token = tokens[i];
  18070. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18071. if (parsedInput) {
  18072. skipped = string.substr(0, string.indexOf(parsedInput));
  18073. if (skipped.length > 0) {
  18074. config._pf.unusedInput.push(skipped);
  18075. }
  18076. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18077. totalParsedInputLength += parsedInput.length;
  18078. }
  18079. // don't parse if it's not a known token
  18080. if (formatTokenFunctions[token]) {
  18081. if (parsedInput) {
  18082. config._pf.empty = false;
  18083. }
  18084. else {
  18085. config._pf.unusedTokens.push(token);
  18086. }
  18087. addTimeToArrayFromToken(token, parsedInput, config);
  18088. }
  18089. else if (config._strict && !parsedInput) {
  18090. config._pf.unusedTokens.push(token);
  18091. }
  18092. }
  18093. // add remaining unparsed input length to the string
  18094. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18095. if (string.length > 0) {
  18096. config._pf.unusedInput.push(string);
  18097. }
  18098. // handle am pm
  18099. if (config._isPm && config._a[HOUR] < 12) {
  18100. config._a[HOUR] += 12;
  18101. }
  18102. // if is 12 am, change hours to 0
  18103. if (config._isPm === false && config._a[HOUR] === 12) {
  18104. config._a[HOUR] = 0;
  18105. }
  18106. dateFromConfig(config);
  18107. checkOverflow(config);
  18108. }
  18109. function unescapeFormat(s) {
  18110. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18111. return p1 || p2 || p3 || p4;
  18112. });
  18113. }
  18114. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18115. function regexpEscape(s) {
  18116. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18117. }
  18118. // date from string and array of format strings
  18119. function makeDateFromStringAndArray(config) {
  18120. var tempConfig,
  18121. bestMoment,
  18122. scoreToBeat,
  18123. i,
  18124. currentScore;
  18125. if (config._f.length === 0) {
  18126. config._pf.invalidFormat = true;
  18127. config._d = new Date(NaN);
  18128. return;
  18129. }
  18130. for (i = 0; i < config._f.length; i++) {
  18131. currentScore = 0;
  18132. tempConfig = extend({}, config);
  18133. tempConfig._pf = defaultParsingFlags();
  18134. tempConfig._f = config._f[i];
  18135. makeDateFromStringAndFormat(tempConfig);
  18136. if (!isValid(tempConfig)) {
  18137. continue;
  18138. }
  18139. // if there is any input that was not parsed add a penalty for that format
  18140. currentScore += tempConfig._pf.charsLeftOver;
  18141. //or tokens
  18142. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18143. tempConfig._pf.score = currentScore;
  18144. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18145. scoreToBeat = currentScore;
  18146. bestMoment = tempConfig;
  18147. }
  18148. }
  18149. extend(config, bestMoment || tempConfig);
  18150. }
  18151. // date from iso format
  18152. function makeDateFromString(config) {
  18153. var i, l,
  18154. string = config._i,
  18155. match = isoRegex.exec(string);
  18156. if (match) {
  18157. config._pf.iso = true;
  18158. for (i = 0, l = isoDates.length; i < l; i++) {
  18159. if (isoDates[i][1].exec(string)) {
  18160. // match[5] should be "T" or undefined
  18161. config._f = isoDates[i][0] + (match[6] || " ");
  18162. break;
  18163. }
  18164. }
  18165. for (i = 0, l = isoTimes.length; i < l; i++) {
  18166. if (isoTimes[i][1].exec(string)) {
  18167. config._f += isoTimes[i][0];
  18168. break;
  18169. }
  18170. }
  18171. if (string.match(parseTokenTimezone)) {
  18172. config._f += "Z";
  18173. }
  18174. makeDateFromStringAndFormat(config);
  18175. }
  18176. else {
  18177. moment.createFromInputFallback(config);
  18178. }
  18179. }
  18180. function makeDateFromInput(config) {
  18181. var input = config._i,
  18182. matched = aspNetJsonRegex.exec(input);
  18183. if (input === undefined) {
  18184. config._d = new Date();
  18185. } else if (matched) {
  18186. config._d = new Date(+matched[1]);
  18187. } else if (typeof input === 'string') {
  18188. makeDateFromString(config);
  18189. } else if (isArray(input)) {
  18190. config._a = input.slice(0);
  18191. dateFromConfig(config);
  18192. } else if (isDate(input)) {
  18193. config._d = new Date(+input);
  18194. } else if (typeof(input) === 'object') {
  18195. dateFromObject(config);
  18196. } else if (typeof(input) === 'number') {
  18197. // from milliseconds
  18198. config._d = new Date(input);
  18199. } else {
  18200. moment.createFromInputFallback(config);
  18201. }
  18202. }
  18203. function makeDate(y, m, d, h, M, s, ms) {
  18204. //can't just apply() to create a date:
  18205. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18206. var date = new Date(y, m, d, h, M, s, ms);
  18207. //the date constructor doesn't accept years < 1970
  18208. if (y < 1970) {
  18209. date.setFullYear(y);
  18210. }
  18211. return date;
  18212. }
  18213. function makeUTCDate(y) {
  18214. var date = new Date(Date.UTC.apply(null, arguments));
  18215. if (y < 1970) {
  18216. date.setUTCFullYear(y);
  18217. }
  18218. return date;
  18219. }
  18220. function parseWeekday(input, language) {
  18221. if (typeof input === 'string') {
  18222. if (!isNaN(input)) {
  18223. input = parseInt(input, 10);
  18224. }
  18225. else {
  18226. input = language.weekdaysParse(input);
  18227. if (typeof input !== 'number') {
  18228. return null;
  18229. }
  18230. }
  18231. }
  18232. return input;
  18233. }
  18234. /************************************
  18235. Relative Time
  18236. ************************************/
  18237. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18238. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18239. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18240. }
  18241. function relativeTime(milliseconds, withoutSuffix, lang) {
  18242. var seconds = round(Math.abs(milliseconds) / 1000),
  18243. minutes = round(seconds / 60),
  18244. hours = round(minutes / 60),
  18245. days = round(hours / 24),
  18246. years = round(days / 365),
  18247. args = seconds < 45 && ['s', seconds] ||
  18248. minutes === 1 && ['m'] ||
  18249. minutes < 45 && ['mm', minutes] ||
  18250. hours === 1 && ['h'] ||
  18251. hours < 22 && ['hh', hours] ||
  18252. days === 1 && ['d'] ||
  18253. days <= 25 && ['dd', days] ||
  18254. days <= 45 && ['M'] ||
  18255. days < 345 && ['MM', round(days / 30)] ||
  18256. years === 1 && ['y'] || ['yy', years];
  18257. args[2] = withoutSuffix;
  18258. args[3] = milliseconds > 0;
  18259. args[4] = lang;
  18260. return substituteTimeAgo.apply({}, args);
  18261. }
  18262. /************************************
  18263. Week of Year
  18264. ************************************/
  18265. // firstDayOfWeek 0 = sun, 6 = sat
  18266. // the day of the week that starts the week
  18267. // (usually sunday or monday)
  18268. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18269. // the first week is the week that contains the first
  18270. // of this day of the week
  18271. // (eg. ISO weeks use thursday (4))
  18272. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18273. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18274. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18275. adjustedMoment;
  18276. if (daysToDayOfWeek > end) {
  18277. daysToDayOfWeek -= 7;
  18278. }
  18279. if (daysToDayOfWeek < end - 7) {
  18280. daysToDayOfWeek += 7;
  18281. }
  18282. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18283. return {
  18284. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18285. year: adjustedMoment.year()
  18286. };
  18287. }
  18288. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18289. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18290. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18291. weekday = weekday != null ? weekday : firstDayOfWeek;
  18292. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18293. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18294. return {
  18295. year: dayOfYear > 0 ? year : year - 1,
  18296. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18297. };
  18298. }
  18299. /************************************
  18300. Top Level Functions
  18301. ************************************/
  18302. function makeMoment(config) {
  18303. var input = config._i,
  18304. format = config._f;
  18305. if (input === null || (format === undefined && input === '')) {
  18306. return moment.invalid({nullInput: true});
  18307. }
  18308. if (typeof input === 'string') {
  18309. config._i = input = getLangDefinition().preparse(input);
  18310. }
  18311. if (moment.isMoment(input)) {
  18312. config = cloneMoment(input);
  18313. config._d = new Date(+input._d);
  18314. } else if (format) {
  18315. if (isArray(format)) {
  18316. makeDateFromStringAndArray(config);
  18317. } else {
  18318. makeDateFromStringAndFormat(config);
  18319. }
  18320. } else {
  18321. makeDateFromInput(config);
  18322. }
  18323. return new Moment(config);
  18324. }
  18325. moment = function (input, format, lang, strict) {
  18326. var c;
  18327. if (typeof(lang) === "boolean") {
  18328. strict = lang;
  18329. lang = undefined;
  18330. }
  18331. // object construction must be done this way.
  18332. // https://github.com/moment/moment/issues/1423
  18333. c = {};
  18334. c._isAMomentObject = true;
  18335. c._i = input;
  18336. c._f = format;
  18337. c._l = lang;
  18338. c._strict = strict;
  18339. c._isUTC = false;
  18340. c._pf = defaultParsingFlags();
  18341. return makeMoment(c);
  18342. };
  18343. moment.suppressDeprecationWarnings = false;
  18344. moment.createFromInputFallback = deprecate(
  18345. "moment construction falls back to js Date. This is " +
  18346. "discouraged and will be removed in upcoming major " +
  18347. "release. Please refer to " +
  18348. "https://github.com/moment/moment/issues/1407 for more info.",
  18349. function (config) {
  18350. config._d = new Date(config._i);
  18351. });
  18352. // creating with utc
  18353. moment.utc = function (input, format, lang, strict) {
  18354. var c;
  18355. if (typeof(lang) === "boolean") {
  18356. strict = lang;
  18357. lang = undefined;
  18358. }
  18359. // object construction must be done this way.
  18360. // https://github.com/moment/moment/issues/1423
  18361. c = {};
  18362. c._isAMomentObject = true;
  18363. c._useUTC = true;
  18364. c._isUTC = true;
  18365. c._l = lang;
  18366. c._i = input;
  18367. c._f = format;
  18368. c._strict = strict;
  18369. c._pf = defaultParsingFlags();
  18370. return makeMoment(c).utc();
  18371. };
  18372. // creating with unix timestamp (in seconds)
  18373. moment.unix = function (input) {
  18374. return moment(input * 1000);
  18375. };
  18376. // duration
  18377. moment.duration = function (input, key) {
  18378. var duration = input,
  18379. // matching against regexp is expensive, do it on demand
  18380. match = null,
  18381. sign,
  18382. ret,
  18383. parseIso;
  18384. if (moment.isDuration(input)) {
  18385. duration = {
  18386. ms: input._milliseconds,
  18387. d: input._days,
  18388. M: input._months
  18389. };
  18390. } else if (typeof input === 'number') {
  18391. duration = {};
  18392. if (key) {
  18393. duration[key] = input;
  18394. } else {
  18395. duration.milliseconds = input;
  18396. }
  18397. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18398. sign = (match[1] === "-") ? -1 : 1;
  18399. duration = {
  18400. y: 0,
  18401. d: toInt(match[DATE]) * sign,
  18402. h: toInt(match[HOUR]) * sign,
  18403. m: toInt(match[MINUTE]) * sign,
  18404. s: toInt(match[SECOND]) * sign,
  18405. ms: toInt(match[MILLISECOND]) * sign
  18406. };
  18407. } else if (!!(match = isoDurationRegex.exec(input))) {
  18408. sign = (match[1] === "-") ? -1 : 1;
  18409. parseIso = function (inp) {
  18410. // We'd normally use ~~inp for this, but unfortunately it also
  18411. // converts floats to ints.
  18412. // inp may be undefined, so careful calling replace on it.
  18413. var res = inp && parseFloat(inp.replace(',', '.'));
  18414. // apply sign while we're at it
  18415. return (isNaN(res) ? 0 : res) * sign;
  18416. };
  18417. duration = {
  18418. y: parseIso(match[2]),
  18419. M: parseIso(match[3]),
  18420. d: parseIso(match[4]),
  18421. h: parseIso(match[5]),
  18422. m: parseIso(match[6]),
  18423. s: parseIso(match[7]),
  18424. w: parseIso(match[8])
  18425. };
  18426. }
  18427. ret = new Duration(duration);
  18428. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18429. ret._lang = input._lang;
  18430. }
  18431. return ret;
  18432. };
  18433. // version number
  18434. moment.version = VERSION;
  18435. // default format
  18436. moment.defaultFormat = isoFormat;
  18437. // Plugins that add properties should also add the key here (null value),
  18438. // so we can properly clone ourselves.
  18439. moment.momentProperties = momentProperties;
  18440. // This function will be called whenever a moment is mutated.
  18441. // It is intended to keep the offset in sync with the timezone.
  18442. moment.updateOffset = function () {};
  18443. // This function will load languages and then set the global language. If
  18444. // no arguments are passed in, it will simply return the current global
  18445. // language key.
  18446. moment.lang = function (key, values) {
  18447. var r;
  18448. if (!key) {
  18449. return moment.fn._lang._abbr;
  18450. }
  18451. if (values) {
  18452. loadLang(normalizeLanguage(key), values);
  18453. } else if (values === null) {
  18454. unloadLang(key);
  18455. key = 'en';
  18456. } else if (!languages[key]) {
  18457. getLangDefinition(key);
  18458. }
  18459. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18460. return r._abbr;
  18461. };
  18462. // returns language data
  18463. moment.langData = function (key) {
  18464. if (key && key._lang && key._lang._abbr) {
  18465. key = key._lang._abbr;
  18466. }
  18467. return getLangDefinition(key);
  18468. };
  18469. // compare moment object
  18470. moment.isMoment = function (obj) {
  18471. return obj instanceof Moment ||
  18472. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18473. };
  18474. // for typechecking Duration objects
  18475. moment.isDuration = function (obj) {
  18476. return obj instanceof Duration;
  18477. };
  18478. for (i = lists.length - 1; i >= 0; --i) {
  18479. makeList(lists[i]);
  18480. }
  18481. moment.normalizeUnits = function (units) {
  18482. return normalizeUnits(units);
  18483. };
  18484. moment.invalid = function (flags) {
  18485. var m = moment.utc(NaN);
  18486. if (flags != null) {
  18487. extend(m._pf, flags);
  18488. }
  18489. else {
  18490. m._pf.userInvalidated = true;
  18491. }
  18492. return m;
  18493. };
  18494. moment.parseZone = function () {
  18495. return moment.apply(null, arguments).parseZone();
  18496. };
  18497. moment.parseTwoDigitYear = function (input) {
  18498. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18499. };
  18500. /************************************
  18501. Moment Prototype
  18502. ************************************/
  18503. extend(moment.fn = Moment.prototype, {
  18504. clone : function () {
  18505. return moment(this);
  18506. },
  18507. valueOf : function () {
  18508. return +this._d + ((this._offset || 0) * 60000);
  18509. },
  18510. unix : function () {
  18511. return Math.floor(+this / 1000);
  18512. },
  18513. toString : function () {
  18514. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18515. },
  18516. toDate : function () {
  18517. return this._offset ? new Date(+this) : this._d;
  18518. },
  18519. toISOString : function () {
  18520. var m = moment(this).utc();
  18521. if (0 < m.year() && m.year() <= 9999) {
  18522. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18523. } else {
  18524. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18525. }
  18526. },
  18527. toArray : function () {
  18528. var m = this;
  18529. return [
  18530. m.year(),
  18531. m.month(),
  18532. m.date(),
  18533. m.hours(),
  18534. m.minutes(),
  18535. m.seconds(),
  18536. m.milliseconds()
  18537. ];
  18538. },
  18539. isValid : function () {
  18540. return isValid(this);
  18541. },
  18542. isDSTShifted : function () {
  18543. if (this._a) {
  18544. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18545. }
  18546. return false;
  18547. },
  18548. parsingFlags : function () {
  18549. return extend({}, this._pf);
  18550. },
  18551. invalidAt: function () {
  18552. return this._pf.overflow;
  18553. },
  18554. utc : function () {
  18555. return this.zone(0);
  18556. },
  18557. local : function () {
  18558. this.zone(0);
  18559. this._isUTC = false;
  18560. return this;
  18561. },
  18562. format : function (inputString) {
  18563. var output = formatMoment(this, inputString || moment.defaultFormat);
  18564. return this.lang().postformat(output);
  18565. },
  18566. add : function (input, val) {
  18567. var dur;
  18568. // switch args to support add('s', 1) and add(1, 's')
  18569. if (typeof input === 'string') {
  18570. dur = moment.duration(+val, input);
  18571. } else {
  18572. dur = moment.duration(input, val);
  18573. }
  18574. addOrSubtractDurationFromMoment(this, dur, 1);
  18575. return this;
  18576. },
  18577. subtract : function (input, val) {
  18578. var dur;
  18579. // switch args to support subtract('s', 1) and subtract(1, 's')
  18580. if (typeof input === 'string') {
  18581. dur = moment.duration(+val, input);
  18582. } else {
  18583. dur = moment.duration(input, val);
  18584. }
  18585. addOrSubtractDurationFromMoment(this, dur, -1);
  18586. return this;
  18587. },
  18588. diff : function (input, units, asFloat) {
  18589. var that = makeAs(input, this),
  18590. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18591. diff, output;
  18592. units = normalizeUnits(units);
  18593. if (units === 'year' || units === 'month') {
  18594. // average number of days in the months in the given dates
  18595. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18596. // difference in months
  18597. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18598. // adjust by taking difference in days, average number of days
  18599. // and dst in the given months.
  18600. output += ((this - moment(this).startOf('month')) -
  18601. (that - moment(that).startOf('month'))) / diff;
  18602. // same as above but with zones, to negate all dst
  18603. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18604. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18605. if (units === 'year') {
  18606. output = output / 12;
  18607. }
  18608. } else {
  18609. diff = (this - that);
  18610. output = units === 'second' ? diff / 1e3 : // 1000
  18611. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18612. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18613. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18614. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18615. diff;
  18616. }
  18617. return asFloat ? output : absRound(output);
  18618. },
  18619. from : function (time, withoutSuffix) {
  18620. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18621. },
  18622. fromNow : function (withoutSuffix) {
  18623. return this.from(moment(), withoutSuffix);
  18624. },
  18625. calendar : function () {
  18626. // We want to compare the start of today, vs this.
  18627. // Getting start-of-today depends on whether we're zone'd or not.
  18628. var sod = makeAs(moment(), this).startOf('day'),
  18629. diff = this.diff(sod, 'days', true),
  18630. format = diff < -6 ? 'sameElse' :
  18631. diff < -1 ? 'lastWeek' :
  18632. diff < 0 ? 'lastDay' :
  18633. diff < 1 ? 'sameDay' :
  18634. diff < 2 ? 'nextDay' :
  18635. diff < 7 ? 'nextWeek' : 'sameElse';
  18636. return this.format(this.lang().calendar(format, this));
  18637. },
  18638. isLeapYear : function () {
  18639. return isLeapYear(this.year());
  18640. },
  18641. isDST : function () {
  18642. return (this.zone() < this.clone().month(0).zone() ||
  18643. this.zone() < this.clone().month(5).zone());
  18644. },
  18645. day : function (input) {
  18646. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18647. if (input != null) {
  18648. input = parseWeekday(input, this.lang());
  18649. return this.add({ d : input - day });
  18650. } else {
  18651. return day;
  18652. }
  18653. },
  18654. month : makeAccessor('Month', true),
  18655. startOf: function (units) {
  18656. units = normalizeUnits(units);
  18657. // the following switch intentionally omits break keywords
  18658. // to utilize falling through the cases.
  18659. switch (units) {
  18660. case 'year':
  18661. this.month(0);
  18662. /* falls through */
  18663. case 'quarter':
  18664. case 'month':
  18665. this.date(1);
  18666. /* falls through */
  18667. case 'week':
  18668. case 'isoWeek':
  18669. case 'day':
  18670. this.hours(0);
  18671. /* falls through */
  18672. case 'hour':
  18673. this.minutes(0);
  18674. /* falls through */
  18675. case 'minute':
  18676. this.seconds(0);
  18677. /* falls through */
  18678. case 'second':
  18679. this.milliseconds(0);
  18680. /* falls through */
  18681. }
  18682. // weeks are a special case
  18683. if (units === 'week') {
  18684. this.weekday(0);
  18685. } else if (units === 'isoWeek') {
  18686. this.isoWeekday(1);
  18687. }
  18688. // quarters are also special
  18689. if (units === 'quarter') {
  18690. this.month(Math.floor(this.month() / 3) * 3);
  18691. }
  18692. return this;
  18693. },
  18694. endOf: function (units) {
  18695. units = normalizeUnits(units);
  18696. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18697. },
  18698. isAfter: function (input, units) {
  18699. units = typeof units !== 'undefined' ? units : 'millisecond';
  18700. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18701. },
  18702. isBefore: function (input, units) {
  18703. units = typeof units !== 'undefined' ? units : 'millisecond';
  18704. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18705. },
  18706. isSame: function (input, units) {
  18707. units = units || 'ms';
  18708. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18709. },
  18710. min: function (other) {
  18711. other = moment.apply(null, arguments);
  18712. return other < this ? this : other;
  18713. },
  18714. max: function (other) {
  18715. other = moment.apply(null, arguments);
  18716. return other > this ? this : other;
  18717. },
  18718. // keepTime = true means only change the timezone, without affecting
  18719. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18720. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18721. // adjust the time as needed, to be valid.
  18722. //
  18723. // Keeping the time actually adds/subtracts (one hour)
  18724. // from the actual represented time. That is why we call updateOffset
  18725. // a second time. In case it wants us to change the offset again
  18726. // _changeInProgress == true case, then we have to adjust, because
  18727. // there is no such time in the given timezone.
  18728. zone : function (input, keepTime) {
  18729. var offset = this._offset || 0;
  18730. if (input != null) {
  18731. if (typeof input === "string") {
  18732. input = timezoneMinutesFromString(input);
  18733. }
  18734. if (Math.abs(input) < 16) {
  18735. input = input * 60;
  18736. }
  18737. this._offset = input;
  18738. this._isUTC = true;
  18739. if (offset !== input) {
  18740. if (!keepTime || this._changeInProgress) {
  18741. addOrSubtractDurationFromMoment(this,
  18742. moment.duration(offset - input, 'm'), 1, false);
  18743. } else if (!this._changeInProgress) {
  18744. this._changeInProgress = true;
  18745. moment.updateOffset(this, true);
  18746. this._changeInProgress = null;
  18747. }
  18748. }
  18749. } else {
  18750. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18751. }
  18752. return this;
  18753. },
  18754. zoneAbbr : function () {
  18755. return this._isUTC ? "UTC" : "";
  18756. },
  18757. zoneName : function () {
  18758. return this._isUTC ? "Coordinated Universal Time" : "";
  18759. },
  18760. parseZone : function () {
  18761. if (this._tzm) {
  18762. this.zone(this._tzm);
  18763. } else if (typeof this._i === 'string') {
  18764. this.zone(this._i);
  18765. }
  18766. return this;
  18767. },
  18768. hasAlignedHourOffset : function (input) {
  18769. if (!input) {
  18770. input = 0;
  18771. }
  18772. else {
  18773. input = moment(input).zone();
  18774. }
  18775. return (this.zone() - input) % 60 === 0;
  18776. },
  18777. daysInMonth : function () {
  18778. return daysInMonth(this.year(), this.month());
  18779. },
  18780. dayOfYear : function (input) {
  18781. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18782. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18783. },
  18784. quarter : function (input) {
  18785. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  18786. },
  18787. weekYear : function (input) {
  18788. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18789. return input == null ? year : this.add("y", (input - year));
  18790. },
  18791. isoWeekYear : function (input) {
  18792. var year = weekOfYear(this, 1, 4).year;
  18793. return input == null ? year : this.add("y", (input - year));
  18794. },
  18795. week : function (input) {
  18796. var week = this.lang().week(this);
  18797. return input == null ? week : this.add("d", (input - week) * 7);
  18798. },
  18799. isoWeek : function (input) {
  18800. var week = weekOfYear(this, 1, 4).week;
  18801. return input == null ? week : this.add("d", (input - week) * 7);
  18802. },
  18803. weekday : function (input) {
  18804. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18805. return input == null ? weekday : this.add("d", input - weekday);
  18806. },
  18807. isoWeekday : function (input) {
  18808. // behaves the same as moment#day except
  18809. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18810. // as a setter, sunday should belong to the previous week.
  18811. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18812. },
  18813. isoWeeksInYear : function () {
  18814. return weeksInYear(this.year(), 1, 4);
  18815. },
  18816. weeksInYear : function () {
  18817. var weekInfo = this._lang._week;
  18818. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  18819. },
  18820. get : function (units) {
  18821. units = normalizeUnits(units);
  18822. return this[units]();
  18823. },
  18824. set : function (units, value) {
  18825. units = normalizeUnits(units);
  18826. if (typeof this[units] === 'function') {
  18827. this[units](value);
  18828. }
  18829. return this;
  18830. },
  18831. // If passed a language key, it will set the language for this
  18832. // instance. Otherwise, it will return the language configuration
  18833. // variables for this instance.
  18834. lang : function (key) {
  18835. if (key === undefined) {
  18836. return this._lang;
  18837. } else {
  18838. this._lang = getLangDefinition(key);
  18839. return this;
  18840. }
  18841. }
  18842. });
  18843. function rawMonthSetter(mom, value) {
  18844. var dayOfMonth;
  18845. // TODO: Move this out of here!
  18846. if (typeof value === 'string') {
  18847. value = mom.lang().monthsParse(value);
  18848. // TODO: Another silent failure?
  18849. if (typeof value !== 'number') {
  18850. return mom;
  18851. }
  18852. }
  18853. dayOfMonth = Math.min(mom.date(),
  18854. daysInMonth(mom.year(), value));
  18855. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  18856. return mom;
  18857. }
  18858. function rawGetter(mom, unit) {
  18859. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  18860. }
  18861. function rawSetter(mom, unit, value) {
  18862. if (unit === 'Month') {
  18863. return rawMonthSetter(mom, value);
  18864. } else {
  18865. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  18866. }
  18867. }
  18868. function makeAccessor(unit, keepTime) {
  18869. return function (value) {
  18870. if (value != null) {
  18871. rawSetter(this, unit, value);
  18872. moment.updateOffset(this, keepTime);
  18873. return this;
  18874. } else {
  18875. return rawGetter(this, unit);
  18876. }
  18877. };
  18878. }
  18879. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  18880. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  18881. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  18882. // Setting the hour should keep the time, because the user explicitly
  18883. // specified which hour he wants. So trying to maintain the same hour (in
  18884. // a new timezone) makes sense. Adding/subtracting hours does not follow
  18885. // this rule.
  18886. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  18887. // moment.fn.month is defined separately
  18888. moment.fn.date = makeAccessor('Date', true);
  18889. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  18890. moment.fn.year = makeAccessor('FullYear', true);
  18891. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  18892. // add plural methods
  18893. moment.fn.days = moment.fn.day;
  18894. moment.fn.months = moment.fn.month;
  18895. moment.fn.weeks = moment.fn.week;
  18896. moment.fn.isoWeeks = moment.fn.isoWeek;
  18897. moment.fn.quarters = moment.fn.quarter;
  18898. // add aliased format methods
  18899. moment.fn.toJSON = moment.fn.toISOString;
  18900. /************************************
  18901. Duration Prototype
  18902. ************************************/
  18903. extend(moment.duration.fn = Duration.prototype, {
  18904. _bubble : function () {
  18905. var milliseconds = this._milliseconds,
  18906. days = this._days,
  18907. months = this._months,
  18908. data = this._data,
  18909. seconds, minutes, hours, years;
  18910. // The following code bubbles up values, see the tests for
  18911. // examples of what that means.
  18912. data.milliseconds = milliseconds % 1000;
  18913. seconds = absRound(milliseconds / 1000);
  18914. data.seconds = seconds % 60;
  18915. minutes = absRound(seconds / 60);
  18916. data.minutes = minutes % 60;
  18917. hours = absRound(minutes / 60);
  18918. data.hours = hours % 24;
  18919. days += absRound(hours / 24);
  18920. data.days = days % 30;
  18921. months += absRound(days / 30);
  18922. data.months = months % 12;
  18923. years = absRound(months / 12);
  18924. data.years = years;
  18925. },
  18926. weeks : function () {
  18927. return absRound(this.days() / 7);
  18928. },
  18929. valueOf : function () {
  18930. return this._milliseconds +
  18931. this._days * 864e5 +
  18932. (this._months % 12) * 2592e6 +
  18933. toInt(this._months / 12) * 31536e6;
  18934. },
  18935. humanize : function (withSuffix) {
  18936. var difference = +this,
  18937. output = relativeTime(difference, !withSuffix, this.lang());
  18938. if (withSuffix) {
  18939. output = this.lang().pastFuture(difference, output);
  18940. }
  18941. return this.lang().postformat(output);
  18942. },
  18943. add : function (input, val) {
  18944. // supports only 2.0-style add(1, 's') or add(moment)
  18945. var dur = moment.duration(input, val);
  18946. this._milliseconds += dur._milliseconds;
  18947. this._days += dur._days;
  18948. this._months += dur._months;
  18949. this._bubble();
  18950. return this;
  18951. },
  18952. subtract : function (input, val) {
  18953. var dur = moment.duration(input, val);
  18954. this._milliseconds -= dur._milliseconds;
  18955. this._days -= dur._days;
  18956. this._months -= dur._months;
  18957. this._bubble();
  18958. return this;
  18959. },
  18960. get : function (units) {
  18961. units = normalizeUnits(units);
  18962. return this[units.toLowerCase() + 's']();
  18963. },
  18964. as : function (units) {
  18965. units = normalizeUnits(units);
  18966. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18967. },
  18968. lang : moment.fn.lang,
  18969. toIsoString : function () {
  18970. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18971. var years = Math.abs(this.years()),
  18972. months = Math.abs(this.months()),
  18973. days = Math.abs(this.days()),
  18974. hours = Math.abs(this.hours()),
  18975. minutes = Math.abs(this.minutes()),
  18976. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18977. if (!this.asSeconds()) {
  18978. // this is the same as C#'s (Noda) and python (isodate)...
  18979. // but not other JS (goog.date)
  18980. return 'P0D';
  18981. }
  18982. return (this.asSeconds() < 0 ? '-' : '') +
  18983. 'P' +
  18984. (years ? years + 'Y' : '') +
  18985. (months ? months + 'M' : '') +
  18986. (days ? days + 'D' : '') +
  18987. ((hours || minutes || seconds) ? 'T' : '') +
  18988. (hours ? hours + 'H' : '') +
  18989. (minutes ? minutes + 'M' : '') +
  18990. (seconds ? seconds + 'S' : '');
  18991. }
  18992. });
  18993. function makeDurationGetter(name) {
  18994. moment.duration.fn[name] = function () {
  18995. return this._data[name];
  18996. };
  18997. }
  18998. function makeDurationAsGetter(name, factor) {
  18999. moment.duration.fn['as' + name] = function () {
  19000. return +this / factor;
  19001. };
  19002. }
  19003. for (i in unitMillisecondFactors) {
  19004. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19005. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19006. makeDurationGetter(i.toLowerCase());
  19007. }
  19008. }
  19009. makeDurationAsGetter('Weeks', 6048e5);
  19010. moment.duration.fn.asMonths = function () {
  19011. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19012. };
  19013. /************************************
  19014. Default Lang
  19015. ************************************/
  19016. // Set default language, other languages will inherit from English.
  19017. moment.lang('en', {
  19018. ordinal : function (number) {
  19019. var b = number % 10,
  19020. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19021. (b === 1) ? 'st' :
  19022. (b === 2) ? 'nd' :
  19023. (b === 3) ? 'rd' : 'th';
  19024. return number + output;
  19025. }
  19026. });
  19027. /* EMBED_LANGUAGES */
  19028. /************************************
  19029. Exposing Moment
  19030. ************************************/
  19031. function makeGlobal(shouldDeprecate) {
  19032. /*global ender:false */
  19033. if (typeof ender !== 'undefined') {
  19034. return;
  19035. }
  19036. oldGlobalMoment = globalScope.moment;
  19037. if (shouldDeprecate) {
  19038. globalScope.moment = deprecate(
  19039. "Accessing Moment through the global scope is " +
  19040. "deprecated, and will be removed in an upcoming " +
  19041. "release.",
  19042. moment);
  19043. } else {
  19044. globalScope.moment = moment;
  19045. }
  19046. }
  19047. // CommonJS module is defined
  19048. if (hasModule) {
  19049. module.exports = moment;
  19050. } else if (typeof define === "function" && define.amd) {
  19051. define("moment", function (require, exports, module) {
  19052. if (module.config && module.config() && module.config().noGlobal === true) {
  19053. // release the global variable
  19054. globalScope.moment = oldGlobalMoment;
  19055. }
  19056. return moment;
  19057. });
  19058. makeGlobal(true);
  19059. } else {
  19060. makeGlobal();
  19061. }
  19062. }).call(this);
  19063. },{}],5:[function(require,module,exports){
  19064. /**
  19065. * Copyright 2012 Craig Campbell
  19066. *
  19067. * Licensed under the Apache License, Version 2.0 (the "License");
  19068. * you may not use this file except in compliance with the License.
  19069. * You may obtain a copy of the License at
  19070. *
  19071. * http://www.apache.org/licenses/LICENSE-2.0
  19072. *
  19073. * Unless required by applicable law or agreed to in writing, software
  19074. * distributed under the License is distributed on an "AS IS" BASIS,
  19075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19076. * See the License for the specific language governing permissions and
  19077. * limitations under the License.
  19078. *
  19079. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19080. * no external dependencies
  19081. *
  19082. * @version 1.1.2
  19083. * @url craig.is/killing/mice
  19084. */
  19085. /**
  19086. * mapping of special keycodes to their corresponding keys
  19087. *
  19088. * everything in this dictionary cannot use keypress events
  19089. * so it has to be here to map to the correct keycodes for
  19090. * keyup/keydown events
  19091. *
  19092. * @type {Object}
  19093. */
  19094. var _MAP = {
  19095. 8: 'backspace',
  19096. 9: 'tab',
  19097. 13: 'enter',
  19098. 16: 'shift',
  19099. 17: 'ctrl',
  19100. 18: 'alt',
  19101. 20: 'capslock',
  19102. 27: 'esc',
  19103. 32: 'space',
  19104. 33: 'pageup',
  19105. 34: 'pagedown',
  19106. 35: 'end',
  19107. 36: 'home',
  19108. 37: 'left',
  19109. 38: 'up',
  19110. 39: 'right',
  19111. 40: 'down',
  19112. 45: 'ins',
  19113. 46: 'del',
  19114. 91: 'meta',
  19115. 93: 'meta',
  19116. 224: 'meta'
  19117. },
  19118. /**
  19119. * mapping for special characters so they can support
  19120. *
  19121. * this dictionary is only used incase you want to bind a
  19122. * keyup or keydown event to one of these keys
  19123. *
  19124. * @type {Object}
  19125. */
  19126. _KEYCODE_MAP = {
  19127. 106: '*',
  19128. 107: '+',
  19129. 109: '-',
  19130. 110: '.',
  19131. 111 : '/',
  19132. 186: ';',
  19133. 187: '=',
  19134. 188: ',',
  19135. 189: '-',
  19136. 190: '.',
  19137. 191: '/',
  19138. 192: '`',
  19139. 219: '[',
  19140. 220: '\\',
  19141. 221: ']',
  19142. 222: '\''
  19143. },
  19144. /**
  19145. * this is a mapping of keys that require shift on a US keypad
  19146. * back to the non shift equivelents
  19147. *
  19148. * this is so you can use keyup events with these keys
  19149. *
  19150. * note that this will only work reliably on US keyboards
  19151. *
  19152. * @type {Object}
  19153. */
  19154. _SHIFT_MAP = {
  19155. '~': '`',
  19156. '!': '1',
  19157. '@': '2',
  19158. '#': '3',
  19159. '$': '4',
  19160. '%': '5',
  19161. '^': '6',
  19162. '&': '7',
  19163. '*': '8',
  19164. '(': '9',
  19165. ')': '0',
  19166. '_': '-',
  19167. '+': '=',
  19168. ':': ';',
  19169. '\"': '\'',
  19170. '<': ',',
  19171. '>': '.',
  19172. '?': '/',
  19173. '|': '\\'
  19174. },
  19175. /**
  19176. * this is a list of special strings you can use to map
  19177. * to modifier keys when you specify your keyboard shortcuts
  19178. *
  19179. * @type {Object}
  19180. */
  19181. _SPECIAL_ALIASES = {
  19182. 'option': 'alt',
  19183. 'command': 'meta',
  19184. 'return': 'enter',
  19185. 'escape': 'esc'
  19186. },
  19187. /**
  19188. * variable to store the flipped version of _MAP from above
  19189. * needed to check if we should use keypress or not when no action
  19190. * is specified
  19191. *
  19192. * @type {Object|undefined}
  19193. */
  19194. _REVERSE_MAP,
  19195. /**
  19196. * a list of all the callbacks setup via Mousetrap.bind()
  19197. *
  19198. * @type {Object}
  19199. */
  19200. _callbacks = {},
  19201. /**
  19202. * direct map of string combinations to callbacks used for trigger()
  19203. *
  19204. * @type {Object}
  19205. */
  19206. _direct_map = {},
  19207. /**
  19208. * keeps track of what level each sequence is at since multiple
  19209. * sequences can start out with the same sequence
  19210. *
  19211. * @type {Object}
  19212. */
  19213. _sequence_levels = {},
  19214. /**
  19215. * variable to store the setTimeout call
  19216. *
  19217. * @type {null|number}
  19218. */
  19219. _reset_timer,
  19220. /**
  19221. * temporary state where we will ignore the next keyup
  19222. *
  19223. * @type {boolean|string}
  19224. */
  19225. _ignore_next_keyup = false,
  19226. /**
  19227. * are we currently inside of a sequence?
  19228. * type of action ("keyup" or "keydown" or "keypress") or false
  19229. *
  19230. * @type {boolean|string}
  19231. */
  19232. _inside_sequence = false;
  19233. /**
  19234. * loop through the f keys, f1 to f19 and add them to the map
  19235. * programatically
  19236. */
  19237. for (var i = 1; i < 20; ++i) {
  19238. _MAP[111 + i] = 'f' + i;
  19239. }
  19240. /**
  19241. * loop through to map numbers on the numeric keypad
  19242. */
  19243. for (i = 0; i <= 9; ++i) {
  19244. _MAP[i + 96] = i;
  19245. }
  19246. /**
  19247. * cross browser add event method
  19248. *
  19249. * @param {Element|HTMLDocument} object
  19250. * @param {string} type
  19251. * @param {Function} callback
  19252. * @returns void
  19253. */
  19254. function _addEvent(object, type, callback) {
  19255. if (object.addEventListener) {
  19256. return object.addEventListener(type, callback, false);
  19257. }
  19258. object.attachEvent('on' + type, callback);
  19259. }
  19260. /**
  19261. * takes the event and returns the key character
  19262. *
  19263. * @param {Event} e
  19264. * @return {string}
  19265. */
  19266. function _characterFromEvent(e) {
  19267. // for keypress events we should return the character as is
  19268. if (e.type == 'keypress') {
  19269. return String.fromCharCode(e.which);
  19270. }
  19271. // for non keypress events the special maps are needed
  19272. if (_MAP[e.which]) {
  19273. return _MAP[e.which];
  19274. }
  19275. if (_KEYCODE_MAP[e.which]) {
  19276. return _KEYCODE_MAP[e.which];
  19277. }
  19278. // if it is not in the special map
  19279. return String.fromCharCode(e.which).toLowerCase();
  19280. }
  19281. /**
  19282. * should we stop this event before firing off callbacks
  19283. *
  19284. * @param {Event} e
  19285. * @return {boolean}
  19286. */
  19287. function _stop(e) {
  19288. var element = e.target || e.srcElement,
  19289. tag_name = element.tagName;
  19290. // if the element has the class "mousetrap" then no need to stop
  19291. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19292. return false;
  19293. }
  19294. // stop for input, select, and textarea
  19295. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19296. }
  19297. /**
  19298. * checks if two arrays are equal
  19299. *
  19300. * @param {Array} modifiers1
  19301. * @param {Array} modifiers2
  19302. * @returns {boolean}
  19303. */
  19304. function _modifiersMatch(modifiers1, modifiers2) {
  19305. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19306. }
  19307. /**
  19308. * resets all sequence counters except for the ones passed in
  19309. *
  19310. * @param {Object} do_not_reset
  19311. * @returns void
  19312. */
  19313. function _resetSequences(do_not_reset) {
  19314. do_not_reset = do_not_reset || {};
  19315. var active_sequences = false,
  19316. key;
  19317. for (key in _sequence_levels) {
  19318. if (do_not_reset[key]) {
  19319. active_sequences = true;
  19320. continue;
  19321. }
  19322. _sequence_levels[key] = 0;
  19323. }
  19324. if (!active_sequences) {
  19325. _inside_sequence = false;
  19326. }
  19327. }
  19328. /**
  19329. * finds all callbacks that match based on the keycode, modifiers,
  19330. * and action
  19331. *
  19332. * @param {string} character
  19333. * @param {Array} modifiers
  19334. * @param {string} action
  19335. * @param {boolean=} remove - should we remove any matches
  19336. * @param {string=} combination
  19337. * @returns {Array}
  19338. */
  19339. function _getMatches(character, modifiers, action, remove, combination) {
  19340. var i,
  19341. callback,
  19342. matches = [];
  19343. // if there are no events related to this keycode
  19344. if (!_callbacks[character]) {
  19345. return [];
  19346. }
  19347. // if a modifier key is coming up on its own we should allow it
  19348. if (action == 'keyup' && _isModifier(character)) {
  19349. modifiers = [character];
  19350. }
  19351. // loop through all callbacks for the key that was pressed
  19352. // and see if any of them match
  19353. for (i = 0; i < _callbacks[character].length; ++i) {
  19354. callback = _callbacks[character][i];
  19355. // if this is a sequence but it is not at the right level
  19356. // then move onto the next match
  19357. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19358. continue;
  19359. }
  19360. // if the action we are looking for doesn't match the action we got
  19361. // then we should keep going
  19362. if (action != callback.action) {
  19363. continue;
  19364. }
  19365. // if this is a keypress event that means that we need to only
  19366. // look at the character, otherwise check the modifiers as
  19367. // well
  19368. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19369. // remove is used so if you change your mind and call bind a
  19370. // second time with a new function the first one is overwritten
  19371. if (remove && callback.combo == combination) {
  19372. _callbacks[character].splice(i, 1);
  19373. }
  19374. matches.push(callback);
  19375. }
  19376. }
  19377. return matches;
  19378. }
  19379. /**
  19380. * takes a key event and figures out what the modifiers are
  19381. *
  19382. * @param {Event} e
  19383. * @returns {Array}
  19384. */
  19385. function _eventModifiers(e) {
  19386. var modifiers = [];
  19387. if (e.shiftKey) {
  19388. modifiers.push('shift');
  19389. }
  19390. if (e.altKey) {
  19391. modifiers.push('alt');
  19392. }
  19393. if (e.ctrlKey) {
  19394. modifiers.push('ctrl');
  19395. }
  19396. if (e.metaKey) {
  19397. modifiers.push('meta');
  19398. }
  19399. return modifiers;
  19400. }
  19401. /**
  19402. * actually calls the callback function
  19403. *
  19404. * if your callback function returns false this will use the jquery
  19405. * convention - prevent default and stop propogation on the event
  19406. *
  19407. * @param {Function} callback
  19408. * @param {Event} e
  19409. * @returns void
  19410. */
  19411. function _fireCallback(callback, e) {
  19412. if (callback(e) === false) {
  19413. if (e.preventDefault) {
  19414. e.preventDefault();
  19415. }
  19416. if (e.stopPropagation) {
  19417. e.stopPropagation();
  19418. }
  19419. e.returnValue = false;
  19420. e.cancelBubble = true;
  19421. }
  19422. }
  19423. /**
  19424. * handles a character key event
  19425. *
  19426. * @param {string} character
  19427. * @param {Event} e
  19428. * @returns void
  19429. */
  19430. function _handleCharacter(character, e) {
  19431. // if this event should not happen stop here
  19432. if (_stop(e)) {
  19433. return;
  19434. }
  19435. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19436. i,
  19437. do_not_reset = {},
  19438. processed_sequence_callback = false;
  19439. // loop through matching callbacks for this key event
  19440. for (i = 0; i < callbacks.length; ++i) {
  19441. // fire for all sequence callbacks
  19442. // this is because if for example you have multiple sequences
  19443. // bound such as "g i" and "g t" they both need to fire the
  19444. // callback for matching g cause otherwise you can only ever
  19445. // match the first one
  19446. if (callbacks[i].seq) {
  19447. processed_sequence_callback = true;
  19448. // keep a list of which sequences were matches for later
  19449. do_not_reset[callbacks[i].seq] = 1;
  19450. _fireCallback(callbacks[i].callback, e);
  19451. continue;
  19452. }
  19453. // if there were no sequence matches but we are still here
  19454. // that means this is a regular match so we should fire that
  19455. if (!processed_sequence_callback && !_inside_sequence) {
  19456. _fireCallback(callbacks[i].callback, e);
  19457. }
  19458. }
  19459. // if you are inside of a sequence and the key you are pressing
  19460. // is not a modifier key then we should reset all sequences
  19461. // that were not matched by this key event
  19462. if (e.type == _inside_sequence && !_isModifier(character)) {
  19463. _resetSequences(do_not_reset);
  19464. }
  19465. }
  19466. /**
  19467. * handles a keydown event
  19468. *
  19469. * @param {Event} e
  19470. * @returns void
  19471. */
  19472. function _handleKey(e) {
  19473. // normalize e.which for key events
  19474. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19475. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19476. var character = _characterFromEvent(e);
  19477. // no character found then stop
  19478. if (!character) {
  19479. return;
  19480. }
  19481. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19482. _ignore_next_keyup = false;
  19483. return;
  19484. }
  19485. _handleCharacter(character, e);
  19486. }
  19487. /**
  19488. * determines if the keycode specified is a modifier key or not
  19489. *
  19490. * @param {string} key
  19491. * @returns {boolean}
  19492. */
  19493. function _isModifier(key) {
  19494. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19495. }
  19496. /**
  19497. * called to set a 1 second timeout on the specified sequence
  19498. *
  19499. * this is so after each key press in the sequence you have 1 second
  19500. * to press the next key before you have to start over
  19501. *
  19502. * @returns void
  19503. */
  19504. function _resetSequenceTimer() {
  19505. clearTimeout(_reset_timer);
  19506. _reset_timer = setTimeout(_resetSequences, 1000);
  19507. }
  19508. /**
  19509. * reverses the map lookup so that we can look for specific keys
  19510. * to see what can and can't use keypress
  19511. *
  19512. * @return {Object}
  19513. */
  19514. function _getReverseMap() {
  19515. if (!_REVERSE_MAP) {
  19516. _REVERSE_MAP = {};
  19517. for (var key in _MAP) {
  19518. // pull out the numeric keypad from here cause keypress should
  19519. // be able to detect the keys from the character
  19520. if (key > 95 && key < 112) {
  19521. continue;
  19522. }
  19523. if (_MAP.hasOwnProperty(key)) {
  19524. _REVERSE_MAP[_MAP[key]] = key;
  19525. }
  19526. }
  19527. }
  19528. return _REVERSE_MAP;
  19529. }
  19530. /**
  19531. * picks the best action based on the key combination
  19532. *
  19533. * @param {string} key - character for key
  19534. * @param {Array} modifiers
  19535. * @param {string=} action passed in
  19536. */
  19537. function _pickBestAction(key, modifiers, action) {
  19538. // if no action was picked in we should try to pick the one
  19539. // that we think would work best for this key
  19540. if (!action) {
  19541. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19542. }
  19543. // modifier keys don't work as expected with keypress,
  19544. // switch to keydown
  19545. if (action == 'keypress' && modifiers.length) {
  19546. action = 'keydown';
  19547. }
  19548. return action;
  19549. }
  19550. /**
  19551. * binds a key sequence to an event
  19552. *
  19553. * @param {string} combo - combo specified in bind call
  19554. * @param {Array} keys
  19555. * @param {Function} callback
  19556. * @param {string=} action
  19557. * @returns void
  19558. */
  19559. function _bindSequence(combo, keys, callback, action) {
  19560. // start off by adding a sequence level record for this combination
  19561. // and setting the level to 0
  19562. _sequence_levels[combo] = 0;
  19563. // if there is no action pick the best one for the first key
  19564. // in the sequence
  19565. if (!action) {
  19566. action = _pickBestAction(keys[0], []);
  19567. }
  19568. /**
  19569. * callback to increase the sequence level for this sequence and reset
  19570. * all other sequences that were active
  19571. *
  19572. * @param {Event} e
  19573. * @returns void
  19574. */
  19575. var _increaseSequence = function(e) {
  19576. _inside_sequence = action;
  19577. ++_sequence_levels[combo];
  19578. _resetSequenceTimer();
  19579. },
  19580. /**
  19581. * wraps the specified callback inside of another function in order
  19582. * to reset all sequence counters as soon as this sequence is done
  19583. *
  19584. * @param {Event} e
  19585. * @returns void
  19586. */
  19587. _callbackAndReset = function(e) {
  19588. _fireCallback(callback, e);
  19589. // we should ignore the next key up if the action is key down
  19590. // or keypress. this is so if you finish a sequence and
  19591. // release the key the final key will not trigger a keyup
  19592. if (action !== 'keyup') {
  19593. _ignore_next_keyup = _characterFromEvent(e);
  19594. }
  19595. // weird race condition if a sequence ends with the key
  19596. // another sequence begins with
  19597. setTimeout(_resetSequences, 10);
  19598. },
  19599. i;
  19600. // loop through keys one at a time and bind the appropriate callback
  19601. // function. for any key leading up to the final one it should
  19602. // increase the sequence. after the final, it should reset all sequences
  19603. for (i = 0; i < keys.length; ++i) {
  19604. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19605. }
  19606. }
  19607. /**
  19608. * binds a single keyboard combination
  19609. *
  19610. * @param {string} combination
  19611. * @param {Function} callback
  19612. * @param {string=} action
  19613. * @param {string=} sequence_name - name of sequence if part of sequence
  19614. * @param {number=} level - what part of the sequence the command is
  19615. * @returns void
  19616. */
  19617. function _bindSingle(combination, callback, action, sequence_name, level) {
  19618. // make sure multiple spaces in a row become a single space
  19619. combination = combination.replace(/\s+/g, ' ');
  19620. var sequence = combination.split(' '),
  19621. i,
  19622. key,
  19623. keys,
  19624. modifiers = [];
  19625. // if this pattern is a sequence of keys then run through this method
  19626. // to reprocess each pattern one key at a time
  19627. if (sequence.length > 1) {
  19628. return _bindSequence(combination, sequence, callback, action);
  19629. }
  19630. // take the keys from this pattern and figure out what the actual
  19631. // pattern is all about
  19632. keys = combination === '+' ? ['+'] : combination.split('+');
  19633. for (i = 0; i < keys.length; ++i) {
  19634. key = keys[i];
  19635. // normalize key names
  19636. if (_SPECIAL_ALIASES[key]) {
  19637. key = _SPECIAL_ALIASES[key];
  19638. }
  19639. // if this is not a keypress event then we should
  19640. // be smart about using shift keys
  19641. // this will only work for US keyboards however
  19642. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19643. key = _SHIFT_MAP[key];
  19644. modifiers.push('shift');
  19645. }
  19646. // if this key is a modifier then add it to the list of modifiers
  19647. if (_isModifier(key)) {
  19648. modifiers.push(key);
  19649. }
  19650. }
  19651. // depending on what the key combination is
  19652. // we will try to pick the best event for it
  19653. action = _pickBestAction(key, modifiers, action);
  19654. // make sure to initialize array if this is the first time
  19655. // a callback is added for this key
  19656. if (!_callbacks[key]) {
  19657. _callbacks[key] = [];
  19658. }
  19659. // remove an existing match if there is one
  19660. _getMatches(key, modifiers, action, !sequence_name, combination);
  19661. // add this call back to the array
  19662. // if it is a sequence put it at the beginning
  19663. // if not put it at the end
  19664. //
  19665. // this is important because the way these are processed expects
  19666. // the sequence ones to come first
  19667. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19668. callback: callback,
  19669. modifiers: modifiers,
  19670. action: action,
  19671. seq: sequence_name,
  19672. level: level,
  19673. combo: combination
  19674. });
  19675. }
  19676. /**
  19677. * binds multiple combinations to the same callback
  19678. *
  19679. * @param {Array} combinations
  19680. * @param {Function} callback
  19681. * @param {string|undefined} action
  19682. * @returns void
  19683. */
  19684. function _bindMultiple(combinations, callback, action) {
  19685. for (var i = 0; i < combinations.length; ++i) {
  19686. _bindSingle(combinations[i], callback, action);
  19687. }
  19688. }
  19689. // start!
  19690. _addEvent(document, 'keypress', _handleKey);
  19691. _addEvent(document, 'keydown', _handleKey);
  19692. _addEvent(document, 'keyup', _handleKey);
  19693. var mousetrap = {
  19694. /**
  19695. * binds an event to mousetrap
  19696. *
  19697. * can be a single key, a combination of keys separated with +,
  19698. * a comma separated list of keys, an array of keys, or
  19699. * a sequence of keys separated by spaces
  19700. *
  19701. * be sure to list the modifier keys first to make sure that the
  19702. * correct key ends up getting bound (the last key in the pattern)
  19703. *
  19704. * @param {string|Array} keys
  19705. * @param {Function} callback
  19706. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19707. * @returns void
  19708. */
  19709. bind: function(keys, callback, action) {
  19710. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19711. _direct_map[keys + ':' + action] = callback;
  19712. return this;
  19713. },
  19714. /**
  19715. * unbinds an event to mousetrap
  19716. *
  19717. * the unbinding sets the callback function of the specified key combo
  19718. * to an empty function and deletes the corresponding key in the
  19719. * _direct_map dict.
  19720. *
  19721. * the keycombo+action has to be exactly the same as
  19722. * it was defined in the bind method
  19723. *
  19724. * TODO: actually remove this from the _callbacks dictionary instead
  19725. * of binding an empty function
  19726. *
  19727. * @param {string|Array} keys
  19728. * @param {string} action
  19729. * @returns void
  19730. */
  19731. unbind: function(keys, action) {
  19732. if (_direct_map[keys + ':' + action]) {
  19733. delete _direct_map[keys + ':' + action];
  19734. this.bind(keys, function() {}, action);
  19735. }
  19736. return this;
  19737. },
  19738. /**
  19739. * triggers an event that has already been bound
  19740. *
  19741. * @param {string} keys
  19742. * @param {string=} action
  19743. * @returns void
  19744. */
  19745. trigger: function(keys, action) {
  19746. _direct_map[keys + ':' + action]();
  19747. return this;
  19748. },
  19749. /**
  19750. * resets the library back to its initial state. this is useful
  19751. * if you want to clear out the current keyboard shortcuts and bind
  19752. * new ones - for example if you switch to another page
  19753. *
  19754. * @returns void
  19755. */
  19756. reset: function() {
  19757. _callbacks = {};
  19758. _direct_map = {};
  19759. return this;
  19760. }
  19761. };
  19762. module.exports = mousetrap;
  19763. },{}]},{},[1])
  19764. (1)
  19765. });