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.

22814 lines
675 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.3-SNAPSHOT
  8. * @date 2014-05-28
  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. * Deep extend an object a with the properties of object b
  354. * @param {Object} a
  355. * @param {Object} b
  356. * @returns {Object}
  357. */
  358. util.deepExtend = function deepExtend (a, b) {
  359. // TODO: add support for Arrays to deepExtend
  360. if (Array.isArray(b)) {
  361. throw new TypeError('Arrays are not supported by deepExtend');
  362. }
  363. for (var prop in b) {
  364. if (b.hasOwnProperty(prop)) {
  365. if (b[prop] && b[prop].constructor === Object) {
  366. if (a[prop] === undefined) {
  367. a[prop] = {};
  368. }
  369. if (a[prop].constructor === Object) {
  370. deepExtend(a[prop], b[prop]);
  371. }
  372. else {
  373. a[prop] = b[prop];
  374. }
  375. } else if (Array.isArray(b[prop])) {
  376. throw new TypeError('Arrays are not supported by deepExtend');
  377. } else {
  378. a[prop] = b[prop];
  379. }
  380. }
  381. }
  382. return a;
  383. };
  384. /**
  385. * Test whether all elements in two arrays are equal.
  386. * @param {Array} a
  387. * @param {Array} b
  388. * @return {boolean} Returns true if both arrays have the same length and same
  389. * elements.
  390. */
  391. util.equalArray = function (a, b) {
  392. if (a.length != b.length) return false;
  393. for (var i = 0, len = a.length; i < len; i++) {
  394. if (a[i] != b[i]) return false;
  395. }
  396. return true;
  397. };
  398. /**
  399. * Convert an object to another type
  400. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  401. * @param {String | undefined} type Name of the type. Available types:
  402. * 'Boolean', 'Number', 'String',
  403. * 'Date', 'Moment', ISODate', 'ASPDate'.
  404. * @return {*} object
  405. * @throws Error
  406. */
  407. util.convert = function convert(object, type) {
  408. var match;
  409. if (object === undefined) {
  410. return undefined;
  411. }
  412. if (object === null) {
  413. return null;
  414. }
  415. if (!type) {
  416. return object;
  417. }
  418. if (!(typeof type === 'string') && !(type instanceof String)) {
  419. throw new Error('Type must be a string');
  420. }
  421. //noinspection FallthroughInSwitchStatementJS
  422. switch (type) {
  423. case 'boolean':
  424. case 'Boolean':
  425. return Boolean(object);
  426. case 'number':
  427. case 'Number':
  428. return Number(object.valueOf());
  429. case 'string':
  430. case 'String':
  431. return String(object);
  432. case 'Date':
  433. if (util.isNumber(object)) {
  434. return new Date(object);
  435. }
  436. if (object instanceof Date) {
  437. return new Date(object.valueOf());
  438. }
  439. else if (moment.isMoment(object)) {
  440. return new Date(object.valueOf());
  441. }
  442. if (util.isString(object)) {
  443. match = ASPDateRegex.exec(object);
  444. if (match) {
  445. // object is an ASP date
  446. return new Date(Number(match[1])); // parse number
  447. }
  448. else {
  449. return moment(object).toDate(); // parse string
  450. }
  451. }
  452. else {
  453. throw new Error(
  454. 'Cannot convert object of type ' + util.getType(object) +
  455. ' to type Date');
  456. }
  457. case 'Moment':
  458. if (util.isNumber(object)) {
  459. return moment(object);
  460. }
  461. if (object instanceof Date) {
  462. return moment(object.valueOf());
  463. }
  464. else if (moment.isMoment(object)) {
  465. return moment(object);
  466. }
  467. if (util.isString(object)) {
  468. match = ASPDateRegex.exec(object);
  469. if (match) {
  470. // object is an ASP date
  471. return moment(Number(match[1])); // parse number
  472. }
  473. else {
  474. return moment(object); // parse string
  475. }
  476. }
  477. else {
  478. throw new Error(
  479. 'Cannot convert object of type ' + util.getType(object) +
  480. ' to type Date');
  481. }
  482. case 'ISODate':
  483. if (util.isNumber(object)) {
  484. return new Date(object);
  485. }
  486. else if (object instanceof Date) {
  487. return object.toISOString();
  488. }
  489. else if (moment.isMoment(object)) {
  490. return object.toDate().toISOString();
  491. }
  492. else if (util.isString(object)) {
  493. match = ASPDateRegex.exec(object);
  494. if (match) {
  495. // object is an ASP date
  496. return new Date(Number(match[1])).toISOString(); // parse number
  497. }
  498. else {
  499. return new Date(object).toISOString(); // parse string
  500. }
  501. }
  502. else {
  503. throw new Error(
  504. 'Cannot convert object of type ' + util.getType(object) +
  505. ' to type ISODate');
  506. }
  507. case 'ASPDate':
  508. if (util.isNumber(object)) {
  509. return '/Date(' + object + ')/';
  510. }
  511. else if (object instanceof Date) {
  512. return '/Date(' + object.valueOf() + ')/';
  513. }
  514. else if (util.isString(object)) {
  515. match = ASPDateRegex.exec(object);
  516. var value;
  517. if (match) {
  518. // object is an ASP date
  519. value = new Date(Number(match[1])).valueOf(); // parse number
  520. }
  521. else {
  522. value = new Date(object).valueOf(); // parse string
  523. }
  524. return '/Date(' + value + ')/';
  525. }
  526. else {
  527. throw new Error(
  528. 'Cannot convert object of type ' + util.getType(object) +
  529. ' to type ASPDate');
  530. }
  531. default:
  532. throw new Error('Cannot convert object of type ' + util.getType(object) +
  533. ' to type "' + type + '"');
  534. }
  535. };
  536. // parse ASP.Net Date pattern,
  537. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  538. // code from http://momentjs.com/
  539. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  540. /**
  541. * Get the type of an object, for example util.getType([]) returns 'Array'
  542. * @param {*} object
  543. * @return {String} type
  544. */
  545. util.getType = function getType(object) {
  546. var type = typeof object;
  547. if (type == 'object') {
  548. if (object == null) {
  549. return 'null';
  550. }
  551. if (object instanceof Boolean) {
  552. return 'Boolean';
  553. }
  554. if (object instanceof Number) {
  555. return 'Number';
  556. }
  557. if (object instanceof String) {
  558. return 'String';
  559. }
  560. if (object instanceof Array) {
  561. return 'Array';
  562. }
  563. if (object instanceof Date) {
  564. return 'Date';
  565. }
  566. return 'Object';
  567. }
  568. else if (type == 'number') {
  569. return 'Number';
  570. }
  571. else if (type == 'boolean') {
  572. return 'Boolean';
  573. }
  574. else if (type == 'string') {
  575. return 'String';
  576. }
  577. return type;
  578. };
  579. /**
  580. * Retrieve the absolute left value of a DOM element
  581. * @param {Element} elem A dom element, for example a div
  582. * @return {number} left The absolute left position of this element
  583. * in the browser page.
  584. */
  585. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. var left = elem.offsetLeft;
  589. var e = elem.offsetParent;
  590. while (e != null && e != body && e != doc) {
  591. left += e.offsetLeft;
  592. left -= e.scrollLeft;
  593. e = e.offsetParent;
  594. }
  595. return left;
  596. };
  597. /**
  598. * Retrieve the absolute top value of a DOM element
  599. * @param {Element} elem A dom element, for example a div
  600. * @return {number} top The absolute top position of this element
  601. * in the browser page.
  602. */
  603. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  604. var doc = document.documentElement;
  605. var body = document.body;
  606. var top = elem.offsetTop;
  607. var e = elem.offsetParent;
  608. while (e != null && e != body && e != doc) {
  609. top += e.offsetTop;
  610. top -= e.scrollTop;
  611. e = e.offsetParent;
  612. }
  613. return top;
  614. };
  615. /**
  616. * Get the absolute, vertical mouse position from an event.
  617. * @param {Event} event
  618. * @return {Number} pageY
  619. */
  620. util.getPageY = function getPageY (event) {
  621. if ('pageY' in event) {
  622. return event.pageY;
  623. }
  624. else {
  625. var clientY;
  626. if (('targetTouches' in event) && event.targetTouches.length) {
  627. clientY = event.targetTouches[0].clientY;
  628. }
  629. else {
  630. clientY = event.clientY;
  631. }
  632. var doc = document.documentElement;
  633. var body = document.body;
  634. return clientY +
  635. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  636. ( doc && doc.clientTop || body && body.clientTop || 0 );
  637. }
  638. };
  639. /**
  640. * Get the absolute, horizontal mouse position from an event.
  641. * @param {Event} event
  642. * @return {Number} pageX
  643. */
  644. util.getPageX = function getPageX (event) {
  645. if ('pageY' in event) {
  646. return event.pageX;
  647. }
  648. else {
  649. var clientX;
  650. if (('targetTouches' in event) && event.targetTouches.length) {
  651. clientX = event.targetTouches[0].clientX;
  652. }
  653. else {
  654. clientX = event.clientX;
  655. }
  656. var doc = document.documentElement;
  657. var body = document.body;
  658. return clientX +
  659. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  660. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  661. }
  662. };
  663. /**
  664. * add a className to the given elements style
  665. * @param {Element} elem
  666. * @param {String} className
  667. */
  668. util.addClassName = function addClassName(elem, className) {
  669. var classes = elem.className.split(' ');
  670. if (classes.indexOf(className) == -1) {
  671. classes.push(className); // add the class to the array
  672. elem.className = classes.join(' ');
  673. }
  674. };
  675. /**
  676. * add a className to the given elements style
  677. * @param {Element} elem
  678. * @param {String} className
  679. */
  680. util.removeClassName = function removeClassname(elem, className) {
  681. var classes = elem.className.split(' ');
  682. var index = classes.indexOf(className);
  683. if (index != -1) {
  684. classes.splice(index, 1); // remove the class from the array
  685. elem.className = classes.join(' ');
  686. }
  687. };
  688. /**
  689. * For each method for both arrays and objects.
  690. * In case of an array, the built-in Array.forEach() is applied.
  691. * In case of an Object, the method loops over all properties of the object.
  692. * @param {Object | Array} object An Object or Array
  693. * @param {function} callback Callback method, called for each item in
  694. * the object or array with three parameters:
  695. * callback(value, index, object)
  696. */
  697. util.forEach = function forEach (object, callback) {
  698. var i,
  699. len;
  700. if (object instanceof Array) {
  701. // array
  702. for (i = 0, len = object.length; i < len; i++) {
  703. callback(object[i], i, object);
  704. }
  705. }
  706. else {
  707. // object
  708. for (i in object) {
  709. if (object.hasOwnProperty(i)) {
  710. callback(object[i], i, object);
  711. }
  712. }
  713. }
  714. };
  715. /**
  716. * Convert an object into an array: all objects properties are put into the
  717. * array. The resulting array is unordered.
  718. * @param {Object} object
  719. * @param {Array} array
  720. */
  721. util.toArray = function toArray(object) {
  722. var array = [];
  723. for (var prop in object) {
  724. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  725. }
  726. return array;
  727. }
  728. /**
  729. * Update a property in an object
  730. * @param {Object} object
  731. * @param {String} key
  732. * @param {*} value
  733. * @return {Boolean} changed
  734. */
  735. util.updateProperty = function updateProperty (object, key, value) {
  736. if (object[key] !== value) {
  737. object[key] = value;
  738. return true;
  739. }
  740. else {
  741. return false;
  742. }
  743. };
  744. /**
  745. * Add and event listener. Works for all browsers
  746. * @param {Element} element An html element
  747. * @param {string} action The action, for example "click",
  748. * without the prefix "on"
  749. * @param {function} listener The callback function to be executed
  750. * @param {boolean} [useCapture]
  751. */
  752. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  753. if (element.addEventListener) {
  754. if (useCapture === undefined)
  755. useCapture = false;
  756. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  757. action = "DOMMouseScroll"; // For Firefox
  758. }
  759. element.addEventListener(action, listener, useCapture);
  760. } else {
  761. element.attachEvent("on" + action, listener); // IE browsers
  762. }
  763. };
  764. /**
  765. * Remove an event listener from an element
  766. * @param {Element} element An html dom element
  767. * @param {string} action The name of the event, for example "mousedown"
  768. * @param {function} listener The listener function
  769. * @param {boolean} [useCapture]
  770. */
  771. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  772. if (element.removeEventListener) {
  773. // non-IE browsers
  774. if (useCapture === undefined)
  775. useCapture = false;
  776. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  777. action = "DOMMouseScroll"; // For Firefox
  778. }
  779. element.removeEventListener(action, listener, useCapture);
  780. } else {
  781. // IE browsers
  782. element.detachEvent("on" + action, listener);
  783. }
  784. };
  785. /**
  786. * Get HTML element which is the target of the event
  787. * @param {Event} event
  788. * @return {Element} target element
  789. */
  790. util.getTarget = function getTarget(event) {
  791. // code from http://www.quirksmode.org/js/events_properties.html
  792. if (!event) {
  793. event = window.event;
  794. }
  795. var target;
  796. if (event.target) {
  797. target = event.target;
  798. }
  799. else if (event.srcElement) {
  800. target = event.srcElement;
  801. }
  802. if (target.nodeType != undefined && target.nodeType == 3) {
  803. // defeat Safari bug
  804. target = target.parentNode;
  805. }
  806. return target;
  807. };
  808. /**
  809. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  810. * @param {Element} element
  811. * @param {Event} event
  812. */
  813. util.fakeGesture = function fakeGesture (element, event) {
  814. var eventType = null;
  815. // for hammer.js 1.0.5
  816. var gesture = Hammer.event.collectEventData(this, eventType, event);
  817. // for hammer.js 1.0.6
  818. //var touches = Hammer.event.getTouchList(event, eventType);
  819. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  820. // on IE in standards mode, no touches are recognized by hammer.js,
  821. // resulting in NaN values for center.pageX and center.pageY
  822. if (isNaN(gesture.center.pageX)) {
  823. gesture.center.pageX = event.pageX;
  824. }
  825. if (isNaN(gesture.center.pageY)) {
  826. gesture.center.pageY = event.pageY;
  827. }
  828. return gesture;
  829. };
  830. util.option = {};
  831. /**
  832. * Convert a value into a boolean
  833. * @param {Boolean | function | undefined} value
  834. * @param {Boolean} [defaultValue]
  835. * @returns {Boolean} bool
  836. */
  837. util.option.asBoolean = function (value, defaultValue) {
  838. if (typeof value == 'function') {
  839. value = value();
  840. }
  841. if (value != null) {
  842. return (value != false);
  843. }
  844. return defaultValue || null;
  845. };
  846. /**
  847. * Convert a value into a number
  848. * @param {Boolean | function | undefined} value
  849. * @param {Number} [defaultValue]
  850. * @returns {Number} number
  851. */
  852. util.option.asNumber = function (value, defaultValue) {
  853. if (typeof value == 'function') {
  854. value = value();
  855. }
  856. if (value != null) {
  857. return Number(value) || defaultValue || null;
  858. }
  859. return defaultValue || null;
  860. };
  861. /**
  862. * Convert a value into a string
  863. * @param {String | function | undefined} value
  864. * @param {String} [defaultValue]
  865. * @returns {String} str
  866. */
  867. util.option.asString = function (value, defaultValue) {
  868. if (typeof value == 'function') {
  869. value = value();
  870. }
  871. if (value != null) {
  872. return String(value);
  873. }
  874. return defaultValue || null;
  875. };
  876. /**
  877. * Convert a size or location into a string with pixels or a percentage
  878. * @param {String | Number | function | undefined} value
  879. * @param {String} [defaultValue]
  880. * @returns {String} size
  881. */
  882. util.option.asSize = function (value, defaultValue) {
  883. if (typeof value == 'function') {
  884. value = value();
  885. }
  886. if (util.isString(value)) {
  887. return value;
  888. }
  889. else if (util.isNumber(value)) {
  890. return value + 'px';
  891. }
  892. else {
  893. return defaultValue || null;
  894. }
  895. };
  896. /**
  897. * Convert a value into a DOM element
  898. * @param {HTMLElement | function | undefined} value
  899. * @param {HTMLElement} [defaultValue]
  900. * @returns {HTMLElement | null} dom
  901. */
  902. util.option.asElement = function (value, defaultValue) {
  903. if (typeof value == 'function') {
  904. value = value();
  905. }
  906. return value || defaultValue || null;
  907. };
  908. util.GiveDec = function GiveDec(Hex) {
  909. var Value;
  910. if (Hex == "A")
  911. Value = 10;
  912. else if (Hex == "B")
  913. Value = 11;
  914. else if (Hex == "C")
  915. Value = 12;
  916. else if (Hex == "D")
  917. Value = 13;
  918. else if (Hex == "E")
  919. Value = 14;
  920. else if (Hex == "F")
  921. Value = 15;
  922. else
  923. Value = eval(Hex);
  924. return Value;
  925. };
  926. util.GiveHex = function GiveHex(Dec) {
  927. var Value;
  928. if(Dec == 10)
  929. Value = "A";
  930. else if (Dec == 11)
  931. Value = "B";
  932. else if (Dec == 12)
  933. Value = "C";
  934. else if (Dec == 13)
  935. Value = "D";
  936. else if (Dec == 14)
  937. Value = "E";
  938. else if (Dec == 15)
  939. Value = "F";
  940. else
  941. Value = "" + Dec;
  942. return Value;
  943. };
  944. /**
  945. * Parse a color property into an object with border, background, and
  946. * highlight colors
  947. * @param {Object | String} color
  948. * @return {Object} colorObject
  949. */
  950. util.parseColor = function(color) {
  951. var c;
  952. if (util.isString(color)) {
  953. if (util.isValidHex(color)) {
  954. var hsv = util.hexToHSV(color);
  955. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  956. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  957. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  958. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  959. c = {
  960. background: color,
  961. border:darkerColorHex,
  962. highlight: {
  963. background:lighterColorHex,
  964. border:darkerColorHex
  965. }
  966. };
  967. }
  968. else {
  969. c = {
  970. background:color,
  971. border:color,
  972. highlight: {
  973. background:color,
  974. border:color
  975. }
  976. };
  977. }
  978. }
  979. else {
  980. c = {};
  981. c.background = color.background || 'white';
  982. c.border = color.border || c.background;
  983. if (util.isString(color.highlight)) {
  984. c.highlight = {
  985. border: color.highlight,
  986. background: color.highlight
  987. }
  988. }
  989. else {
  990. c.highlight = {};
  991. c.highlight.background = color.highlight && color.highlight.background || c.background;
  992. c.highlight.border = color.highlight && color.highlight.border || c.border;
  993. }
  994. }
  995. return c;
  996. };
  997. /**
  998. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  999. *
  1000. * @param {String} hex
  1001. * @returns {{r: *, g: *, b: *}}
  1002. */
  1003. util.hexToRGB = function hexToRGB(hex) {
  1004. hex = hex.replace("#","").toUpperCase();
  1005. var a = util.GiveDec(hex.substring(0, 1));
  1006. var b = util.GiveDec(hex.substring(1, 2));
  1007. var c = util.GiveDec(hex.substring(2, 3));
  1008. var d = util.GiveDec(hex.substring(3, 4));
  1009. var e = util.GiveDec(hex.substring(4, 5));
  1010. var f = util.GiveDec(hex.substring(5, 6));
  1011. var r = (a * 16) + b;
  1012. var g = (c * 16) + d;
  1013. var b = (e * 16) + f;
  1014. return {r:r,g:g,b:b};
  1015. };
  1016. util.RGBToHex = function RGBToHex(red,green,blue) {
  1017. var a = util.GiveHex(Math.floor(red / 16));
  1018. var b = util.GiveHex(red % 16);
  1019. var c = util.GiveHex(Math.floor(green / 16));
  1020. var d = util.GiveHex(green % 16);
  1021. var e = util.GiveHex(Math.floor(blue / 16));
  1022. var f = util.GiveHex(blue % 16);
  1023. var hex = a + b + c + d + e + f;
  1024. return "#" + hex;
  1025. };
  1026. /**
  1027. * http://www.javascripter.net/faq/rgb2hsv.htm
  1028. *
  1029. * @param red
  1030. * @param green
  1031. * @param blue
  1032. * @returns {*}
  1033. * @constructor
  1034. */
  1035. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1036. red=red/255; green=green/255; blue=blue/255;
  1037. var minRGB = Math.min(red,Math.min(green,blue));
  1038. var maxRGB = Math.max(red,Math.max(green,blue));
  1039. // Black-gray-white
  1040. if (minRGB == maxRGB) {
  1041. return {h:0,s:0,v:minRGB};
  1042. }
  1043. // Colors other than black-gray-white:
  1044. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1045. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1046. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1047. var saturation = (maxRGB - minRGB)/maxRGB;
  1048. var value = maxRGB;
  1049. return {h:hue,s:saturation,v:value};
  1050. };
  1051. /**
  1052. * https://gist.github.com/mjijackson/5311256
  1053. * @param hue
  1054. * @param saturation
  1055. * @param value
  1056. * @returns {{r: number, g: number, b: number}}
  1057. * @constructor
  1058. */
  1059. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1060. var r, g, b;
  1061. var i = Math.floor(h * 6);
  1062. var f = h * 6 - i;
  1063. var p = v * (1 - s);
  1064. var q = v * (1 - f * s);
  1065. var t = v * (1 - (1 - f) * s);
  1066. switch (i % 6) {
  1067. case 0: r = v, g = t, b = p; break;
  1068. case 1: r = q, g = v, b = p; break;
  1069. case 2: r = p, g = v, b = t; break;
  1070. case 3: r = p, g = q, b = v; break;
  1071. case 4: r = t, g = p, b = v; break;
  1072. case 5: r = v, g = p, b = q; break;
  1073. }
  1074. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1075. };
  1076. util.HSVToHex = function HSVToHex(h, s, v) {
  1077. var rgb = util.HSVToRGB(h, s, v);
  1078. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1079. };
  1080. util.hexToHSV = function hexToHSV(hex) {
  1081. var rgb = util.hexToRGB(hex);
  1082. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1083. };
  1084. util.isValidHex = function isValidHex(hex) {
  1085. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1086. return isOk;
  1087. };
  1088. util.copyObject = function copyObject(objectFrom, objectTo) {
  1089. for (var i in objectFrom) {
  1090. if (objectFrom.hasOwnProperty(i)) {
  1091. if (typeof objectFrom[i] == "object") {
  1092. objectTo[i] = {};
  1093. util.copyObject(objectFrom[i], objectTo[i]);
  1094. }
  1095. else {
  1096. objectTo[i] = objectFrom[i];
  1097. }
  1098. }
  1099. }
  1100. };
  1101. /**
  1102. * DataSet
  1103. *
  1104. * Usage:
  1105. * var dataSet = new DataSet({
  1106. * fieldId: '_id',
  1107. * convert: {
  1108. * // ...
  1109. * }
  1110. * });
  1111. *
  1112. * dataSet.add(item);
  1113. * dataSet.add(data);
  1114. * dataSet.update(item);
  1115. * dataSet.update(data);
  1116. * dataSet.remove(id);
  1117. * dataSet.remove(ids);
  1118. * var data = dataSet.get();
  1119. * var data = dataSet.get(id);
  1120. * var data = dataSet.get(ids);
  1121. * var data = dataSet.get(ids, options, data);
  1122. * dataSet.clear();
  1123. *
  1124. * A data set can:
  1125. * - add/remove/update data
  1126. * - gives triggers upon changes in the data
  1127. * - can import/export data in various data formats
  1128. *
  1129. * @param {Array | DataTable} [data] Optional array with initial data
  1130. * @param {Object} [options] Available options:
  1131. * {String} fieldId Field name of the id in the
  1132. * items, 'id' by default.
  1133. * {Object.<String, String} convert
  1134. * A map with field names as key,
  1135. * and the field type as value.
  1136. * @constructor DataSet
  1137. */
  1138. // TODO: add a DataSet constructor DataSet(data, options)
  1139. function DataSet (data, options) {
  1140. this.id = util.randomUUID();
  1141. // correctly read optional arguments
  1142. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1143. options = data;
  1144. data = null;
  1145. }
  1146. this.options = options || {};
  1147. this.data = {}; // map with data indexed by id
  1148. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1149. this.convert = {}; // field types by field name
  1150. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1151. if (this.options.convert) {
  1152. for (var field in this.options.convert) {
  1153. if (this.options.convert.hasOwnProperty(field)) {
  1154. var value = this.options.convert[field];
  1155. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1156. this.convert[field] = 'Date';
  1157. }
  1158. else {
  1159. this.convert[field] = value;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. this.subscribers = {}; // event subscribers
  1165. this.internalIds = {}; // internally generated id's
  1166. // add initial data when provided
  1167. if (data) {
  1168. this.add(data);
  1169. }
  1170. }
  1171. /**
  1172. * Subscribe to an event, add an event listener
  1173. * @param {String} event Event name. Available events: 'put', 'update',
  1174. * 'remove'
  1175. * @param {function} callback Callback method. Called with three parameters:
  1176. * {String} event
  1177. * {Object | null} params
  1178. * {String | Number} senderId
  1179. */
  1180. DataSet.prototype.on = function on (event, callback) {
  1181. var subscribers = this.subscribers[event];
  1182. if (!subscribers) {
  1183. subscribers = [];
  1184. this.subscribers[event] = subscribers;
  1185. }
  1186. subscribers.push({
  1187. callback: callback
  1188. });
  1189. };
  1190. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1191. DataSet.prototype.subscribe = DataSet.prototype.on;
  1192. /**
  1193. * Unsubscribe from an event, remove an event listener
  1194. * @param {String} event
  1195. * @param {function} callback
  1196. */
  1197. DataSet.prototype.off = function off(event, callback) {
  1198. var subscribers = this.subscribers[event];
  1199. if (subscribers) {
  1200. this.subscribers[event] = subscribers.filter(function (listener) {
  1201. return (listener.callback != callback);
  1202. });
  1203. }
  1204. };
  1205. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1206. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1207. /**
  1208. * Trigger an event
  1209. * @param {String} event
  1210. * @param {Object | null} params
  1211. * @param {String} [senderId] Optional id of the sender.
  1212. * @private
  1213. */
  1214. DataSet.prototype._trigger = function (event, params, senderId) {
  1215. if (event == '*') {
  1216. throw new Error('Cannot trigger event *');
  1217. }
  1218. var subscribers = [];
  1219. if (event in this.subscribers) {
  1220. subscribers = subscribers.concat(this.subscribers[event]);
  1221. }
  1222. if ('*' in this.subscribers) {
  1223. subscribers = subscribers.concat(this.subscribers['*']);
  1224. }
  1225. for (var i = 0; i < subscribers.length; i++) {
  1226. var subscriber = subscribers[i];
  1227. if (subscriber.callback) {
  1228. subscriber.callback(event, params, senderId || null);
  1229. }
  1230. }
  1231. };
  1232. /**
  1233. * Add data.
  1234. * Adding an item will fail when there already is an item with the same id.
  1235. * @param {Object | Array | DataTable} data
  1236. * @param {String} [senderId] Optional sender id
  1237. * @return {Array} addedIds Array with the ids of the added items
  1238. */
  1239. DataSet.prototype.add = function (data, senderId) {
  1240. var addedIds = [],
  1241. id,
  1242. me = this;
  1243. if (data instanceof Array) {
  1244. // Array
  1245. for (var i = 0, len = data.length; i < len; i++) {
  1246. id = me._addItem(data[i]);
  1247. addedIds.push(id);
  1248. }
  1249. }
  1250. else if (util.isDataTable(data)) {
  1251. // Google DataTable
  1252. var columns = this._getColumnNames(data);
  1253. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1254. var item = {};
  1255. for (var col = 0, cols = columns.length; col < cols; col++) {
  1256. var field = columns[col];
  1257. item[field] = data.getValue(row, col);
  1258. }
  1259. id = me._addItem(item);
  1260. addedIds.push(id);
  1261. }
  1262. }
  1263. else if (data instanceof Object) {
  1264. // Single item
  1265. id = me._addItem(data);
  1266. addedIds.push(id);
  1267. }
  1268. else {
  1269. throw new Error('Unknown dataType');
  1270. }
  1271. if (addedIds.length) {
  1272. this._trigger('add', {items: addedIds}, senderId);
  1273. }
  1274. return addedIds;
  1275. };
  1276. /**
  1277. * Update existing items. When an item does not exist, it will be created
  1278. * @param {Object | Array | DataTable} data
  1279. * @param {String} [senderId] Optional sender id
  1280. * @return {Array} updatedIds The ids of the added or updated items
  1281. */
  1282. DataSet.prototype.update = function (data, senderId) {
  1283. var addedIds = [],
  1284. updatedIds = [],
  1285. me = this,
  1286. fieldId = me.fieldId;
  1287. var addOrUpdate = function (item) {
  1288. var id = item[fieldId];
  1289. if (me.data[id]) {
  1290. // update item
  1291. id = me._updateItem(item);
  1292. updatedIds.push(id);
  1293. }
  1294. else {
  1295. // add new item
  1296. id = me._addItem(item);
  1297. addedIds.push(id);
  1298. }
  1299. };
  1300. if (data instanceof Array) {
  1301. // Array
  1302. for (var i = 0, len = data.length; i < len; i++) {
  1303. addOrUpdate(data[i]);
  1304. }
  1305. }
  1306. else if (util.isDataTable(data)) {
  1307. // Google DataTable
  1308. var columns = this._getColumnNames(data);
  1309. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1310. var item = {};
  1311. for (var col = 0, cols = columns.length; col < cols; col++) {
  1312. var field = columns[col];
  1313. item[field] = data.getValue(row, col);
  1314. }
  1315. addOrUpdate(item);
  1316. }
  1317. }
  1318. else if (data instanceof Object) {
  1319. // Single item
  1320. addOrUpdate(data);
  1321. }
  1322. else {
  1323. throw new Error('Unknown dataType');
  1324. }
  1325. if (addedIds.length) {
  1326. this._trigger('add', {items: addedIds}, senderId);
  1327. }
  1328. if (updatedIds.length) {
  1329. this._trigger('update', {items: updatedIds}, senderId);
  1330. }
  1331. return addedIds.concat(updatedIds);
  1332. };
  1333. /**
  1334. * Get a data item or multiple items.
  1335. *
  1336. * Usage:
  1337. *
  1338. * get()
  1339. * get(options: Object)
  1340. * get(options: Object, data: Array | DataTable)
  1341. *
  1342. * get(id: Number | String)
  1343. * get(id: Number | String, options: Object)
  1344. * get(id: Number | String, options: Object, data: Array | DataTable)
  1345. *
  1346. * get(ids: Number[] | String[])
  1347. * get(ids: Number[] | String[], options: Object)
  1348. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1349. *
  1350. * Where:
  1351. *
  1352. * {Number | String} id The id of an item
  1353. * {Number[] | String{}} ids An array with ids of items
  1354. * {Object} options An Object with options. Available options:
  1355. * {String} [type] Type of data to be returned. Can
  1356. * be 'DataTable' or 'Array' (default)
  1357. * {Object.<String, String>} [convert]
  1358. * {String[]} [fields] field names to be returned
  1359. * {function} [filter] filter items
  1360. * {String | function} [order] Order the items by
  1361. * a field name or custom sort function.
  1362. * {Array | DataTable} [data] If provided, items will be appended to this
  1363. * array or table. Required in case of Google
  1364. * DataTable.
  1365. *
  1366. * @throws Error
  1367. */
  1368. DataSet.prototype.get = function (args) {
  1369. var me = this;
  1370. var globalShowInternalIds = this.showInternalIds;
  1371. // parse the arguments
  1372. var id, ids, options, data;
  1373. var firstType = util.getType(arguments[0]);
  1374. if (firstType == 'String' || firstType == 'Number') {
  1375. // get(id [, options] [, data])
  1376. id = arguments[0];
  1377. options = arguments[1];
  1378. data = arguments[2];
  1379. }
  1380. else if (firstType == 'Array') {
  1381. // get(ids [, options] [, data])
  1382. ids = arguments[0];
  1383. options = arguments[1];
  1384. data = arguments[2];
  1385. }
  1386. else {
  1387. // get([, options] [, data])
  1388. options = arguments[0];
  1389. data = arguments[1];
  1390. }
  1391. // determine the return type
  1392. var type;
  1393. if (options && options.type) {
  1394. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1395. if (data && (type != util.getType(data))) {
  1396. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1397. 'does not correspond with specified options.type (' + options.type + ')');
  1398. }
  1399. if (type == 'DataTable' && !util.isDataTable(data)) {
  1400. throw new Error('Parameter "data" must be a DataTable ' +
  1401. 'when options.type is "DataTable"');
  1402. }
  1403. }
  1404. else if (data) {
  1405. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1406. }
  1407. else {
  1408. type = 'Array';
  1409. }
  1410. // we allow the setting of this value for a single get request.
  1411. if (options != undefined) {
  1412. if (options.showInternalIds != undefined) {
  1413. this.showInternalIds = options.showInternalIds;
  1414. }
  1415. }
  1416. // build options
  1417. var convert = options && options.convert || this.options.convert;
  1418. var filter = options && options.filter;
  1419. var items = [], item, itemId, i, len;
  1420. // convert items
  1421. if (id != undefined) {
  1422. // return a single item
  1423. item = me._getItem(id, convert);
  1424. if (filter && !filter(item)) {
  1425. item = null;
  1426. }
  1427. }
  1428. else if (ids != undefined) {
  1429. // return a subset of items
  1430. for (i = 0, len = ids.length; i < len; i++) {
  1431. item = me._getItem(ids[i], convert);
  1432. if (!filter || filter(item)) {
  1433. items.push(item);
  1434. }
  1435. }
  1436. }
  1437. else {
  1438. // return all items
  1439. for (itemId in this.data) {
  1440. if (this.data.hasOwnProperty(itemId)) {
  1441. item = me._getItem(itemId, convert);
  1442. if (!filter || filter(item)) {
  1443. items.push(item);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. // restore the global value of showInternalIds
  1449. this.showInternalIds = globalShowInternalIds;
  1450. // order the results
  1451. if (options && options.order && id == undefined) {
  1452. this._sort(items, options.order);
  1453. }
  1454. // filter fields of the items
  1455. if (options && options.fields) {
  1456. var fields = options.fields;
  1457. if (id != undefined) {
  1458. item = this._filterFields(item, fields);
  1459. }
  1460. else {
  1461. for (i = 0, len = items.length; i < len; i++) {
  1462. items[i] = this._filterFields(items[i], fields);
  1463. }
  1464. }
  1465. }
  1466. // return the results
  1467. if (type == 'DataTable') {
  1468. var columns = this._getColumnNames(data);
  1469. if (id != undefined) {
  1470. // append a single item to the data table
  1471. me._appendRow(data, columns, item);
  1472. }
  1473. else {
  1474. // copy the items to the provided data table
  1475. for (i = 0, len = items.length; i < len; i++) {
  1476. me._appendRow(data, columns, items[i]);
  1477. }
  1478. }
  1479. return data;
  1480. }
  1481. else {
  1482. // return an array
  1483. if (id != undefined) {
  1484. // a single item
  1485. return item;
  1486. }
  1487. else {
  1488. // multiple items
  1489. if (data) {
  1490. // copy the items to the provided array
  1491. for (i = 0, len = items.length; i < len; i++) {
  1492. data.push(items[i]);
  1493. }
  1494. return data;
  1495. }
  1496. else {
  1497. // just return our array
  1498. return items;
  1499. }
  1500. }
  1501. }
  1502. };
  1503. /**
  1504. * Get ids of all items or from a filtered set of items.
  1505. * @param {Object} [options] An Object with options. Available options:
  1506. * {function} [filter] filter items
  1507. * {String | function} [order] Order the items by
  1508. * a field name or custom sort function.
  1509. * @return {Array} ids
  1510. */
  1511. DataSet.prototype.getIds = function (options) {
  1512. var data = this.data,
  1513. filter = options && options.filter,
  1514. order = options && options.order,
  1515. convert = options && options.convert || this.options.convert,
  1516. i,
  1517. len,
  1518. id,
  1519. item,
  1520. items,
  1521. ids = [];
  1522. if (filter) {
  1523. // get filtered items
  1524. if (order) {
  1525. // create ordered list
  1526. items = [];
  1527. for (id in data) {
  1528. if (data.hasOwnProperty(id)) {
  1529. item = this._getItem(id, convert);
  1530. if (filter(item)) {
  1531. items.push(item);
  1532. }
  1533. }
  1534. }
  1535. this._sort(items, order);
  1536. for (i = 0, len = items.length; i < len; i++) {
  1537. ids[i] = items[i][this.fieldId];
  1538. }
  1539. }
  1540. else {
  1541. // create unordered list
  1542. for (id in data) {
  1543. if (data.hasOwnProperty(id)) {
  1544. item = this._getItem(id, convert);
  1545. if (filter(item)) {
  1546. ids.push(item[this.fieldId]);
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. else {
  1553. // get all items
  1554. if (order) {
  1555. // create an ordered list
  1556. items = [];
  1557. for (id in data) {
  1558. if (data.hasOwnProperty(id)) {
  1559. items.push(data[id]);
  1560. }
  1561. }
  1562. this._sort(items, order);
  1563. for (i = 0, len = items.length; i < len; i++) {
  1564. ids[i] = items[i][this.fieldId];
  1565. }
  1566. }
  1567. else {
  1568. // create unordered list
  1569. for (id in data) {
  1570. if (data.hasOwnProperty(id)) {
  1571. item = data[id];
  1572. ids.push(item[this.fieldId]);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. return ids;
  1578. };
  1579. /**
  1580. * Execute a callback function for every item in the dataset.
  1581. * @param {function} callback
  1582. * @param {Object} [options] Available options:
  1583. * {Object.<String, String>} [convert]
  1584. * {String[]} [fields] filter fields
  1585. * {function} [filter] filter items
  1586. * {String | function} [order] Order the items by
  1587. * a field name or custom sort function.
  1588. */
  1589. DataSet.prototype.forEach = function (callback, options) {
  1590. var filter = options && options.filter,
  1591. convert = options && options.convert || this.options.convert,
  1592. data = this.data,
  1593. item,
  1594. id;
  1595. if (options && options.order) {
  1596. // execute forEach on ordered list
  1597. var items = this.get(options);
  1598. for (var i = 0, len = items.length; i < len; i++) {
  1599. item = items[i];
  1600. id = item[this.fieldId];
  1601. callback(item, id);
  1602. }
  1603. }
  1604. else {
  1605. // unordered
  1606. for (id in data) {
  1607. if (data.hasOwnProperty(id)) {
  1608. item = this._getItem(id, convert);
  1609. if (!filter || filter(item)) {
  1610. callback(item, id);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. };
  1616. /**
  1617. * Map every item in the dataset.
  1618. * @param {function} callback
  1619. * @param {Object} [options] Available options:
  1620. * {Object.<String, String>} [convert]
  1621. * {String[]} [fields] filter fields
  1622. * {function} [filter] filter items
  1623. * {String | function} [order] Order the items by
  1624. * a field name or custom sort function.
  1625. * @return {Object[]} mappedItems
  1626. */
  1627. DataSet.prototype.map = function (callback, options) {
  1628. var filter = options && options.filter,
  1629. convert = options && options.convert || this.options.convert,
  1630. mappedItems = [],
  1631. data = this.data,
  1632. item;
  1633. // convert and filter items
  1634. for (var id in data) {
  1635. if (data.hasOwnProperty(id)) {
  1636. item = this._getItem(id, convert);
  1637. if (!filter || filter(item)) {
  1638. mappedItems.push(callback(item, id));
  1639. }
  1640. }
  1641. }
  1642. // order items
  1643. if (options && options.order) {
  1644. this._sort(mappedItems, options.order);
  1645. }
  1646. return mappedItems;
  1647. };
  1648. /**
  1649. * Filter the fields of an item
  1650. * @param {Object} item
  1651. * @param {String[]} fields Field names
  1652. * @return {Object} filteredItem
  1653. * @private
  1654. */
  1655. DataSet.prototype._filterFields = function (item, fields) {
  1656. var filteredItem = {};
  1657. for (var field in item) {
  1658. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1659. filteredItem[field] = item[field];
  1660. }
  1661. }
  1662. return filteredItem;
  1663. };
  1664. /**
  1665. * Sort the provided array with items
  1666. * @param {Object[]} items
  1667. * @param {String | function} order A field name or custom sort function.
  1668. * @private
  1669. */
  1670. DataSet.prototype._sort = function (items, order) {
  1671. if (util.isString(order)) {
  1672. // order by provided field name
  1673. var name = order; // field name
  1674. items.sort(function (a, b) {
  1675. var av = a[name];
  1676. var bv = b[name];
  1677. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1678. });
  1679. }
  1680. else if (typeof order === 'function') {
  1681. // order by sort function
  1682. items.sort(order);
  1683. }
  1684. // TODO: extend order by an Object {field:String, direction:String}
  1685. // where direction can be 'asc' or 'desc'
  1686. else {
  1687. throw new TypeError('Order must be a function or a string');
  1688. }
  1689. };
  1690. /**
  1691. * Remove an object by pointer or by id
  1692. * @param {String | Number | Object | Array} id Object or id, or an array with
  1693. * objects or ids to be removed
  1694. * @param {String} [senderId] Optional sender id
  1695. * @return {Array} removedIds
  1696. */
  1697. DataSet.prototype.remove = function (id, senderId) {
  1698. var removedIds = [],
  1699. i, len, removedId;
  1700. if (id instanceof Array) {
  1701. for (i = 0, len = id.length; i < len; i++) {
  1702. removedId = this._remove(id[i]);
  1703. if (removedId != null) {
  1704. removedIds.push(removedId);
  1705. }
  1706. }
  1707. }
  1708. else {
  1709. removedId = this._remove(id);
  1710. if (removedId != null) {
  1711. removedIds.push(removedId);
  1712. }
  1713. }
  1714. if (removedIds.length) {
  1715. this._trigger('remove', {items: removedIds}, senderId);
  1716. }
  1717. return removedIds;
  1718. };
  1719. /**
  1720. * Remove an item by its id
  1721. * @param {Number | String | Object} id id or item
  1722. * @returns {Number | String | null} id
  1723. * @private
  1724. */
  1725. DataSet.prototype._remove = function (id) {
  1726. if (util.isNumber(id) || util.isString(id)) {
  1727. if (this.data[id]) {
  1728. delete this.data[id];
  1729. delete this.internalIds[id];
  1730. return id;
  1731. }
  1732. }
  1733. else if (id instanceof Object) {
  1734. var itemId = id[this.fieldId];
  1735. if (itemId && this.data[itemId]) {
  1736. delete this.data[itemId];
  1737. delete this.internalIds[itemId];
  1738. return itemId;
  1739. }
  1740. }
  1741. return null;
  1742. };
  1743. /**
  1744. * Clear the data
  1745. * @param {String} [senderId] Optional sender id
  1746. * @return {Array} removedIds The ids of all removed items
  1747. */
  1748. DataSet.prototype.clear = function (senderId) {
  1749. var ids = Object.keys(this.data);
  1750. this.data = {};
  1751. this.internalIds = {};
  1752. this._trigger('remove', {items: ids}, senderId);
  1753. return ids;
  1754. };
  1755. /**
  1756. * Find the item with maximum value of a specified field
  1757. * @param {String} field
  1758. * @return {Object | null} item Item containing max value, or null if no items
  1759. */
  1760. DataSet.prototype.max = function (field) {
  1761. var data = this.data,
  1762. max = null,
  1763. maxField = null;
  1764. for (var id in data) {
  1765. if (data.hasOwnProperty(id)) {
  1766. var item = data[id];
  1767. var itemField = item[field];
  1768. if (itemField != null && (!max || itemField > maxField)) {
  1769. max = item;
  1770. maxField = itemField;
  1771. }
  1772. }
  1773. }
  1774. return max;
  1775. };
  1776. /**
  1777. * Find the item with minimum value of a specified field
  1778. * @param {String} field
  1779. * @return {Object | null} item Item containing max value, or null if no items
  1780. */
  1781. DataSet.prototype.min = function (field) {
  1782. var data = this.data,
  1783. min = null,
  1784. minField = null;
  1785. for (var id in data) {
  1786. if (data.hasOwnProperty(id)) {
  1787. var item = data[id];
  1788. var itemField = item[field];
  1789. if (itemField != null && (!min || itemField < minField)) {
  1790. min = item;
  1791. minField = itemField;
  1792. }
  1793. }
  1794. }
  1795. return min;
  1796. };
  1797. /**
  1798. * Find all distinct values of a specified field
  1799. * @param {String} field
  1800. * @return {Array} values Array containing all distinct values. If data items
  1801. * do not contain the specified field are ignored.
  1802. * The returned array is unordered.
  1803. */
  1804. DataSet.prototype.distinct = function (field) {
  1805. var data = this.data,
  1806. values = [],
  1807. fieldType = this.options.convert[field],
  1808. count = 0;
  1809. for (var prop in data) {
  1810. if (data.hasOwnProperty(prop)) {
  1811. var item = data[prop];
  1812. var value = util.convert(item[field], fieldType);
  1813. var exists = false;
  1814. for (var i = 0; i < count; i++) {
  1815. if (values[i] == value) {
  1816. exists = true;
  1817. break;
  1818. }
  1819. }
  1820. if (!exists && (value !== undefined)) {
  1821. values[count] = value;
  1822. count++;
  1823. }
  1824. }
  1825. }
  1826. return values;
  1827. };
  1828. /**
  1829. * Add a single item. Will fail when an item with the same id already exists.
  1830. * @param {Object} item
  1831. * @return {String} id
  1832. * @private
  1833. */
  1834. DataSet.prototype._addItem = function (item) {
  1835. var id = item[this.fieldId];
  1836. if (id != undefined) {
  1837. // check whether this id is already taken
  1838. if (this.data[id]) {
  1839. // item already exists
  1840. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1841. }
  1842. }
  1843. else {
  1844. // generate an id
  1845. id = util.randomUUID();
  1846. item[this.fieldId] = id;
  1847. this.internalIds[id] = item;
  1848. }
  1849. var d = {};
  1850. for (var field in item) {
  1851. if (item.hasOwnProperty(field)) {
  1852. var fieldType = this.convert[field]; // type may be undefined
  1853. d[field] = util.convert(item[field], fieldType);
  1854. }
  1855. }
  1856. this.data[id] = d;
  1857. return id;
  1858. };
  1859. /**
  1860. * Get an item. Fields can be converted to a specific type
  1861. * @param {String} id
  1862. * @param {Object.<String, String>} [convert] field types to convert
  1863. * @return {Object | null} item
  1864. * @private
  1865. */
  1866. DataSet.prototype._getItem = function (id, convert) {
  1867. var field, value;
  1868. // get the item from the dataset
  1869. var raw = this.data[id];
  1870. if (!raw) {
  1871. return null;
  1872. }
  1873. // convert the items field types
  1874. var converted = {},
  1875. fieldId = this.fieldId,
  1876. internalIds = this.internalIds;
  1877. if (convert) {
  1878. for (field in raw) {
  1879. if (raw.hasOwnProperty(field)) {
  1880. value = raw[field];
  1881. // output all fields, except internal ids
  1882. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1883. converted[field] = util.convert(value, convert[field]);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. else {
  1889. // no field types specified, no converting needed
  1890. for (field in raw) {
  1891. if (raw.hasOwnProperty(field)) {
  1892. value = raw[field];
  1893. // output all fields, except internal ids
  1894. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1895. converted[field] = value;
  1896. }
  1897. }
  1898. }
  1899. }
  1900. return converted;
  1901. };
  1902. /**
  1903. * Update a single item: merge with existing item.
  1904. * Will fail when the item has no id, or when there does not exist an item
  1905. * with the same id.
  1906. * @param {Object} item
  1907. * @return {String} id
  1908. * @private
  1909. */
  1910. DataSet.prototype._updateItem = function (item) {
  1911. var id = item[this.fieldId];
  1912. if (id == undefined) {
  1913. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1914. }
  1915. var d = this.data[id];
  1916. if (!d) {
  1917. // item doesn't exist
  1918. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1919. }
  1920. // merge with current item
  1921. for (var field in item) {
  1922. if (item.hasOwnProperty(field)) {
  1923. var fieldType = this.convert[field]; // type may be undefined
  1924. d[field] = util.convert(item[field], fieldType);
  1925. }
  1926. }
  1927. return id;
  1928. };
  1929. /**
  1930. * check if an id is an internal or external id
  1931. * @param id
  1932. * @returns {boolean}
  1933. * @private
  1934. */
  1935. DataSet.prototype.isInternalId = function(id) {
  1936. return (id in this.internalIds);
  1937. };
  1938. /**
  1939. * Get an array with the column names of a Google DataTable
  1940. * @param {DataTable} dataTable
  1941. * @return {String[]} columnNames
  1942. * @private
  1943. */
  1944. DataSet.prototype._getColumnNames = function (dataTable) {
  1945. var columns = [];
  1946. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1947. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1948. }
  1949. return columns;
  1950. };
  1951. /**
  1952. * Append an item as a row to the dataTable
  1953. * @param dataTable
  1954. * @param columns
  1955. * @param item
  1956. * @private
  1957. */
  1958. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1959. var row = dataTable.addRow();
  1960. for (var col = 0, cols = columns.length; col < cols; col++) {
  1961. var field = columns[col];
  1962. dataTable.setValue(row, col, item[field]);
  1963. }
  1964. };
  1965. /**
  1966. * DataView
  1967. *
  1968. * a dataview offers a filtered view on a dataset or an other dataview.
  1969. *
  1970. * @param {DataSet | DataView} data
  1971. * @param {Object} [options] Available options: see method get
  1972. *
  1973. * @constructor DataView
  1974. */
  1975. function DataView (data, options) {
  1976. this.id = util.randomUUID();
  1977. this.data = null;
  1978. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1979. this.options = options || {};
  1980. this.fieldId = 'id'; // name of the field containing id
  1981. this.subscribers = {}; // event subscribers
  1982. var me = this;
  1983. this.listener = function () {
  1984. me._onEvent.apply(me, arguments);
  1985. };
  1986. this.setData(data);
  1987. }
  1988. // TODO: implement a function .config() to dynamically update things like configured filter
  1989. // and trigger changes accordingly
  1990. /**
  1991. * Set a data source for the view
  1992. * @param {DataSet | DataView} data
  1993. */
  1994. DataView.prototype.setData = function (data) {
  1995. var ids, dataItems, i, len;
  1996. if (this.data) {
  1997. // unsubscribe from current dataset
  1998. if (this.data.unsubscribe) {
  1999. this.data.unsubscribe('*', this.listener);
  2000. }
  2001. // trigger a remove of all items in memory
  2002. ids = [];
  2003. for (var id in this.ids) {
  2004. if (this.ids.hasOwnProperty(id)) {
  2005. ids.push(id);
  2006. }
  2007. }
  2008. this.ids = {};
  2009. this._trigger('remove', {items: ids});
  2010. }
  2011. this.data = data;
  2012. if (this.data) {
  2013. // update fieldId
  2014. this.fieldId = this.options.fieldId ||
  2015. (this.data && this.data.options && this.data.options.fieldId) ||
  2016. 'id';
  2017. // trigger an add of all added items
  2018. ids = this.data.getIds({filter: this.options && this.options.filter});
  2019. for (i = 0, len = ids.length; i < len; i++) {
  2020. id = ids[i];
  2021. this.ids[id] = true;
  2022. }
  2023. this._trigger('add', {items: ids});
  2024. // subscribe to new dataset
  2025. if (this.data.on) {
  2026. this.data.on('*', this.listener);
  2027. }
  2028. }
  2029. };
  2030. /**
  2031. * Get data from the data view
  2032. *
  2033. * Usage:
  2034. *
  2035. * get()
  2036. * get(options: Object)
  2037. * get(options: Object, data: Array | DataTable)
  2038. *
  2039. * get(id: Number)
  2040. * get(id: Number, options: Object)
  2041. * get(id: Number, options: Object, data: Array | DataTable)
  2042. *
  2043. * get(ids: Number[])
  2044. * get(ids: Number[], options: Object)
  2045. * get(ids: Number[], options: Object, data: Array | DataTable)
  2046. *
  2047. * Where:
  2048. *
  2049. * {Number | String} id The id of an item
  2050. * {Number[] | String{}} ids An array with ids of items
  2051. * {Object} options An Object with options. Available options:
  2052. * {String} [type] Type of data to be returned. Can
  2053. * be 'DataTable' or 'Array' (default)
  2054. * {Object.<String, String>} [convert]
  2055. * {String[]} [fields] field names to be returned
  2056. * {function} [filter] filter items
  2057. * {String | function} [order] Order the items by
  2058. * a field name or custom sort function.
  2059. * {Array | DataTable} [data] If provided, items will be appended to this
  2060. * array or table. Required in case of Google
  2061. * DataTable.
  2062. * @param args
  2063. */
  2064. DataView.prototype.get = function (args) {
  2065. var me = this;
  2066. // parse the arguments
  2067. var ids, options, data;
  2068. var firstType = util.getType(arguments[0]);
  2069. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2070. // get(id(s) [, options] [, data])
  2071. ids = arguments[0]; // can be a single id or an array with ids
  2072. options = arguments[1];
  2073. data = arguments[2];
  2074. }
  2075. else {
  2076. // get([, options] [, data])
  2077. options = arguments[0];
  2078. data = arguments[1];
  2079. }
  2080. // extend the options with the default options and provided options
  2081. var viewOptions = util.extend({}, this.options, options);
  2082. // create a combined filter method when needed
  2083. if (this.options.filter && options && options.filter) {
  2084. viewOptions.filter = function (item) {
  2085. return me.options.filter(item) && options.filter(item);
  2086. }
  2087. }
  2088. // build up the call to the linked data set
  2089. var getArguments = [];
  2090. if (ids != undefined) {
  2091. getArguments.push(ids);
  2092. }
  2093. getArguments.push(viewOptions);
  2094. getArguments.push(data);
  2095. return this.data && this.data.get.apply(this.data, getArguments);
  2096. };
  2097. /**
  2098. * Get ids of all items or from a filtered set of items.
  2099. * @param {Object} [options] An Object with options. Available options:
  2100. * {function} [filter] filter items
  2101. * {String | function} [order] Order the items by
  2102. * a field name or custom sort function.
  2103. * @return {Array} ids
  2104. */
  2105. DataView.prototype.getIds = function (options) {
  2106. var ids;
  2107. if (this.data) {
  2108. var defaultFilter = this.options.filter;
  2109. var filter;
  2110. if (options && options.filter) {
  2111. if (defaultFilter) {
  2112. filter = function (item) {
  2113. return defaultFilter(item) && options.filter(item);
  2114. }
  2115. }
  2116. else {
  2117. filter = options.filter;
  2118. }
  2119. }
  2120. else {
  2121. filter = defaultFilter;
  2122. }
  2123. ids = this.data.getIds({
  2124. filter: filter,
  2125. order: options && options.order
  2126. });
  2127. }
  2128. else {
  2129. ids = [];
  2130. }
  2131. return ids;
  2132. };
  2133. /**
  2134. * Event listener. Will propagate all events from the connected data set to
  2135. * the subscribers of the DataView, but will filter the items and only trigger
  2136. * when there are changes in the filtered data set.
  2137. * @param {String} event
  2138. * @param {Object | null} params
  2139. * @param {String} senderId
  2140. * @private
  2141. */
  2142. DataView.prototype._onEvent = function (event, params, senderId) {
  2143. var i, len, id, item,
  2144. ids = params && params.items,
  2145. data = this.data,
  2146. added = [],
  2147. updated = [],
  2148. removed = [];
  2149. if (ids && data) {
  2150. switch (event) {
  2151. case 'add':
  2152. // filter the ids of the added items
  2153. for (i = 0, len = ids.length; i < len; i++) {
  2154. id = ids[i];
  2155. item = this.get(id);
  2156. if (item) {
  2157. this.ids[id] = true;
  2158. added.push(id);
  2159. }
  2160. }
  2161. break;
  2162. case 'update':
  2163. // determine the event from the views viewpoint: an updated
  2164. // item can be added, updated, or removed from this view.
  2165. for (i = 0, len = ids.length; i < len; i++) {
  2166. id = ids[i];
  2167. item = this.get(id);
  2168. if (item) {
  2169. if (this.ids[id]) {
  2170. updated.push(id);
  2171. }
  2172. else {
  2173. this.ids[id] = true;
  2174. added.push(id);
  2175. }
  2176. }
  2177. else {
  2178. if (this.ids[id]) {
  2179. delete this.ids[id];
  2180. removed.push(id);
  2181. }
  2182. else {
  2183. // nothing interesting for me :-(
  2184. }
  2185. }
  2186. }
  2187. break;
  2188. case 'remove':
  2189. // filter the ids of the removed items
  2190. for (i = 0, len = ids.length; i < len; i++) {
  2191. id = ids[i];
  2192. if (this.ids[id]) {
  2193. delete this.ids[id];
  2194. removed.push(id);
  2195. }
  2196. }
  2197. break;
  2198. }
  2199. if (added.length) {
  2200. this._trigger('add', {items: added}, senderId);
  2201. }
  2202. if (updated.length) {
  2203. this._trigger('update', {items: updated}, senderId);
  2204. }
  2205. if (removed.length) {
  2206. this._trigger('remove', {items: removed}, senderId);
  2207. }
  2208. }
  2209. };
  2210. // copy subscription functionality from DataSet
  2211. DataView.prototype.on = DataSet.prototype.on;
  2212. DataView.prototype.off = DataSet.prototype.off;
  2213. DataView.prototype._trigger = DataSet.prototype._trigger;
  2214. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2215. DataView.prototype.subscribe = DataView.prototype.on;
  2216. DataView.prototype.unsubscribe = DataView.prototype.off;
  2217. /**
  2218. * Utility functions for ordering and stacking of items
  2219. */
  2220. var stack = {};
  2221. /**
  2222. * Order items by their start data
  2223. * @param {Item[]} items
  2224. */
  2225. stack.orderByStart = function orderByStart(items) {
  2226. items.sort(function (a, b) {
  2227. return a.data.start - b.data.start;
  2228. });
  2229. };
  2230. /**
  2231. * Order items by their end date. If they have no end date, their start date
  2232. * is used.
  2233. * @param {Item[]} items
  2234. */
  2235. stack.orderByEnd = function orderByEnd(items) {
  2236. items.sort(function (a, b) {
  2237. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2238. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2239. return aTime - bTime;
  2240. });
  2241. };
  2242. /**
  2243. * Adjust vertical positions of the items such that they don't overlap each
  2244. * other.
  2245. * @param {Item[]} items
  2246. * All visible items
  2247. * @param {{item: number, axis: number}} margin
  2248. * Margins between items and between items and the axis.
  2249. * @param {boolean} [force=false]
  2250. * If true, all items will be repositioned. If false (default), only
  2251. * items having a top===null will be re-stacked
  2252. */
  2253. stack.stack = function _stack (items, margin, force) {
  2254. var i, iMax;
  2255. if (force) {
  2256. // reset top position of all items
  2257. for (i = 0, iMax = items.length; i < iMax; i++) {
  2258. items[i].top = null;
  2259. }
  2260. }
  2261. // calculate new, non-overlapping positions
  2262. for (i = 0, iMax = items.length; i < iMax; i++) {
  2263. var item = items[i];
  2264. if (item.top === null) {
  2265. // initialize top position
  2266. item.top = margin.axis;
  2267. do {
  2268. // TODO: optimize checking for overlap. when there is a gap without items,
  2269. // you only need to check for items from the next item on, not from zero
  2270. var collidingItem = null;
  2271. for (var j = 0, jj = items.length; j < jj; j++) {
  2272. var other = items[j];
  2273. if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
  2274. collidingItem = other;
  2275. break;
  2276. }
  2277. }
  2278. if (collidingItem != null) {
  2279. // There is a collision. Reposition the items above the colliding element
  2280. item.top = collidingItem.top + collidingItem.height + margin.item;
  2281. }
  2282. } while (collidingItem);
  2283. }
  2284. }
  2285. };
  2286. /**
  2287. * Adjust vertical positions of the items without stacking them
  2288. * @param {Item[]} items
  2289. * All visible items
  2290. * @param {{item: number, axis: number}} margin
  2291. * Margins between items and between items and the axis.
  2292. */
  2293. stack.nostack = function nostack (items, margin) {
  2294. var i, iMax;
  2295. // reset top position of all items
  2296. for (i = 0, iMax = items.length; i < iMax; i++) {
  2297. items[i].top = margin.axis;
  2298. }
  2299. };
  2300. /**
  2301. * Test if the two provided items collide
  2302. * The items must have parameters left, width, top, and height.
  2303. * @param {Item} a The first item
  2304. * @param {Item} b The second item
  2305. * @param {Number} margin A minimum required margin.
  2306. * If margin is provided, the two items will be
  2307. * marked colliding when they overlap or
  2308. * when the margin between the two is smaller than
  2309. * the requested margin.
  2310. * @return {boolean} true if a and b collide, else false
  2311. */
  2312. stack.collision = function collision (a, b, margin) {
  2313. return ((a.left - margin) < (b.left + b.width) &&
  2314. (a.left + a.width + margin) > b.left &&
  2315. (a.top - margin) < (b.top + b.height) &&
  2316. (a.top + a.height + margin) > b.top);
  2317. };
  2318. /**
  2319. * @constructor TimeStep
  2320. * The class TimeStep is an iterator for dates. You provide a start date and an
  2321. * end date. The class itself determines the best scale (step size) based on the
  2322. * provided start Date, end Date, and minimumStep.
  2323. *
  2324. * If minimumStep is provided, the step size is chosen as close as possible
  2325. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2326. * provided, the scale is set to 1 DAY.
  2327. * The minimumStep should correspond with the onscreen size of about 6 characters
  2328. *
  2329. * Alternatively, you can set a scale by hand.
  2330. * After creation, you can initialize the class by executing first(). Then you
  2331. * can iterate from the start date to the end date via next(). You can check if
  2332. * the end date is reached with the function hasNext(). After each step, you can
  2333. * retrieve the current date via getCurrent().
  2334. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2335. * days, to years.
  2336. *
  2337. * Version: 1.2
  2338. *
  2339. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2340. * or new Date(2010, 9, 21, 23, 45, 00)
  2341. * @param {Date} [end] The end date
  2342. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2343. */
  2344. function TimeStep(start, end, minimumStep) {
  2345. // variables
  2346. this.current = new Date();
  2347. this._start = new Date();
  2348. this._end = new Date();
  2349. this.autoScale = true;
  2350. this.scale = TimeStep.SCALE.DAY;
  2351. this.step = 1;
  2352. // initialize the range
  2353. this.setRange(start, end, minimumStep);
  2354. }
  2355. /// enum scale
  2356. TimeStep.SCALE = {
  2357. MILLISECOND: 1,
  2358. SECOND: 2,
  2359. MINUTE: 3,
  2360. HOUR: 4,
  2361. DAY: 5,
  2362. WEEKDAY: 6,
  2363. MONTH: 7,
  2364. YEAR: 8
  2365. };
  2366. /**
  2367. * Set a new range
  2368. * If minimumStep is provided, the step size is chosen as close as possible
  2369. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2370. * provided, the scale is set to 1 DAY.
  2371. * The minimumStep should correspond with the onscreen size of about 6 characters
  2372. * @param {Date} [start] The start date and time.
  2373. * @param {Date} [end] The end date and time.
  2374. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2375. */
  2376. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2377. if (!(start instanceof Date) || !(end instanceof Date)) {
  2378. throw "No legal start or end date in method setRange";
  2379. }
  2380. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2381. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2382. if (this.autoScale) {
  2383. this.setMinimumStep(minimumStep);
  2384. }
  2385. };
  2386. /**
  2387. * Set the range iterator to the start date.
  2388. */
  2389. TimeStep.prototype.first = function() {
  2390. this.current = new Date(this._start.valueOf());
  2391. this.roundToMinor();
  2392. };
  2393. /**
  2394. * Round the current date to the first minor date value
  2395. * This must be executed once when the current date is set to start Date
  2396. */
  2397. TimeStep.prototype.roundToMinor = function() {
  2398. // round to floor
  2399. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2400. //noinspection FallthroughInSwitchStatementJS
  2401. switch (this.scale) {
  2402. case TimeStep.SCALE.YEAR:
  2403. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2404. this.current.setMonth(0);
  2405. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2406. case TimeStep.SCALE.DAY: // intentional fall through
  2407. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2408. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2409. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2410. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2411. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2412. }
  2413. if (this.step != 1) {
  2414. // round down to the first minor value that is a multiple of the current step size
  2415. switch (this.scale) {
  2416. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2417. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2418. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2419. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2420. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2421. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2422. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2423. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2424. default: break;
  2425. }
  2426. }
  2427. };
  2428. /**
  2429. * Check if the there is a next step
  2430. * @return {boolean} true if the current date has not passed the end date
  2431. */
  2432. TimeStep.prototype.hasNext = function () {
  2433. return (this.current.valueOf() <= this._end.valueOf());
  2434. };
  2435. /**
  2436. * Do the next step
  2437. */
  2438. TimeStep.prototype.next = function() {
  2439. var prev = this.current.valueOf();
  2440. // Two cases, needed to prevent issues with switching daylight savings
  2441. // (end of March and end of October)
  2442. if (this.current.getMonth() < 6) {
  2443. switch (this.scale) {
  2444. case TimeStep.SCALE.MILLISECOND:
  2445. this.current = new Date(this.current.valueOf() + this.step); break;
  2446. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2447. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2448. case TimeStep.SCALE.HOUR:
  2449. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2450. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2451. var h = this.current.getHours();
  2452. this.current.setHours(h - (h % this.step));
  2453. break;
  2454. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2455. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2456. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2457. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2458. default: break;
  2459. }
  2460. }
  2461. else {
  2462. switch (this.scale) {
  2463. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2464. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2465. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2466. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2467. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2468. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2469. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2470. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2471. default: break;
  2472. }
  2473. }
  2474. if (this.step != 1) {
  2475. // round down to the correct major value
  2476. switch (this.scale) {
  2477. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2478. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2479. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2480. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2481. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2482. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2483. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2484. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2485. default: break;
  2486. }
  2487. }
  2488. // safety mechanism: if current time is still unchanged, move to the end
  2489. if (this.current.valueOf() == prev) {
  2490. this.current = new Date(this._end.valueOf());
  2491. }
  2492. };
  2493. /**
  2494. * Get the current datetime
  2495. * @return {Date} current The current date
  2496. */
  2497. TimeStep.prototype.getCurrent = function() {
  2498. return this.current;
  2499. };
  2500. /**
  2501. * Set a custom scale. Autoscaling will be disabled.
  2502. * For example setScale(SCALE.MINUTES, 5) will result
  2503. * in minor steps of 5 minutes, and major steps of an hour.
  2504. *
  2505. * @param {TimeStep.SCALE} newScale
  2506. * A scale. Choose from SCALE.MILLISECOND,
  2507. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2508. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2509. * SCALE.YEAR.
  2510. * @param {Number} newStep A step size, by default 1. Choose for
  2511. * example 1, 2, 5, or 10.
  2512. */
  2513. TimeStep.prototype.setScale = function(newScale, newStep) {
  2514. this.scale = newScale;
  2515. if (newStep > 0) {
  2516. this.step = newStep;
  2517. }
  2518. this.autoScale = false;
  2519. };
  2520. /**
  2521. * Enable or disable autoscaling
  2522. * @param {boolean} enable If true, autoascaling is set true
  2523. */
  2524. TimeStep.prototype.setAutoScale = function (enable) {
  2525. this.autoScale = enable;
  2526. };
  2527. /**
  2528. * Automatically determine the scale that bests fits the provided minimum step
  2529. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2530. */
  2531. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2532. if (minimumStep == undefined) {
  2533. return;
  2534. }
  2535. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2536. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2537. var stepDay = (1000 * 60 * 60 * 24);
  2538. var stepHour = (1000 * 60 * 60);
  2539. var stepMinute = (1000 * 60);
  2540. var stepSecond = (1000);
  2541. var stepMillisecond= (1);
  2542. // find the smallest step that is larger than the provided minimumStep
  2543. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2544. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2545. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2546. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2547. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2548. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2549. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2550. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2551. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2552. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2553. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2554. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2555. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2556. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2557. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2558. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2559. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2560. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2561. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2562. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2563. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2564. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2565. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2566. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2567. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2568. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2569. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2570. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2571. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2572. };
  2573. /**
  2574. * Snap a date to a rounded value.
  2575. * The snap intervals are dependent on the current scale and step.
  2576. * @param {Date} date the date to be snapped.
  2577. * @return {Date} snappedDate
  2578. */
  2579. TimeStep.prototype.snap = function(date) {
  2580. var clone = new Date(date.valueOf());
  2581. if (this.scale == TimeStep.SCALE.YEAR) {
  2582. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2583. clone.setFullYear(Math.round(year / this.step) * this.step);
  2584. clone.setMonth(0);
  2585. clone.setDate(0);
  2586. clone.setHours(0);
  2587. clone.setMinutes(0);
  2588. clone.setSeconds(0);
  2589. clone.setMilliseconds(0);
  2590. }
  2591. else if (this.scale == TimeStep.SCALE.MONTH) {
  2592. if (clone.getDate() > 15) {
  2593. clone.setDate(1);
  2594. clone.setMonth(clone.getMonth() + 1);
  2595. // important: first set Date to 1, after that change the month.
  2596. }
  2597. else {
  2598. clone.setDate(1);
  2599. }
  2600. clone.setHours(0);
  2601. clone.setMinutes(0);
  2602. clone.setSeconds(0);
  2603. clone.setMilliseconds(0);
  2604. }
  2605. else if (this.scale == TimeStep.SCALE.DAY) {
  2606. //noinspection FallthroughInSwitchStatementJS
  2607. switch (this.step) {
  2608. case 5:
  2609. case 2:
  2610. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2611. default:
  2612. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2613. }
  2614. clone.setMinutes(0);
  2615. clone.setSeconds(0);
  2616. clone.setMilliseconds(0);
  2617. }
  2618. else if (this.scale == TimeStep.SCALE.WEEKDAY) {
  2619. //noinspection FallthroughInSwitchStatementJS
  2620. switch (this.step) {
  2621. case 5:
  2622. case 2:
  2623. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2624. default:
  2625. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  2626. }
  2627. clone.setMinutes(0);
  2628. clone.setSeconds(0);
  2629. clone.setMilliseconds(0);
  2630. }
  2631. else if (this.scale == TimeStep.SCALE.HOUR) {
  2632. switch (this.step) {
  2633. case 4:
  2634. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2635. default:
  2636. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2637. }
  2638. clone.setSeconds(0);
  2639. clone.setMilliseconds(0);
  2640. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2641. //noinspection FallthroughInSwitchStatementJS
  2642. switch (this.step) {
  2643. case 15:
  2644. case 10:
  2645. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2646. clone.setSeconds(0);
  2647. break;
  2648. case 5:
  2649. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2650. default:
  2651. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2652. }
  2653. clone.setMilliseconds(0);
  2654. }
  2655. else if (this.scale == TimeStep.SCALE.SECOND) {
  2656. //noinspection FallthroughInSwitchStatementJS
  2657. switch (this.step) {
  2658. case 15:
  2659. case 10:
  2660. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2661. clone.setMilliseconds(0);
  2662. break;
  2663. case 5:
  2664. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2665. default:
  2666. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2667. }
  2668. }
  2669. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2670. var step = this.step > 5 ? this.step / 2 : 1;
  2671. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2672. }
  2673. return clone;
  2674. };
  2675. /**
  2676. * Check if the current value is a major value (for example when the step
  2677. * is DAY, a major value is each first day of the MONTH)
  2678. * @return {boolean} true if current date is major, else false.
  2679. */
  2680. TimeStep.prototype.isMajor = function() {
  2681. switch (this.scale) {
  2682. case TimeStep.SCALE.MILLISECOND:
  2683. return (this.current.getMilliseconds() == 0);
  2684. case TimeStep.SCALE.SECOND:
  2685. return (this.current.getSeconds() == 0);
  2686. case TimeStep.SCALE.MINUTE:
  2687. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2688. // Note: this is no bug. Major label is equal for both minute and hour scale
  2689. case TimeStep.SCALE.HOUR:
  2690. return (this.current.getHours() == 0);
  2691. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2692. case TimeStep.SCALE.DAY:
  2693. return (this.current.getDate() == 1);
  2694. case TimeStep.SCALE.MONTH:
  2695. return (this.current.getMonth() == 0);
  2696. case TimeStep.SCALE.YEAR:
  2697. return false;
  2698. default:
  2699. return false;
  2700. }
  2701. };
  2702. /**
  2703. * Returns formatted text for the minor axislabel, depending on the current
  2704. * date and the scale. For example when scale is MINUTE, the current time is
  2705. * formatted as "hh:mm".
  2706. * @param {Date} [date] custom date. if not provided, current date is taken
  2707. */
  2708. TimeStep.prototype.getLabelMinor = function(date) {
  2709. if (date == undefined) {
  2710. date = this.current;
  2711. }
  2712. switch (this.scale) {
  2713. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2714. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2715. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2716. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2717. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2718. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2719. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2720. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2721. default: return '';
  2722. }
  2723. };
  2724. /**
  2725. * Returns formatted text for the major axis label, depending on the current
  2726. * date and the scale. For example when scale is MINUTE, the major scale is
  2727. * hours, and the hour will be formatted as "hh".
  2728. * @param {Date} [date] custom date. if not provided, current date is taken
  2729. */
  2730. TimeStep.prototype.getLabelMajor = function(date) {
  2731. if (date == undefined) {
  2732. date = this.current;
  2733. }
  2734. //noinspection FallthroughInSwitchStatementJS
  2735. switch (this.scale) {
  2736. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2737. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2738. case TimeStep.SCALE.MINUTE:
  2739. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2740. case TimeStep.SCALE.WEEKDAY:
  2741. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2742. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2743. case TimeStep.SCALE.YEAR: return '';
  2744. default: return '';
  2745. }
  2746. };
  2747. /**
  2748. * @constructor Range
  2749. * A Range controls a numeric range with a start and end value.
  2750. * The Range adjusts the range based on mouse events or programmatic changes,
  2751. * and triggers events when the range is changing or has been changed.
  2752. * @param {RootPanel} root Root panel, used to subscribe to events
  2753. * @param {Panel} parent Parent panel, used to attach to the DOM
  2754. * @param {Object} [options] See description at Range.setOptions
  2755. */
  2756. function Range(root, parent, options) {
  2757. this.id = util.randomUUID();
  2758. this.start = null; // Number
  2759. this.end = null; // Number
  2760. this.root = root;
  2761. this.parent = parent;
  2762. this.options = options || {};
  2763. // drag listeners for dragging
  2764. this.root.on('dragstart', this._onDragStart.bind(this));
  2765. this.root.on('drag', this._onDrag.bind(this));
  2766. this.root.on('dragend', this._onDragEnd.bind(this));
  2767. // ignore dragging when holding
  2768. this.root.on('hold', this._onHold.bind(this));
  2769. // mouse wheel for zooming
  2770. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2771. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2772. // pinch to zoom
  2773. this.root.on('touch', this._onTouch.bind(this));
  2774. this.root.on('pinch', this._onPinch.bind(this));
  2775. this.setOptions(options);
  2776. }
  2777. // turn Range into an event emitter
  2778. Emitter(Range.prototype);
  2779. /**
  2780. * Set options for the range controller
  2781. * @param {Object} options Available options:
  2782. * {Number} min Minimum value for start
  2783. * {Number} max Maximum value for end
  2784. * {Number} zoomMin Set a minimum value for
  2785. * (end - start).
  2786. * {Number} zoomMax Set a maximum value for
  2787. * (end - start).
  2788. */
  2789. Range.prototype.setOptions = function (options) {
  2790. util.extend(this.options, options);
  2791. // re-apply range with new limitations
  2792. if (this.start !== null && this.end !== null) {
  2793. this.setRange(this.start, this.end);
  2794. }
  2795. };
  2796. /**
  2797. * Test whether direction has a valid value
  2798. * @param {String} direction 'horizontal' or 'vertical'
  2799. */
  2800. function validateDirection (direction) {
  2801. if (direction != 'horizontal' && direction != 'vertical') {
  2802. throw new TypeError('Unknown direction "' + direction + '". ' +
  2803. 'Choose "horizontal" or "vertical".');
  2804. }
  2805. }
  2806. /**
  2807. * Set a new start and end range
  2808. * @param {Number} [start]
  2809. * @param {Number} [end]
  2810. */
  2811. Range.prototype.setRange = function(start, end) {
  2812. var changed = this._applyRange(start, end);
  2813. if (changed) {
  2814. var params = {
  2815. start: new Date(this.start),
  2816. end: new Date(this.end)
  2817. };
  2818. this.emit('rangechange', params);
  2819. this.emit('rangechanged', params);
  2820. }
  2821. };
  2822. /**
  2823. * Set a new start and end range. This method is the same as setRange, but
  2824. * does not trigger a range change and range changed event, and it returns
  2825. * true when the range is changed
  2826. * @param {Number} [start]
  2827. * @param {Number} [end]
  2828. * @return {Boolean} changed
  2829. * @private
  2830. */
  2831. Range.prototype._applyRange = function(start, end) {
  2832. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2833. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2834. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2835. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2836. diff;
  2837. // check for valid number
  2838. if (isNaN(newStart) || newStart === null) {
  2839. throw new Error('Invalid start "' + start + '"');
  2840. }
  2841. if (isNaN(newEnd) || newEnd === null) {
  2842. throw new Error('Invalid end "' + end + '"');
  2843. }
  2844. // prevent start < end
  2845. if (newEnd < newStart) {
  2846. newEnd = newStart;
  2847. }
  2848. // prevent start < min
  2849. if (min !== null) {
  2850. if (newStart < min) {
  2851. diff = (min - newStart);
  2852. newStart += diff;
  2853. newEnd += diff;
  2854. // prevent end > max
  2855. if (max != null) {
  2856. if (newEnd > max) {
  2857. newEnd = max;
  2858. }
  2859. }
  2860. }
  2861. }
  2862. // prevent end > max
  2863. if (max !== null) {
  2864. if (newEnd > max) {
  2865. diff = (newEnd - max);
  2866. newStart -= diff;
  2867. newEnd -= diff;
  2868. // prevent start < min
  2869. if (min != null) {
  2870. if (newStart < min) {
  2871. newStart = min;
  2872. }
  2873. }
  2874. }
  2875. }
  2876. // prevent (end-start) < zoomMin
  2877. if (this.options.zoomMin !== null) {
  2878. var zoomMin = parseFloat(this.options.zoomMin);
  2879. if (zoomMin < 0) {
  2880. zoomMin = 0;
  2881. }
  2882. if ((newEnd - newStart) < zoomMin) {
  2883. if ((this.end - this.start) === zoomMin) {
  2884. // ignore this action, we are already zoomed to the minimum
  2885. newStart = this.start;
  2886. newEnd = this.end;
  2887. }
  2888. else {
  2889. // zoom to the minimum
  2890. diff = (zoomMin - (newEnd - newStart));
  2891. newStart -= diff / 2;
  2892. newEnd += diff / 2;
  2893. }
  2894. }
  2895. }
  2896. // prevent (end-start) > zoomMax
  2897. if (this.options.zoomMax !== null) {
  2898. var zoomMax = parseFloat(this.options.zoomMax);
  2899. if (zoomMax < 0) {
  2900. zoomMax = 0;
  2901. }
  2902. if ((newEnd - newStart) > zoomMax) {
  2903. if ((this.end - this.start) === zoomMax) {
  2904. // ignore this action, we are already zoomed to the maximum
  2905. newStart = this.start;
  2906. newEnd = this.end;
  2907. }
  2908. else {
  2909. // zoom to the maximum
  2910. diff = ((newEnd - newStart) - zoomMax);
  2911. newStart += diff / 2;
  2912. newEnd -= diff / 2;
  2913. }
  2914. }
  2915. }
  2916. var changed = (this.start != newStart || this.end != newEnd);
  2917. this.start = newStart;
  2918. this.end = newEnd;
  2919. return changed;
  2920. };
  2921. /**
  2922. * Retrieve the current range.
  2923. * @return {Object} An object with start and end properties
  2924. */
  2925. Range.prototype.getRange = function() {
  2926. return {
  2927. start: this.start,
  2928. end: this.end
  2929. };
  2930. };
  2931. /**
  2932. * Calculate the conversion offset and scale for current range, based on
  2933. * the provided width
  2934. * @param {Number} width
  2935. * @returns {{offset: number, scale: number}} conversion
  2936. */
  2937. Range.prototype.conversion = function (width) {
  2938. return Range.conversion(this.start, this.end, width);
  2939. };
  2940. /**
  2941. * Static method to calculate the conversion offset and scale for a range,
  2942. * based on the provided start, end, and width
  2943. * @param {Number} start
  2944. * @param {Number} end
  2945. * @param {Number} width
  2946. * @returns {{offset: number, scale: number}} conversion
  2947. */
  2948. Range.conversion = function (start, end, width) {
  2949. if (width != 0 && (end - start != 0)) {
  2950. return {
  2951. offset: start,
  2952. scale: width / (end - start)
  2953. }
  2954. }
  2955. else {
  2956. return {
  2957. offset: 0,
  2958. scale: 1
  2959. };
  2960. }
  2961. };
  2962. // global (private) object to store drag params
  2963. var touchParams = {};
  2964. /**
  2965. * Start dragging horizontally or vertically
  2966. * @param {Event} event
  2967. * @private
  2968. */
  2969. Range.prototype._onDragStart = function(event) {
  2970. // refuse to drag when we where pinching to prevent the timeline make a jump
  2971. // when releasing the fingers in opposite order from the touch screen
  2972. if (touchParams.ignore) return;
  2973. // TODO: reckon with option movable
  2974. touchParams.start = this.start;
  2975. touchParams.end = this.end;
  2976. var frame = this.parent.frame;
  2977. if (frame) {
  2978. frame.style.cursor = 'move';
  2979. }
  2980. };
  2981. /**
  2982. * Perform dragging operating.
  2983. * @param {Event} event
  2984. * @private
  2985. */
  2986. Range.prototype._onDrag = function (event) {
  2987. var direction = this.options.direction;
  2988. validateDirection(direction);
  2989. // TODO: reckon with option movable
  2990. // refuse to drag when we where pinching to prevent the timeline make a jump
  2991. // when releasing the fingers in opposite order from the touch screen
  2992. if (touchParams.ignore) return;
  2993. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2994. interval = (touchParams.end - touchParams.start),
  2995. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  2996. diffRange = -delta / width * interval;
  2997. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2998. this.emit('rangechange', {
  2999. start: new Date(this.start),
  3000. end: new Date(this.end)
  3001. });
  3002. };
  3003. /**
  3004. * Stop dragging operating.
  3005. * @param {event} event
  3006. * @private
  3007. */
  3008. Range.prototype._onDragEnd = function (event) {
  3009. // refuse to drag when we where pinching to prevent the timeline make a jump
  3010. // when releasing the fingers in opposite order from the touch screen
  3011. if (touchParams.ignore) return;
  3012. // TODO: reckon with option movable
  3013. if (this.parent.frame) {
  3014. this.parent.frame.style.cursor = 'auto';
  3015. }
  3016. // fire a rangechanged event
  3017. this.emit('rangechanged', {
  3018. start: new Date(this.start),
  3019. end: new Date(this.end)
  3020. });
  3021. };
  3022. /**
  3023. * Event handler for mouse wheel event, used to zoom
  3024. * Code from http://adomas.org/javascript-mouse-wheel/
  3025. * @param {Event} event
  3026. * @private
  3027. */
  3028. Range.prototype._onMouseWheel = function(event) {
  3029. // TODO: reckon with option zoomable
  3030. // retrieve delta
  3031. var delta = 0;
  3032. if (event.wheelDelta) { /* IE/Opera. */
  3033. delta = event.wheelDelta / 120;
  3034. } else if (event.detail) { /* Mozilla case. */
  3035. // In Mozilla, sign of delta is different than in IE.
  3036. // Also, delta is multiple of 3.
  3037. delta = -event.detail / 3;
  3038. }
  3039. // If delta is nonzero, handle it.
  3040. // Basically, delta is now positive if wheel was scrolled up,
  3041. // and negative, if wheel was scrolled down.
  3042. if (delta) {
  3043. // perform the zoom action. Delta is normally 1 or -1
  3044. // adjust a negative delta such that zooming in with delta 0.1
  3045. // equals zooming out with a delta -0.1
  3046. var scale;
  3047. if (delta < 0) {
  3048. scale = 1 - (delta / 5);
  3049. }
  3050. else {
  3051. scale = 1 / (1 + (delta / 5)) ;
  3052. }
  3053. // calculate center, the date to zoom around
  3054. var gesture = util.fakeGesture(this, event),
  3055. pointer = getPointer(gesture.center, this.parent.frame),
  3056. pointerDate = this._pointerToDate(pointer);
  3057. this.zoom(scale, pointerDate);
  3058. }
  3059. // Prevent default actions caused by mouse wheel
  3060. // (else the page and timeline both zoom and scroll)
  3061. event.preventDefault();
  3062. };
  3063. /**
  3064. * Start of a touch gesture
  3065. * @private
  3066. */
  3067. Range.prototype._onTouch = function (event) {
  3068. touchParams.start = this.start;
  3069. touchParams.end = this.end;
  3070. touchParams.ignore = false;
  3071. touchParams.center = null;
  3072. // don't move the range when dragging a selected event
  3073. // TODO: it's not so neat to have to know about the state of the ItemSet
  3074. var item = ItemSet.itemFromTarget(event);
  3075. if (item && item.selected && this.options.editable) {
  3076. touchParams.ignore = true;
  3077. }
  3078. };
  3079. /**
  3080. * On start of a hold gesture
  3081. * @private
  3082. */
  3083. Range.prototype._onHold = function () {
  3084. touchParams.ignore = true;
  3085. };
  3086. /**
  3087. * Handle pinch event
  3088. * @param {Event} event
  3089. * @private
  3090. */
  3091. Range.prototype._onPinch = function (event) {
  3092. var direction = this.options.direction;
  3093. touchParams.ignore = true;
  3094. // TODO: reckon with option zoomable
  3095. if (event.gesture.touches.length > 1) {
  3096. if (!touchParams.center) {
  3097. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3098. }
  3099. var scale = 1 / event.gesture.scale,
  3100. initDate = this._pointerToDate(touchParams.center),
  3101. center = getPointer(event.gesture.center, this.parent.frame),
  3102. date = this._pointerToDate(this.parent, center),
  3103. delta = date - initDate; // TODO: utilize delta
  3104. // calculate new start and end
  3105. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3106. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3107. // apply new range
  3108. this.setRange(newStart, newEnd);
  3109. }
  3110. };
  3111. /**
  3112. * Helper function to calculate the center date for zooming
  3113. * @param {{x: Number, y: Number}} pointer
  3114. * @return {number} date
  3115. * @private
  3116. */
  3117. Range.prototype._pointerToDate = function (pointer) {
  3118. var conversion;
  3119. var direction = this.options.direction;
  3120. validateDirection(direction);
  3121. if (direction == 'horizontal') {
  3122. var width = this.parent.width;
  3123. conversion = this.conversion(width);
  3124. return pointer.x / conversion.scale + conversion.offset;
  3125. }
  3126. else {
  3127. var height = this.parent.height;
  3128. conversion = this.conversion(height);
  3129. return pointer.y / conversion.scale + conversion.offset;
  3130. }
  3131. };
  3132. /**
  3133. * Get the pointer location relative to the location of the dom element
  3134. * @param {{pageX: Number, pageY: Number}} touch
  3135. * @param {Element} element HTML DOM element
  3136. * @return {{x: Number, y: Number}} pointer
  3137. * @private
  3138. */
  3139. function getPointer (touch, element) {
  3140. return {
  3141. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3142. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3143. };
  3144. }
  3145. /**
  3146. * Zoom the range the given scale in or out. Start and end date will
  3147. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3148. * date around which to zoom.
  3149. * For example, try scale = 0.9 or 1.1
  3150. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3151. * values below 1 will zoom in.
  3152. * @param {Number} [center] Value representing a date around which will
  3153. * be zoomed.
  3154. */
  3155. Range.prototype.zoom = function(scale, center) {
  3156. // if centerDate is not provided, take it half between start Date and end Date
  3157. if (center == null) {
  3158. center = (this.start + this.end) / 2;
  3159. }
  3160. // calculate new start and end
  3161. var newStart = center + (this.start - center) * scale;
  3162. var newEnd = center + (this.end - center) * scale;
  3163. this.setRange(newStart, newEnd);
  3164. };
  3165. /**
  3166. * Move the range with a given delta to the left or right. Start and end
  3167. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3168. * @param {Number} delta Moving amount. Positive value will move right,
  3169. * negative value will move left
  3170. */
  3171. Range.prototype.move = function(delta) {
  3172. // zoom start Date and end Date relative to the centerDate
  3173. var diff = (this.end - this.start);
  3174. // apply new values
  3175. var newStart = this.start + diff * delta;
  3176. var newEnd = this.end + diff * delta;
  3177. // TODO: reckon with min and max range
  3178. this.start = newStart;
  3179. this.end = newEnd;
  3180. };
  3181. /**
  3182. * Move the range to a new center point
  3183. * @param {Number} moveTo New center point of the range
  3184. */
  3185. Range.prototype.moveTo = function(moveTo) {
  3186. var center = (this.start + this.end) / 2;
  3187. var diff = center - moveTo;
  3188. // calculate new start and end
  3189. var newStart = this.start - diff;
  3190. var newEnd = this.end - diff;
  3191. this.setRange(newStart, newEnd);
  3192. };
  3193. /**
  3194. * Prototype for visual components
  3195. */
  3196. function Component () {
  3197. this.id = null;
  3198. this.parent = null;
  3199. this.childs = null;
  3200. this.options = null;
  3201. this.top = 0;
  3202. this.left = 0;
  3203. this.width = 0;
  3204. this.height = 0;
  3205. }
  3206. // Turn the Component into an event emitter
  3207. Emitter(Component.prototype);
  3208. /**
  3209. * Set parameters for the frame. Parameters will be merged in current parameter
  3210. * set.
  3211. * @param {Object} options Available parameters:
  3212. * {String | function} [className]
  3213. * {String | Number | function} [left]
  3214. * {String | Number | function} [top]
  3215. * {String | Number | function} [width]
  3216. * {String | Number | function} [height]
  3217. */
  3218. Component.prototype.setOptions = function setOptions(options) {
  3219. if (options) {
  3220. util.extend(this.options, options);
  3221. this.repaint();
  3222. }
  3223. };
  3224. /**
  3225. * Get an option value by name
  3226. * The function will first check this.options object, and else will check
  3227. * this.defaultOptions.
  3228. * @param {String} name
  3229. * @return {*} value
  3230. */
  3231. Component.prototype.getOption = function getOption(name) {
  3232. var value;
  3233. if (this.options) {
  3234. value = this.options[name];
  3235. }
  3236. if (value === undefined && this.defaultOptions) {
  3237. value = this.defaultOptions[name];
  3238. }
  3239. return value;
  3240. };
  3241. /**
  3242. * Get the frame element of the component, the outer HTML DOM element.
  3243. * @returns {HTMLElement | null} frame
  3244. */
  3245. Component.prototype.getFrame = function getFrame() {
  3246. // should be implemented by the component
  3247. return null;
  3248. };
  3249. /**
  3250. * Repaint the component
  3251. * @return {boolean} Returns true if the component is resized
  3252. */
  3253. Component.prototype.repaint = function repaint() {
  3254. // should be implemented by the component
  3255. return false;
  3256. };
  3257. /**
  3258. * Test whether the component is resized since the last time _isResized() was
  3259. * called.
  3260. * @return {Boolean} Returns true if the component is resized
  3261. * @protected
  3262. */
  3263. Component.prototype._isResized = function _isResized() {
  3264. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3265. this._previousWidth = this.width;
  3266. this._previousHeight = this.height;
  3267. return resized;
  3268. };
  3269. /**
  3270. * A panel can contain components
  3271. * @param {Object} [options] Available parameters:
  3272. * {String | Number | function} [left]
  3273. * {String | Number | function} [top]
  3274. * {String | Number | function} [width]
  3275. * {String | Number | function} [height]
  3276. * {String | function} [className]
  3277. * @constructor Panel
  3278. * @extends Component
  3279. */
  3280. function Panel(options) {
  3281. this.id = util.randomUUID();
  3282. this.parent = null;
  3283. this.childs = [];
  3284. this.options = options || {};
  3285. // create frame
  3286. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3287. }
  3288. Panel.prototype = new Component();
  3289. /**
  3290. * Set options. Will extend the current options.
  3291. * @param {Object} [options] Available parameters:
  3292. * {String | function} [className]
  3293. * {String | Number | function} [left]
  3294. * {String | Number | function} [top]
  3295. * {String | Number | function} [width]
  3296. * {String | Number | function} [height]
  3297. */
  3298. Panel.prototype.setOptions = Component.prototype.setOptions;
  3299. /**
  3300. * Get the outer frame of the panel
  3301. * @returns {HTMLElement} frame
  3302. */
  3303. Panel.prototype.getFrame = function () {
  3304. return this.frame;
  3305. };
  3306. /**
  3307. * Append a child to the panel
  3308. * @param {Component} child
  3309. */
  3310. Panel.prototype.appendChild = function (child) {
  3311. this.childs.push(child);
  3312. child.parent = this;
  3313. // attach to the DOM
  3314. var frame = child.getFrame();
  3315. if (frame) {
  3316. if (frame.parentNode) {
  3317. frame.parentNode.removeChild(frame);
  3318. }
  3319. this.frame.appendChild(frame);
  3320. }
  3321. };
  3322. /**
  3323. * Insert a child to the panel
  3324. * @param {Component} child
  3325. * @param {Component} beforeChild
  3326. */
  3327. Panel.prototype.insertBefore = function (child, beforeChild) {
  3328. var index = this.childs.indexOf(beforeChild);
  3329. if (index != -1) {
  3330. this.childs.splice(index, 0, child);
  3331. child.parent = this;
  3332. // attach to the DOM
  3333. var frame = child.getFrame();
  3334. if (frame) {
  3335. if (frame.parentNode) {
  3336. frame.parentNode.removeChild(frame);
  3337. }
  3338. var beforeFrame = beforeChild.getFrame();
  3339. if (beforeFrame) {
  3340. this.frame.insertBefore(frame, beforeFrame);
  3341. }
  3342. else {
  3343. this.frame.appendChild(frame);
  3344. }
  3345. }
  3346. }
  3347. };
  3348. /**
  3349. * Remove a child from the panel
  3350. * @param {Component} child
  3351. */
  3352. Panel.prototype.removeChild = function (child) {
  3353. var index = this.childs.indexOf(child);
  3354. if (index != -1) {
  3355. this.childs.splice(index, 1);
  3356. child.parent = null;
  3357. // remove from the DOM
  3358. var frame = child.getFrame();
  3359. if (frame && frame.parentNode) {
  3360. this.frame.removeChild(frame);
  3361. }
  3362. }
  3363. };
  3364. /**
  3365. * Test whether the panel contains given child
  3366. * @param {Component} child
  3367. */
  3368. Panel.prototype.hasChild = function (child) {
  3369. var index = this.childs.indexOf(child);
  3370. return (index != -1);
  3371. };
  3372. /**
  3373. * Repaint the component
  3374. * @return {boolean} Returns true if the component was resized since previous repaint
  3375. */
  3376. Panel.prototype.repaint = function () {
  3377. var asString = util.option.asString,
  3378. options = this.options,
  3379. frame = this.getFrame();
  3380. // update className
  3381. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3382. // repaint the child components
  3383. var childsResized = this._repaintChilds();
  3384. // update frame size
  3385. this._updateSize();
  3386. return this._isResized() || childsResized;
  3387. };
  3388. /**
  3389. * Repaint all childs of the panel
  3390. * @return {boolean} Returns true if the component is resized
  3391. * @private
  3392. */
  3393. Panel.prototype._repaintChilds = function () {
  3394. var resized = false;
  3395. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3396. resized = this.childs[i].repaint() || resized;
  3397. }
  3398. return resized;
  3399. };
  3400. /**
  3401. * Apply the size from options to the panel, and recalculate it's actual size.
  3402. * @private
  3403. */
  3404. Panel.prototype._updateSize = function () {
  3405. // apply size
  3406. this.frame.style.top = util.option.asSize(this.options.top);
  3407. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3408. this.frame.style.left = util.option.asSize(this.options.left);
  3409. this.frame.style.right = util.option.asSize(this.options.right);
  3410. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3411. this.frame.style.height = util.option.asSize(this.options.height, '');
  3412. // get actual size
  3413. this.top = this.frame.offsetTop;
  3414. this.left = this.frame.offsetLeft;
  3415. this.width = this.frame.offsetWidth;
  3416. this.height = this.frame.offsetHeight;
  3417. };
  3418. /**
  3419. * A root panel can hold components. The root panel must be initialized with
  3420. * a DOM element as container.
  3421. * @param {HTMLElement} container
  3422. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3423. * @constructor RootPanel
  3424. * @extends Panel
  3425. */
  3426. function RootPanel(container, options) {
  3427. this.id = util.randomUUID();
  3428. this.container = container;
  3429. this.options = options || {};
  3430. this.defaultOptions = {
  3431. autoResize: true
  3432. };
  3433. // create the HTML DOM
  3434. this._create();
  3435. // attach the root panel to the provided container
  3436. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3437. this.container.appendChild(this.getFrame());
  3438. this._initWatch();
  3439. }
  3440. RootPanel.prototype = new Panel();
  3441. /**
  3442. * Create the HTML DOM for the root panel
  3443. */
  3444. RootPanel.prototype._create = function _create() {
  3445. // create frame
  3446. this.frame = document.createElement('div');
  3447. // create event listeners for all interesting events, these events will be
  3448. // emitted via emitter
  3449. this.hammer = Hammer(this.frame, {
  3450. prevent_default: true
  3451. });
  3452. this.listeners = {};
  3453. var me = this;
  3454. var events = [
  3455. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3456. 'dragstart', 'drag', 'dragend',
  3457. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3458. ];
  3459. events.forEach(function (event) {
  3460. var listener = function () {
  3461. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3462. me.emit.apply(me, args);
  3463. };
  3464. me.hammer.on(event, listener);
  3465. me.listeners[event] = listener;
  3466. });
  3467. };
  3468. /**
  3469. * Set options. Will extend the current options.
  3470. * @param {Object} [options] Available parameters:
  3471. * {String | function} [className]
  3472. * {String | Number | function} [left]
  3473. * {String | Number | function} [top]
  3474. * {String | Number | function} [width]
  3475. * {String | Number | function} [height]
  3476. * {Boolean | function} [autoResize]
  3477. */
  3478. RootPanel.prototype.setOptions = function setOptions(options) {
  3479. if (options) {
  3480. util.extend(this.options, options);
  3481. this.repaint();
  3482. this._initWatch();
  3483. }
  3484. };
  3485. /**
  3486. * Get the frame of the root panel
  3487. */
  3488. RootPanel.prototype.getFrame = function getFrame() {
  3489. return this.frame;
  3490. };
  3491. /**
  3492. * Repaint the root panel
  3493. */
  3494. RootPanel.prototype.repaint = function repaint() {
  3495. // update class name
  3496. var options = this.options;
  3497. var editable = options.editable.updateTime || options.editable.updateGroup;
  3498. var className = 'vis timeline rootpanel ' + options.orientation + (editable ? ' editable' : '');
  3499. if (options.className) className += ' ' + util.option.asString(className);
  3500. this.frame.className = className;
  3501. // repaint the child components
  3502. var childsResized = this._repaintChilds();
  3503. // update frame size
  3504. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3505. this.frame.style.minHeight = util.option.asSize(this.options.minHeight, '');
  3506. this._updateSize();
  3507. // if the root panel or any of its childs is resized, repaint again,
  3508. // as other components may need to be resized accordingly
  3509. var resized = this._isResized() || childsResized;
  3510. if (resized) {
  3511. setTimeout(this.repaint.bind(this), 0);
  3512. }
  3513. };
  3514. /**
  3515. * Initialize watching when option autoResize is true
  3516. * @private
  3517. */
  3518. RootPanel.prototype._initWatch = function _initWatch() {
  3519. var autoResize = this.getOption('autoResize');
  3520. if (autoResize) {
  3521. this._watch();
  3522. }
  3523. else {
  3524. this._unwatch();
  3525. }
  3526. };
  3527. /**
  3528. * Watch for changes in the size of the frame. On resize, the Panel will
  3529. * automatically redraw itself.
  3530. * @private
  3531. */
  3532. RootPanel.prototype._watch = function _watch() {
  3533. var me = this;
  3534. this._unwatch();
  3535. var checkSize = function checkSize() {
  3536. var autoResize = me.getOption('autoResize');
  3537. if (!autoResize) {
  3538. // stop watching when the option autoResize is changed to false
  3539. me._unwatch();
  3540. return;
  3541. }
  3542. if (me.frame) {
  3543. // check whether the frame is resized
  3544. if ((me.frame.clientWidth != me.lastWidth) ||
  3545. (me.frame.clientHeight != me.lastHeight)) {
  3546. me.lastWidth = me.frame.clientWidth;
  3547. me.lastHeight = me.frame.clientHeight;
  3548. me.repaint();
  3549. // TODO: emit a resize event instead?
  3550. }
  3551. }
  3552. };
  3553. // TODO: automatically cleanup the event listener when the frame is deleted
  3554. util.addEventListener(window, 'resize', checkSize);
  3555. this.watchTimer = setInterval(checkSize, 1000);
  3556. };
  3557. /**
  3558. * Stop watching for a resize of the frame.
  3559. * @private
  3560. */
  3561. RootPanel.prototype._unwatch = function _unwatch() {
  3562. if (this.watchTimer) {
  3563. clearInterval(this.watchTimer);
  3564. this.watchTimer = undefined;
  3565. }
  3566. // TODO: remove event listener on window.resize
  3567. };
  3568. /**
  3569. * A horizontal time axis
  3570. * @param {Object} [options] See TimeAxis.setOptions for the available
  3571. * options.
  3572. * @constructor TimeAxis
  3573. * @extends Component
  3574. */
  3575. function TimeAxis (options) {
  3576. this.id = util.randomUUID();
  3577. this.dom = {
  3578. majorLines: [],
  3579. majorTexts: [],
  3580. minorLines: [],
  3581. minorTexts: [],
  3582. redundant: {
  3583. majorLines: [],
  3584. majorTexts: [],
  3585. minorLines: [],
  3586. minorTexts: []
  3587. }
  3588. };
  3589. this.props = {
  3590. range: {
  3591. start: 0,
  3592. end: 0,
  3593. minimumStep: 0
  3594. },
  3595. lineTop: 0
  3596. };
  3597. this.options = options || {};
  3598. this.defaultOptions = {
  3599. orientation: 'bottom', // supported: 'top', 'bottom'
  3600. // TODO: implement timeaxis orientations 'left' and 'right'
  3601. showMinorLabels: true,
  3602. showMajorLabels: true
  3603. };
  3604. this.range = null;
  3605. // create the HTML DOM
  3606. this._create();
  3607. }
  3608. TimeAxis.prototype = new Component();
  3609. // TODO: comment options
  3610. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3611. /**
  3612. * Create the HTML DOM for the TimeAxis
  3613. */
  3614. TimeAxis.prototype._create = function _create() {
  3615. this.frame = document.createElement('div');
  3616. };
  3617. /**
  3618. * Set a range (start and end)
  3619. * @param {Range | Object} range A Range or an object containing start and end.
  3620. */
  3621. TimeAxis.prototype.setRange = function (range) {
  3622. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3623. throw new TypeError('Range must be an instance of Range, ' +
  3624. 'or an object containing start and end.');
  3625. }
  3626. this.range = range;
  3627. };
  3628. /**
  3629. * Get the outer frame of the time axis
  3630. * @return {HTMLElement} frame
  3631. */
  3632. TimeAxis.prototype.getFrame = function getFrame() {
  3633. return this.frame;
  3634. };
  3635. /**
  3636. * Repaint the component
  3637. * @return {boolean} Returns true if the component is resized
  3638. */
  3639. TimeAxis.prototype.repaint = function () {
  3640. var asSize = util.option.asSize,
  3641. options = this.options,
  3642. props = this.props,
  3643. frame = this.frame;
  3644. // update classname
  3645. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3646. var parent = frame.parentNode;
  3647. if (parent) {
  3648. // calculate character width and height
  3649. this._calculateCharSize();
  3650. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3651. var orientation = this.getOption('orientation'),
  3652. showMinorLabels = this.getOption('showMinorLabels'),
  3653. showMajorLabels = this.getOption('showMajorLabels');
  3654. // determine the width and height of the elemens for the axis
  3655. var parentHeight = this.parent.height;
  3656. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3657. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3658. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3659. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3660. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3661. props.minorLineWidth = 1; // TODO: really calculate width
  3662. props.majorLineHeight = parentHeight + this.height;
  3663. props.majorLineWidth = 1; // TODO: really calculate width
  3664. // take frame offline while updating (is almost twice as fast)
  3665. var beforeChild = frame.nextSibling;
  3666. parent.removeChild(frame);
  3667. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3668. if (orientation == 'top') {
  3669. frame.style.top = '0';
  3670. frame.style.left = '0';
  3671. frame.style.bottom = '';
  3672. frame.style.width = asSize(options.width, '100%');
  3673. frame.style.height = this.height + 'px';
  3674. }
  3675. else { // bottom
  3676. frame.style.top = '';
  3677. frame.style.bottom = '0';
  3678. frame.style.left = '0';
  3679. frame.style.width = asSize(options.width, '100%');
  3680. frame.style.height = this.height + 'px';
  3681. }
  3682. this._repaintLabels();
  3683. this._repaintLine();
  3684. // put frame online again
  3685. if (beforeChild) {
  3686. parent.insertBefore(frame, beforeChild);
  3687. }
  3688. else {
  3689. parent.appendChild(frame)
  3690. }
  3691. }
  3692. return this._isResized();
  3693. };
  3694. /**
  3695. * Repaint major and minor text labels and vertical grid lines
  3696. * @private
  3697. */
  3698. TimeAxis.prototype._repaintLabels = function () {
  3699. var orientation = this.getOption('orientation');
  3700. // calculate range and step (step such that we have space for 7 characters per label)
  3701. var start = util.convert(this.range.start, 'Number'),
  3702. end = util.convert(this.range.end, 'Number'),
  3703. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  3704. -this.options.toTime(0).valueOf();
  3705. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3706. this.step = step;
  3707. // Move all DOM elements to a "redundant" list, where they
  3708. // can be picked for re-use, and clear the lists with lines and texts.
  3709. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3710. var dom = this.dom;
  3711. dom.redundant.majorLines = dom.majorLines;
  3712. dom.redundant.majorTexts = dom.majorTexts;
  3713. dom.redundant.minorLines = dom.minorLines;
  3714. dom.redundant.minorTexts = dom.minorTexts;
  3715. dom.majorLines = [];
  3716. dom.majorTexts = [];
  3717. dom.minorLines = [];
  3718. dom.minorTexts = [];
  3719. step.first();
  3720. var xFirstMajorLabel = undefined;
  3721. var max = 0;
  3722. while (step.hasNext() && max < 1000) {
  3723. max++;
  3724. var cur = step.getCurrent(),
  3725. x = this.options.toScreen(cur),
  3726. isMajor = step.isMajor();
  3727. // TODO: lines must have a width, such that we can create css backgrounds
  3728. if (this.getOption('showMinorLabels')) {
  3729. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3730. }
  3731. if (isMajor && this.getOption('showMajorLabels')) {
  3732. if (x > 0) {
  3733. if (xFirstMajorLabel == undefined) {
  3734. xFirstMajorLabel = x;
  3735. }
  3736. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3737. }
  3738. this._repaintMajorLine(x, orientation);
  3739. }
  3740. else {
  3741. this._repaintMinorLine(x, orientation);
  3742. }
  3743. step.next();
  3744. }
  3745. // create a major label on the left when needed
  3746. if (this.getOption('showMajorLabels')) {
  3747. var leftTime = this.options.toTime(0),
  3748. leftText = step.getLabelMajor(leftTime),
  3749. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3750. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3751. this._repaintMajorText(0, leftText, orientation);
  3752. }
  3753. }
  3754. // Cleanup leftover DOM elements from the redundant list
  3755. util.forEach(this.dom.redundant, function (arr) {
  3756. while (arr.length) {
  3757. var elem = arr.pop();
  3758. if (elem && elem.parentNode) {
  3759. elem.parentNode.removeChild(elem);
  3760. }
  3761. }
  3762. });
  3763. };
  3764. /**
  3765. * Create a minor label for the axis at position x
  3766. * @param {Number} x
  3767. * @param {String} text
  3768. * @param {String} orientation "top" or "bottom" (default)
  3769. * @private
  3770. */
  3771. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3772. // reuse redundant label
  3773. var label = this.dom.redundant.minorTexts.shift();
  3774. if (!label) {
  3775. // create new label
  3776. var content = document.createTextNode('');
  3777. label = document.createElement('div');
  3778. label.appendChild(content);
  3779. label.className = 'text minor';
  3780. this.frame.appendChild(label);
  3781. }
  3782. this.dom.minorTexts.push(label);
  3783. label.childNodes[0].nodeValue = text;
  3784. if (orientation == 'top') {
  3785. label.style.top = this.props.majorLabelHeight + 'px';
  3786. label.style.bottom = '';
  3787. }
  3788. else {
  3789. label.style.top = '';
  3790. label.style.bottom = this.props.majorLabelHeight + 'px';
  3791. }
  3792. label.style.left = x + 'px';
  3793. //label.title = title; // TODO: this is a heavy operation
  3794. };
  3795. /**
  3796. * Create a Major label for the axis at position x
  3797. * @param {Number} x
  3798. * @param {String} text
  3799. * @param {String} orientation "top" or "bottom" (default)
  3800. * @private
  3801. */
  3802. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3803. // reuse redundant label
  3804. var label = this.dom.redundant.majorTexts.shift();
  3805. if (!label) {
  3806. // create label
  3807. var content = document.createTextNode(text);
  3808. label = document.createElement('div');
  3809. label.className = 'text major';
  3810. label.appendChild(content);
  3811. this.frame.appendChild(label);
  3812. }
  3813. this.dom.majorTexts.push(label);
  3814. label.childNodes[0].nodeValue = text;
  3815. //label.title = title; // TODO: this is a heavy operation
  3816. if (orientation == 'top') {
  3817. label.style.top = '0px';
  3818. label.style.bottom = '';
  3819. }
  3820. else {
  3821. label.style.top = '';
  3822. label.style.bottom = '0px';
  3823. }
  3824. label.style.left = x + 'px';
  3825. };
  3826. /**
  3827. * Create a minor line for the axis at position x
  3828. * @param {Number} x
  3829. * @param {String} orientation "top" or "bottom" (default)
  3830. * @private
  3831. */
  3832. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3833. // reuse redundant line
  3834. var line = this.dom.redundant.minorLines.shift();
  3835. if (!line) {
  3836. // create vertical line
  3837. line = document.createElement('div');
  3838. line.className = 'grid vertical minor';
  3839. this.frame.appendChild(line);
  3840. }
  3841. this.dom.minorLines.push(line);
  3842. var props = this.props;
  3843. if (orientation == 'top') {
  3844. line.style.top = this.props.majorLabelHeight + 'px';
  3845. line.style.bottom = '';
  3846. }
  3847. else {
  3848. line.style.top = '';
  3849. line.style.bottom = this.props.majorLabelHeight + 'px';
  3850. }
  3851. line.style.height = props.minorLineHeight + 'px';
  3852. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3853. };
  3854. /**
  3855. * Create a Major line for the axis at position x
  3856. * @param {Number} x
  3857. * @param {String} orientation "top" or "bottom" (default)
  3858. * @private
  3859. */
  3860. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3861. // reuse redundant line
  3862. var line = this.dom.redundant.majorLines.shift();
  3863. if (!line) {
  3864. // create vertical line
  3865. line = document.createElement('DIV');
  3866. line.className = 'grid vertical major';
  3867. this.frame.appendChild(line);
  3868. }
  3869. this.dom.majorLines.push(line);
  3870. var props = this.props;
  3871. if (orientation == 'top') {
  3872. line.style.top = '0px';
  3873. line.style.bottom = '';
  3874. }
  3875. else {
  3876. line.style.top = '';
  3877. line.style.bottom = '0px';
  3878. }
  3879. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3880. line.style.height = props.majorLineHeight + 'px';
  3881. };
  3882. /**
  3883. * Repaint the horizontal line for the axis
  3884. * @private
  3885. */
  3886. TimeAxis.prototype._repaintLine = function() {
  3887. var line = this.dom.line,
  3888. frame = this.frame,
  3889. orientation = this.getOption('orientation');
  3890. // line before all axis elements
  3891. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3892. if (line) {
  3893. // put this line at the end of all childs
  3894. frame.removeChild(line);
  3895. frame.appendChild(line);
  3896. }
  3897. else {
  3898. // create the axis line
  3899. line = document.createElement('div');
  3900. line.className = 'grid horizontal major';
  3901. frame.appendChild(line);
  3902. this.dom.line = line;
  3903. }
  3904. if (orientation == 'top') {
  3905. line.style.top = this.height + 'px';
  3906. line.style.bottom = '';
  3907. }
  3908. else {
  3909. line.style.top = '';
  3910. line.style.bottom = this.height + 'px';
  3911. }
  3912. }
  3913. else {
  3914. if (line && line.parentNode) {
  3915. line.parentNode.removeChild(line);
  3916. delete this.dom.line;
  3917. }
  3918. }
  3919. };
  3920. /**
  3921. * Determine the size of text on the axis (both major and minor axis).
  3922. * The size is calculated only once and then cached in this.props.
  3923. * @private
  3924. */
  3925. TimeAxis.prototype._calculateCharSize = function () {
  3926. // Note: We calculate char size with every repaint. Size may change, for
  3927. // example when any of the timelines parents had display:none for example.
  3928. // determine the char width and height on the minor axis
  3929. if (!this.dom.measureCharMinor) {
  3930. this.dom.measureCharMinor = document.createElement('DIV');
  3931. this.dom.measureCharMinor.className = 'text minor measure';
  3932. this.dom.measureCharMinor.style.position = 'absolute';
  3933. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  3934. this.frame.appendChild(this.dom.measureCharMinor);
  3935. }
  3936. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  3937. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  3938. // determine the char width and height on the major axis
  3939. if (!this.dom.measureCharMajor) {
  3940. this.dom.measureCharMajor = document.createElement('DIV');
  3941. this.dom.measureCharMajor.className = 'text minor measure';
  3942. this.dom.measureCharMajor.style.position = 'absolute';
  3943. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  3944. this.frame.appendChild(this.dom.measureCharMajor);
  3945. }
  3946. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  3947. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  3948. };
  3949. /**
  3950. * Snap a date to a rounded value.
  3951. * The snap intervals are dependent on the current scale and step.
  3952. * @param {Date} date the date to be snapped.
  3953. * @return {Date} snappedDate
  3954. */
  3955. TimeAxis.prototype.snap = function snap (date) {
  3956. return this.step.snap(date);
  3957. };
  3958. /**
  3959. * A current time bar
  3960. * @param {Range} range
  3961. * @param {Object} [options] Available parameters:
  3962. * {Boolean} [showCurrentTime]
  3963. * @constructor CurrentTime
  3964. * @extends Component
  3965. */
  3966. function CurrentTime (range, options) {
  3967. this.id = util.randomUUID();
  3968. this.range = range;
  3969. this.options = options || {};
  3970. this.defaultOptions = {
  3971. showCurrentTime: false
  3972. };
  3973. this._create();
  3974. }
  3975. CurrentTime.prototype = new Component();
  3976. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3977. /**
  3978. * Create the HTML DOM for the current time bar
  3979. * @private
  3980. */
  3981. CurrentTime.prototype._create = function _create () {
  3982. var bar = document.createElement('div');
  3983. bar.className = 'currenttime';
  3984. bar.style.position = 'absolute';
  3985. bar.style.top = '0px';
  3986. bar.style.height = '100%';
  3987. this.bar = bar;
  3988. };
  3989. /**
  3990. * Get the frame element of the current time bar
  3991. * @returns {HTMLElement} frame
  3992. */
  3993. CurrentTime.prototype.getFrame = function getFrame() {
  3994. return this.bar;
  3995. };
  3996. /**
  3997. * Repaint the component
  3998. * @return {boolean} Returns true if the component is resized
  3999. */
  4000. CurrentTime.prototype.repaint = function repaint() {
  4001. var parent = this.parent;
  4002. var now = new Date();
  4003. var x = this.options.toScreen(now);
  4004. this.bar.style.left = x + 'px';
  4005. this.bar.title = 'Current time: ' + now;
  4006. return false;
  4007. };
  4008. /**
  4009. * Start auto refreshing the current time bar
  4010. */
  4011. CurrentTime.prototype.start = function start() {
  4012. var me = this;
  4013. function update () {
  4014. me.stop();
  4015. // determine interval to refresh
  4016. var scale = me.range.conversion(me.parent.width).scale;
  4017. var interval = 1 / scale / 10;
  4018. if (interval < 30) interval = 30;
  4019. if (interval > 1000) interval = 1000;
  4020. me.repaint();
  4021. // start a timer to adjust for the new time
  4022. me.currentTimeTimer = setTimeout(update, interval);
  4023. }
  4024. update();
  4025. };
  4026. /**
  4027. * Stop auto refreshing the current time bar
  4028. */
  4029. CurrentTime.prototype.stop = function stop() {
  4030. if (this.currentTimeTimer !== undefined) {
  4031. clearTimeout(this.currentTimeTimer);
  4032. delete this.currentTimeTimer;
  4033. }
  4034. };
  4035. /**
  4036. * A custom time bar
  4037. * @param {Object} [options] Available parameters:
  4038. * {Boolean} [showCustomTime]
  4039. * @constructor CustomTime
  4040. * @extends Component
  4041. */
  4042. function CustomTime (options) {
  4043. this.id = util.randomUUID();
  4044. this.options = options || {};
  4045. this.defaultOptions = {
  4046. showCustomTime: false
  4047. };
  4048. this.customTime = new Date();
  4049. this.eventParams = {}; // stores state parameters while dragging the bar
  4050. // create the DOM
  4051. this._create();
  4052. }
  4053. CustomTime.prototype = new Component();
  4054. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4055. /**
  4056. * Create the DOM for the custom time
  4057. * @private
  4058. */
  4059. CustomTime.prototype._create = function _create () {
  4060. var bar = document.createElement('div');
  4061. bar.className = 'customtime';
  4062. bar.style.position = 'absolute';
  4063. bar.style.top = '0px';
  4064. bar.style.height = '100%';
  4065. this.bar = bar;
  4066. var drag = document.createElement('div');
  4067. drag.style.position = 'relative';
  4068. drag.style.top = '0px';
  4069. drag.style.left = '-10px';
  4070. drag.style.height = '100%';
  4071. drag.style.width = '20px';
  4072. bar.appendChild(drag);
  4073. // attach event listeners
  4074. this.hammer = Hammer(bar, {
  4075. prevent_default: true
  4076. });
  4077. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4078. this.hammer.on('drag', this._onDrag.bind(this));
  4079. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4080. };
  4081. /**
  4082. * Get the frame element of the custom time bar
  4083. * @returns {HTMLElement} frame
  4084. */
  4085. CustomTime.prototype.getFrame = function getFrame() {
  4086. return this.bar;
  4087. };
  4088. /**
  4089. * Repaint the component
  4090. * @return {boolean} Returns true if the component is resized
  4091. */
  4092. CustomTime.prototype.repaint = function () {
  4093. var x = this.options.toScreen(this.customTime);
  4094. this.bar.style.left = x + 'px';
  4095. this.bar.title = 'Time: ' + this.customTime;
  4096. return false;
  4097. };
  4098. /**
  4099. * Set custom time.
  4100. * @param {Date} time
  4101. */
  4102. CustomTime.prototype.setCustomTime = function(time) {
  4103. this.customTime = new Date(time.valueOf());
  4104. this.repaint();
  4105. };
  4106. /**
  4107. * Retrieve the current custom time.
  4108. * @return {Date} customTime
  4109. */
  4110. CustomTime.prototype.getCustomTime = function() {
  4111. return new Date(this.customTime.valueOf());
  4112. };
  4113. /**
  4114. * Start moving horizontally
  4115. * @param {Event} event
  4116. * @private
  4117. */
  4118. CustomTime.prototype._onDragStart = function(event) {
  4119. this.eventParams.dragging = true;
  4120. this.eventParams.customTime = this.customTime;
  4121. event.stopPropagation();
  4122. event.preventDefault();
  4123. };
  4124. /**
  4125. * Perform moving operating.
  4126. * @param {Event} event
  4127. * @private
  4128. */
  4129. CustomTime.prototype._onDrag = function (event) {
  4130. if (!this.eventParams.dragging) return;
  4131. var deltaX = event.gesture.deltaX,
  4132. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4133. time = this.options.toTime(x);
  4134. this.setCustomTime(time);
  4135. // fire a timechange event
  4136. this.emit('timechange', {
  4137. time: new Date(this.customTime.valueOf())
  4138. });
  4139. event.stopPropagation();
  4140. event.preventDefault();
  4141. };
  4142. /**
  4143. * Stop moving operating.
  4144. * @param {event} event
  4145. * @private
  4146. */
  4147. CustomTime.prototype._onDragEnd = function (event) {
  4148. if (!this.eventParams.dragging) return;
  4149. // fire a timechanged event
  4150. this.emit('timechanged', {
  4151. time: new Date(this.customTime.valueOf())
  4152. });
  4153. event.stopPropagation();
  4154. event.preventDefault();
  4155. };
  4156. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4157. /**
  4158. * An ItemSet holds a set of items and ranges which can be displayed in a
  4159. * range. The width is determined by the parent of the ItemSet, and the height
  4160. * is determined by the size of the items.
  4161. * @param {Panel} backgroundPanel Panel which can be used to display the
  4162. * vertical lines of box items.
  4163. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4164. * can be displayed.
  4165. * @param {Panel} sidePanel Left side panel holding labels
  4166. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4167. * @constructor ItemSet
  4168. * @extends Panel
  4169. */
  4170. function ItemSet(backgroundPanel, axisPanel, sidePanel, options) {
  4171. this.id = util.randomUUID();
  4172. // one options object is shared by this itemset and all its items
  4173. this.options = options || {};
  4174. this.backgroundPanel = backgroundPanel;
  4175. this.axisPanel = axisPanel;
  4176. this.sidePanel = sidePanel;
  4177. this.itemOptions = Object.create(this.options);
  4178. this.dom = {};
  4179. this.hammer = null;
  4180. var me = this;
  4181. this.itemsData = null; // DataSet
  4182. this.groupsData = null; // DataSet
  4183. this.range = null; // Range or Object {start: number, end: number}
  4184. // listeners for the DataSet of the items
  4185. this.itemListeners = {
  4186. 'add': function (event, params, senderId) {
  4187. if (senderId != me.id) me._onAdd(params.items);
  4188. },
  4189. 'update': function (event, params, senderId) {
  4190. if (senderId != me.id) me._onUpdate(params.items);
  4191. },
  4192. 'remove': function (event, params, senderId) {
  4193. if (senderId != me.id) me._onRemove(params.items);
  4194. }
  4195. };
  4196. // listeners for the DataSet of the groups
  4197. this.groupListeners = {
  4198. 'add': function (event, params, senderId) {
  4199. if (senderId != me.id) me._onAddGroups(params.items);
  4200. },
  4201. 'update': function (event, params, senderId) {
  4202. if (senderId != me.id) me._onUpdateGroups(params.items);
  4203. },
  4204. 'remove': function (event, params, senderId) {
  4205. if (senderId != me.id) me._onRemoveGroups(params.items);
  4206. }
  4207. };
  4208. this.items = {}; // object with an Item for every data item
  4209. this.groups = {}; // Group object for every group
  4210. this.groupIds = [];
  4211. this.selection = []; // list with the ids of all selected nodes
  4212. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4213. this.touchParams = {}; // stores properties while dragging
  4214. // create the HTML DOM
  4215. this._create();
  4216. }
  4217. ItemSet.prototype = new Panel();
  4218. // available item types will be registered here
  4219. ItemSet.types = {
  4220. box: ItemBox,
  4221. range: ItemRange,
  4222. rangeoverflow: ItemRangeOverflow,
  4223. point: ItemPoint
  4224. };
  4225. /**
  4226. * Create the HTML DOM for the ItemSet
  4227. */
  4228. ItemSet.prototype._create = function _create(){
  4229. var frame = document.createElement('div');
  4230. frame['timeline-itemset'] = this;
  4231. this.frame = frame;
  4232. // create background panel
  4233. var background = document.createElement('div');
  4234. background.className = 'background';
  4235. this.backgroundPanel.frame.appendChild(background);
  4236. this.dom.background = background;
  4237. // create foreground panel
  4238. var foreground = document.createElement('div');
  4239. foreground.className = 'foreground';
  4240. frame.appendChild(foreground);
  4241. this.dom.foreground = foreground;
  4242. // create axis panel
  4243. var axis = document.createElement('div');
  4244. axis.className = 'axis';
  4245. this.dom.axis = axis;
  4246. this.axisPanel.frame.appendChild(axis);
  4247. // create labelset
  4248. var labelSet = document.createElement('div');
  4249. labelSet.className = 'labelset';
  4250. this.dom.labelSet = labelSet;
  4251. this.sidePanel.frame.appendChild(labelSet);
  4252. // create ungrouped Group
  4253. this._updateUngrouped();
  4254. // attach event listeners
  4255. // TODO: use event listeners from the rootpanel to improve performance?
  4256. this.hammer = Hammer(frame, {
  4257. prevent_default: true
  4258. });
  4259. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4260. this.hammer.on('drag', this._onDrag.bind(this));
  4261. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4262. };
  4263. /**
  4264. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4265. * @param {Object} [options] The following options are available:
  4266. * {String | function} [className]
  4267. * class name for the itemset
  4268. * {String} [type]
  4269. * Default type for the items. Choose from 'box'
  4270. * (default), 'point', or 'range'. The default
  4271. * Style can be overwritten by individual items.
  4272. * {String} align
  4273. * Alignment for the items, only applicable for
  4274. * ItemBox. Choose 'center' (default), 'left', or
  4275. * 'right'.
  4276. * {String} orientation
  4277. * Orientation of the item set. Choose 'top' or
  4278. * 'bottom' (default).
  4279. * {Number} margin.axis
  4280. * Margin between the axis and the items in pixels.
  4281. * Default is 20.
  4282. * {Number} margin.item
  4283. * Margin between items in pixels. Default is 10.
  4284. * {Number} padding
  4285. * Padding of the contents of an item in pixels.
  4286. * Must correspond with the items css. Default is 5.
  4287. * {Function} snap
  4288. * Function to let items snap to nice dates when
  4289. * dragging items.
  4290. */
  4291. ItemSet.prototype.setOptions = function setOptions(options) {
  4292. Component.prototype.setOptions.call(this, options);
  4293. };
  4294. /**
  4295. * Mark the ItemSet dirty so it will refresh everything with next repaint
  4296. */
  4297. ItemSet.prototype.markDirty = function markDirty() {
  4298. this.groupIds = [];
  4299. this.stackDirty = true;
  4300. };
  4301. /**
  4302. * Hide the component from the DOM
  4303. */
  4304. ItemSet.prototype.hide = function hide() {
  4305. // remove the axis with dots
  4306. if (this.dom.axis.parentNode) {
  4307. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4308. }
  4309. // remove the background with vertical lines
  4310. if (this.dom.background.parentNode) {
  4311. this.dom.background.parentNode.removeChild(this.dom.background);
  4312. }
  4313. // remove the labelset containing all group labels
  4314. if (this.dom.labelSet.parentNode) {
  4315. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  4316. }
  4317. };
  4318. /**
  4319. * Show the component in the DOM (when not already visible).
  4320. * @return {Boolean} changed
  4321. */
  4322. ItemSet.prototype.show = function show() {
  4323. // show axis with dots
  4324. if (!this.dom.axis.parentNode) {
  4325. this.axisPanel.frame.appendChild(this.dom.axis);
  4326. }
  4327. // show background with vertical lines
  4328. if (!this.dom.background.parentNode) {
  4329. this.backgroundPanel.frame.appendChild(this.dom.background);
  4330. }
  4331. // show labelset containing labels
  4332. if (!this.dom.labelSet.parentNode) {
  4333. this.sidePanel.frame.appendChild(this.dom.labelSet);
  4334. }
  4335. };
  4336. /**
  4337. * Set range (start and end).
  4338. * @param {Range | Object} range A Range or an object containing start and end.
  4339. */
  4340. ItemSet.prototype.setRange = function setRange(range) {
  4341. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4342. throw new TypeError('Range must be an instance of Range, ' +
  4343. 'or an object containing start and end.');
  4344. }
  4345. this.range = range;
  4346. };
  4347. /**
  4348. * Set selected items by their id. Replaces the current selection
  4349. * Unknown id's are silently ignored.
  4350. * @param {Array} [ids] An array with zero or more id's of the items to be
  4351. * selected. If ids is an empty array, all items will be
  4352. * unselected.
  4353. */
  4354. ItemSet.prototype.setSelection = function setSelection(ids) {
  4355. var i, ii, id, item;
  4356. if (ids) {
  4357. if (!Array.isArray(ids)) {
  4358. throw new TypeError('Array expected');
  4359. }
  4360. // unselect currently selected items
  4361. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4362. id = this.selection[i];
  4363. item = this.items[id];
  4364. if (item) item.unselect();
  4365. }
  4366. // select items
  4367. this.selection = [];
  4368. for (i = 0, ii = ids.length; i < ii; i++) {
  4369. id = ids[i];
  4370. item = this.items[id];
  4371. if (item) {
  4372. this.selection.push(id);
  4373. item.select();
  4374. }
  4375. }
  4376. }
  4377. };
  4378. /**
  4379. * Get the selected items by their id
  4380. * @return {Array} ids The ids of the selected items
  4381. */
  4382. ItemSet.prototype.getSelection = function getSelection() {
  4383. return this.selection.concat([]);
  4384. };
  4385. /**
  4386. * Deselect a selected item
  4387. * @param {String | Number} id
  4388. * @private
  4389. */
  4390. ItemSet.prototype._deselect = function _deselect(id) {
  4391. var selection = this.selection;
  4392. for (var i = 0, ii = selection.length; i < ii; i++) {
  4393. if (selection[i] == id) { // non-strict comparison!
  4394. selection.splice(i, 1);
  4395. break;
  4396. }
  4397. }
  4398. };
  4399. /**
  4400. * Return the item sets frame
  4401. * @returns {HTMLElement} frame
  4402. */
  4403. ItemSet.prototype.getFrame = function getFrame() {
  4404. return this.frame;
  4405. };
  4406. /**
  4407. * Repaint the component
  4408. * @return {boolean} Returns true if the component is resized
  4409. */
  4410. ItemSet.prototype.repaint = function repaint() {
  4411. var margin = this.options.margin,
  4412. range = this.range,
  4413. asSize = util.option.asSize,
  4414. asString = util.option.asString,
  4415. options = this.options,
  4416. orientation = this.getOption('orientation'),
  4417. resized = false,
  4418. frame = this.frame;
  4419. // TODO: document this feature to specify one margin for both item and axis distance
  4420. if (typeof margin === 'number') {
  4421. margin = {
  4422. item: margin,
  4423. axis: margin
  4424. };
  4425. }
  4426. // update className
  4427. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4428. // reorder the groups (if needed)
  4429. resized = this._orderGroups() || resized;
  4430. // check whether zoomed (in that case we need to re-stack everything)
  4431. // TODO: would be nicer to get this as a trigger from Range
  4432. var visibleInterval = this.range.end - this.range.start;
  4433. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4434. if (zoomed) this.stackDirty = true;
  4435. this.lastVisibleInterval = visibleInterval;
  4436. this.lastWidth = this.width;
  4437. // repaint all groups
  4438. var restack = this.stackDirty,
  4439. firstGroup = this._firstGroup(),
  4440. firstMargin = {
  4441. item: margin.item,
  4442. axis: margin.axis
  4443. },
  4444. nonFirstMargin = {
  4445. item: margin.item,
  4446. axis: margin.item / 2
  4447. },
  4448. height = 0,
  4449. minHeight = margin.axis + margin.item;
  4450. util.forEach(this.groups, function (group) {
  4451. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  4452. resized = group.repaint(range, groupMargin, restack) || resized;
  4453. height += group.height;
  4454. });
  4455. height = Math.max(height, minHeight);
  4456. this.stackDirty = false;
  4457. // reposition frame
  4458. frame.style.left = asSize(options.left, '');
  4459. frame.style.right = asSize(options.right, '');
  4460. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4461. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4462. frame.style.width = asSize(options.width, '100%');
  4463. frame.style.height = asSize(height);
  4464. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4465. // calculate actual size and position
  4466. this.top = frame.offsetTop;
  4467. this.left = frame.offsetLeft;
  4468. this.width = frame.offsetWidth;
  4469. this.height = height;
  4470. // reposition axis
  4471. this.dom.axis.style.left = asSize(options.left, '0');
  4472. this.dom.axis.style.right = asSize(options.right, '');
  4473. this.dom.axis.style.width = asSize(options.width, '100%');
  4474. this.dom.axis.style.height = asSize(0);
  4475. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4476. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4477. // check if this component is resized
  4478. resized = this._isResized() || resized;
  4479. return resized;
  4480. };
  4481. /**
  4482. * Get the first group, aligned with the axis
  4483. * @return {Group | null} firstGroup
  4484. * @private
  4485. */
  4486. ItemSet.prototype._firstGroup = function _firstGroup() {
  4487. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  4488. var firstGroupId = this.groupIds[firstGroupIndex];
  4489. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  4490. return firstGroup || null;
  4491. };
  4492. /**
  4493. * Create or delete the group holding all ungrouped items. This group is used when
  4494. * there are no groups specified.
  4495. * @protected
  4496. */
  4497. ItemSet.prototype._updateUngrouped = function _updateUngrouped() {
  4498. var ungrouped = this.groups[UNGROUPED];
  4499. if (this.groupsData) {
  4500. // remove the group holding all ungrouped items
  4501. if (ungrouped) {
  4502. ungrouped.hide();
  4503. delete this.groups[UNGROUPED];
  4504. }
  4505. }
  4506. else {
  4507. // create a group holding all (unfiltered) items
  4508. if (!ungrouped) {
  4509. var id = null;
  4510. var data = null;
  4511. ungrouped = new Group(id, data, this);
  4512. this.groups[UNGROUPED] = ungrouped;
  4513. for (var itemId in this.items) {
  4514. if (this.items.hasOwnProperty(itemId)) {
  4515. ungrouped.add(this.items[itemId]);
  4516. }
  4517. }
  4518. ungrouped.show();
  4519. }
  4520. }
  4521. };
  4522. /**
  4523. * Get the foreground container element
  4524. * @return {HTMLElement} foreground
  4525. */
  4526. ItemSet.prototype.getForeground = function getForeground() {
  4527. return this.dom.foreground;
  4528. };
  4529. /**
  4530. * Get the background container element
  4531. * @return {HTMLElement} background
  4532. */
  4533. ItemSet.prototype.getBackground = function getBackground() {
  4534. return this.dom.background;
  4535. };
  4536. /**
  4537. * Get the axis container element
  4538. * @return {HTMLElement} axis
  4539. */
  4540. ItemSet.prototype.getAxis = function getAxis() {
  4541. return this.dom.axis;
  4542. };
  4543. /**
  4544. * Get the element for the labelset
  4545. * @return {HTMLElement} labelSet
  4546. */
  4547. ItemSet.prototype.getLabelSet = function getLabelSet() {
  4548. return this.dom.labelSet;
  4549. };
  4550. /**
  4551. * Set items
  4552. * @param {vis.DataSet | null} items
  4553. */
  4554. ItemSet.prototype.setItems = function setItems(items) {
  4555. var me = this,
  4556. ids,
  4557. oldItemsData = this.itemsData;
  4558. // replace the dataset
  4559. if (!items) {
  4560. this.itemsData = null;
  4561. }
  4562. else if (items instanceof DataSet || items instanceof DataView) {
  4563. this.itemsData = items;
  4564. }
  4565. else {
  4566. throw new TypeError('Data must be an instance of DataSet or DataView');
  4567. }
  4568. if (oldItemsData) {
  4569. // unsubscribe from old dataset
  4570. util.forEach(this.itemListeners, function (callback, event) {
  4571. oldItemsData.unsubscribe(event, callback);
  4572. });
  4573. // remove all drawn items
  4574. ids = oldItemsData.getIds();
  4575. this._onRemove(ids);
  4576. }
  4577. if (this.itemsData) {
  4578. // subscribe to new dataset
  4579. var id = this.id;
  4580. util.forEach(this.itemListeners, function (callback, event) {
  4581. me.itemsData.on(event, callback, id);
  4582. });
  4583. // add all new items
  4584. ids = this.itemsData.getIds();
  4585. this._onAdd(ids);
  4586. // update the group holding all ungrouped items
  4587. this._updateUngrouped();
  4588. }
  4589. };
  4590. /**
  4591. * Get the current items
  4592. * @returns {vis.DataSet | null}
  4593. */
  4594. ItemSet.prototype.getItems = function getItems() {
  4595. return this.itemsData;
  4596. };
  4597. /**
  4598. * Set groups
  4599. * @param {vis.DataSet} groups
  4600. */
  4601. ItemSet.prototype.setGroups = function setGroups(groups) {
  4602. var me = this,
  4603. ids;
  4604. // unsubscribe from current dataset
  4605. if (this.groupsData) {
  4606. util.forEach(this.groupListeners, function (callback, event) {
  4607. me.groupsData.unsubscribe(event, callback);
  4608. });
  4609. // remove all drawn groups
  4610. ids = this.groupsData.getIds();
  4611. this.groupsData = null;
  4612. this._onRemoveGroups(ids); // note: this will cause a repaint
  4613. }
  4614. // replace the dataset
  4615. if (!groups) {
  4616. this.groupsData = null;
  4617. }
  4618. else if (groups instanceof DataSet || groups instanceof DataView) {
  4619. this.groupsData = groups;
  4620. }
  4621. else {
  4622. throw new TypeError('Data must be an instance of DataSet or DataView');
  4623. }
  4624. if (this.groupsData) {
  4625. // subscribe to new dataset
  4626. var id = this.id;
  4627. util.forEach(this.groupListeners, function (callback, event) {
  4628. me.groupsData.on(event, callback, id);
  4629. });
  4630. // draw all ms
  4631. ids = this.groupsData.getIds();
  4632. this._onAddGroups(ids);
  4633. }
  4634. // update the group holding all ungrouped items
  4635. this._updateUngrouped();
  4636. // update the order of all items in each group
  4637. this._order();
  4638. this.emit('change');
  4639. };
  4640. /**
  4641. * Get the current groups
  4642. * @returns {vis.DataSet | null} groups
  4643. */
  4644. ItemSet.prototype.getGroups = function getGroups() {
  4645. return this.groupsData;
  4646. };
  4647. /**
  4648. * Remove an item by its id
  4649. * @param {String | Number} id
  4650. */
  4651. ItemSet.prototype.removeItem = function removeItem (id) {
  4652. var item = this.itemsData.get(id),
  4653. dataset = this._myDataSet();
  4654. if (item) {
  4655. // confirm deletion
  4656. this.options.onRemove(item, function (item) {
  4657. if (item) {
  4658. // remove by id here, it is possible that an item has no id defined
  4659. // itself, so better not delete by the item itself
  4660. dataset.remove(id);
  4661. }
  4662. });
  4663. }
  4664. };
  4665. /**
  4666. * Handle updated items
  4667. * @param {Number[]} ids
  4668. * @protected
  4669. */
  4670. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4671. var me = this,
  4672. items = this.items,
  4673. itemOptions = this.itemOptions;
  4674. ids.forEach(function (id) {
  4675. var itemData = me.itemsData.get(id),
  4676. item = items[id],
  4677. type = itemData.type ||
  4678. (itemData.start && itemData.end && 'range') ||
  4679. me.options.type ||
  4680. 'box';
  4681. var constructor = ItemSet.types[type];
  4682. if (item) {
  4683. // update item
  4684. if (!constructor || !(item instanceof constructor)) {
  4685. // item type has changed, delete the item and recreate it
  4686. me._removeItem(item);
  4687. item = null;
  4688. }
  4689. else {
  4690. me._updateItem(item, itemData);
  4691. }
  4692. }
  4693. if (!item) {
  4694. // create item
  4695. if (constructor) {
  4696. item = new constructor(itemData, me.options, itemOptions);
  4697. item.id = id; // TODO: not so nice setting id afterwards
  4698. me._addItem(item);
  4699. }
  4700. else {
  4701. throw new TypeError('Unknown item type "' + type + '"');
  4702. }
  4703. }
  4704. });
  4705. this._order();
  4706. this.stackDirty = true; // force re-stacking of all items next repaint
  4707. this.emit('change');
  4708. };
  4709. /**
  4710. * Handle added items
  4711. * @param {Number[]} ids
  4712. * @protected
  4713. */
  4714. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4715. /**
  4716. * Handle removed items
  4717. * @param {Number[]} ids
  4718. * @protected
  4719. */
  4720. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4721. var count = 0;
  4722. var me = this;
  4723. ids.forEach(function (id) {
  4724. var item = me.items[id];
  4725. if (item) {
  4726. count++;
  4727. me._removeItem(item);
  4728. }
  4729. });
  4730. if (count) {
  4731. // update order
  4732. this._order();
  4733. this.stackDirty = true; // force re-stacking of all items next repaint
  4734. this.emit('change');
  4735. }
  4736. };
  4737. /**
  4738. * Update the order of item in all groups
  4739. * @private
  4740. */
  4741. ItemSet.prototype._order = function _order() {
  4742. // reorder the items in all groups
  4743. // TODO: optimization: only reorder groups affected by the changed items
  4744. util.forEach(this.groups, function (group) {
  4745. group.order();
  4746. });
  4747. };
  4748. /**
  4749. * Handle updated groups
  4750. * @param {Number[]} ids
  4751. * @private
  4752. */
  4753. ItemSet.prototype._onUpdateGroups = function _onUpdateGroups(ids) {
  4754. this._onAddGroups(ids);
  4755. };
  4756. /**
  4757. * Handle changed groups
  4758. * @param {Number[]} ids
  4759. * @private
  4760. */
  4761. ItemSet.prototype._onAddGroups = function _onAddGroups(ids) {
  4762. var me = this;
  4763. ids.forEach(function (id) {
  4764. var groupData = me.groupsData.get(id);
  4765. var group = me.groups[id];
  4766. if (!group) {
  4767. // check for reserved ids
  4768. if (id == UNGROUPED) {
  4769. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  4770. }
  4771. var groupOptions = Object.create(me.options);
  4772. util.extend(groupOptions, {
  4773. height: null
  4774. });
  4775. group = new Group(id, groupData, me);
  4776. me.groups[id] = group;
  4777. // add items with this groupId to the new group
  4778. for (var itemId in me.items) {
  4779. if (me.items.hasOwnProperty(itemId)) {
  4780. var item = me.items[itemId];
  4781. if (item.data.group == id) {
  4782. group.add(item);
  4783. }
  4784. }
  4785. }
  4786. group.order();
  4787. group.show();
  4788. }
  4789. else {
  4790. // update group
  4791. group.setData(groupData);
  4792. }
  4793. });
  4794. this.emit('change');
  4795. };
  4796. /**
  4797. * Handle removed groups
  4798. * @param {Number[]} ids
  4799. * @private
  4800. */
  4801. ItemSet.prototype._onRemoveGroups = function _onRemoveGroups(ids) {
  4802. var groups = this.groups;
  4803. ids.forEach(function (id) {
  4804. var group = groups[id];
  4805. if (group) {
  4806. group.hide();
  4807. delete groups[id];
  4808. }
  4809. });
  4810. this.markDirty();
  4811. this.emit('change');
  4812. };
  4813. /**
  4814. * Reorder the groups if needed
  4815. * @return {boolean} changed
  4816. * @private
  4817. */
  4818. ItemSet.prototype._orderGroups = function () {
  4819. if (this.groupsData) {
  4820. // reorder the groups
  4821. var groupIds = this.groupsData.getIds({
  4822. order: this.options.groupOrder
  4823. });
  4824. var changed = !util.equalArray(groupIds, this.groupIds);
  4825. if (changed) {
  4826. // hide all groups, removes them from the DOM
  4827. var groups = this.groups;
  4828. groupIds.forEach(function (groupId) {
  4829. groups[groupId].hide();
  4830. });
  4831. // show the groups again, attach them to the DOM in correct order
  4832. groupIds.forEach(function (groupId) {
  4833. groups[groupId].show();
  4834. });
  4835. this.groupIds = groupIds;
  4836. }
  4837. return changed;
  4838. }
  4839. else {
  4840. return false;
  4841. }
  4842. };
  4843. /**
  4844. * Add a new item
  4845. * @param {Item} item
  4846. * @private
  4847. */
  4848. ItemSet.prototype._addItem = function _addItem(item) {
  4849. this.items[item.id] = item;
  4850. // add to group
  4851. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4852. var group = this.groups[groupId];
  4853. if (group) group.add(item);
  4854. };
  4855. /**
  4856. * Update an existing item
  4857. * @param {Item} item
  4858. * @param {Object} itemData
  4859. * @private
  4860. */
  4861. ItemSet.prototype._updateItem = function _updateItem(item, itemData) {
  4862. var oldGroupId = item.data.group;
  4863. item.data = itemData;
  4864. if (item.displayed) {
  4865. item.repaint();
  4866. }
  4867. // update group
  4868. if (oldGroupId != item.data.group) {
  4869. var oldGroup = this.groups[oldGroupId];
  4870. if (oldGroup) oldGroup.remove(item);
  4871. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4872. var group = this.groups[groupId];
  4873. if (group) group.add(item);
  4874. }
  4875. };
  4876. /**
  4877. * Delete an item from the ItemSet: remove it from the DOM, from the map
  4878. * with items, and from the map with visible items, and from the selection
  4879. * @param {Item} item
  4880. * @private
  4881. */
  4882. ItemSet.prototype._removeItem = function _removeItem(item) {
  4883. // remove from DOM
  4884. item.hide();
  4885. // remove from items
  4886. delete this.items[item.id];
  4887. // remove from selection
  4888. var index = this.selection.indexOf(item.id);
  4889. if (index != -1) this.selection.splice(index, 1);
  4890. // remove from group
  4891. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4892. var group = this.groups[groupId];
  4893. if (group) group.remove(item);
  4894. };
  4895. /**
  4896. * Create an array containing all items being a range (having an end date)
  4897. * @param array
  4898. * @returns {Array}
  4899. * @private
  4900. */
  4901. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  4902. var endArray = [];
  4903. for (var i = 0; i < array.length; i++) {
  4904. if (array[i] instanceof ItemRange) {
  4905. endArray.push(array[i]);
  4906. }
  4907. }
  4908. return endArray;
  4909. };
  4910. /**
  4911. * Get the width of the group labels
  4912. * @return {Number} width
  4913. */
  4914. ItemSet.prototype.getLabelsWidth = function getLabelsWidth() {
  4915. var width = 0;
  4916. util.forEach(this.groups, function (group) {
  4917. width = Math.max(width, group.getLabelWidth());
  4918. });
  4919. return width;
  4920. };
  4921. /**
  4922. * Get the height of the itemsets background
  4923. * @return {Number} height
  4924. */
  4925. ItemSet.prototype.getBackgroundHeight = function getBackgroundHeight() {
  4926. return this.height;
  4927. };
  4928. /**
  4929. * Start dragging the selected events
  4930. * @param {Event} event
  4931. * @private
  4932. */
  4933. ItemSet.prototype._onDragStart = function (event) {
  4934. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  4935. return;
  4936. }
  4937. var item = ItemSet.itemFromTarget(event),
  4938. me = this,
  4939. props;
  4940. if (item && item.selected) {
  4941. var dragLeftItem = event.target.dragLeftItem;
  4942. var dragRightItem = event.target.dragRightItem;
  4943. if (dragLeftItem) {
  4944. props = {
  4945. item: dragLeftItem
  4946. };
  4947. if (me.options.editable.updateTime) {
  4948. props.start = item.data.start.valueOf();
  4949. }
  4950. if (me.options.editable.updateGroup) {
  4951. if ('group' in item.data) props.group = item.data.group;
  4952. }
  4953. this.touchParams.itemProps = [props];
  4954. }
  4955. else if (dragRightItem) {
  4956. props = {
  4957. item: dragRightItem
  4958. };
  4959. if (me.options.editable.updateTime) {
  4960. props.end = item.data.end.valueOf();
  4961. }
  4962. if (me.options.editable.updateGroup) {
  4963. if ('group' in item.data) props.group = item.data.group;
  4964. }
  4965. this.touchParams.itemProps = [props];
  4966. }
  4967. else {
  4968. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4969. var item = me.items[id];
  4970. var props = {
  4971. item: item
  4972. };
  4973. if (me.options.editable.updateTime) {
  4974. if ('start' in item.data) props.start = item.data.start.valueOf();
  4975. if ('end' in item.data) props.end = item.data.end.valueOf();
  4976. }
  4977. if (me.options.editable.updateGroup) {
  4978. if ('group' in item.data) props.group = item.data.group;
  4979. }
  4980. return props;
  4981. });
  4982. }
  4983. event.stopPropagation();
  4984. }
  4985. };
  4986. /**
  4987. * Drag selected items
  4988. * @param {Event} event
  4989. * @private
  4990. */
  4991. ItemSet.prototype._onDrag = function (event) {
  4992. if (this.touchParams.itemProps) {
  4993. var snap = this.options.snap || null,
  4994. deltaX = event.gesture.deltaX,
  4995. scale = (this.width / (this.range.end - this.range.start)),
  4996. offset = deltaX / scale;
  4997. // move
  4998. this.touchParams.itemProps.forEach(function (props) {
  4999. if ('start' in props) {
  5000. var start = new Date(props.start + offset);
  5001. props.item.data.start = snap ? snap(start) : start;
  5002. }
  5003. if ('end' in props) {
  5004. var end = new Date(props.end + offset);
  5005. props.item.data.end = snap ? snap(end) : end;
  5006. }
  5007. if ('group' in props) {
  5008. // drag from one group to another
  5009. var group = ItemSet.groupFromTarget(event);
  5010. if (group && group.groupId != props.item.data.group) {
  5011. var oldGroup = props.item.parent;
  5012. oldGroup.remove(props.item);
  5013. oldGroup.order();
  5014. group.add(props.item);
  5015. group.order();
  5016. props.item.data.group = group.groupId;
  5017. }
  5018. }
  5019. });
  5020. // TODO: implement onMoving handler
  5021. this.stackDirty = true; // force re-stacking of all items next repaint
  5022. this.emit('change');
  5023. event.stopPropagation();
  5024. }
  5025. };
  5026. /**
  5027. * End of dragging selected items
  5028. * @param {Event} event
  5029. * @private
  5030. */
  5031. ItemSet.prototype._onDragEnd = function (event) {
  5032. if (this.touchParams.itemProps) {
  5033. // prepare a change set for the changed items
  5034. var changes = [],
  5035. me = this,
  5036. dataset = this._myDataSet();
  5037. this.touchParams.itemProps.forEach(function (props) {
  5038. var id = props.item.id,
  5039. itemData = me.itemsData.get(id);
  5040. var changed = false;
  5041. if ('start' in props.item.data) {
  5042. changed = (props.start != props.item.data.start.valueOf());
  5043. itemData.start = util.convert(props.item.data.start, dataset.convert['start']);
  5044. }
  5045. if ('end' in props.item.data) {
  5046. changed = changed || (props.end != props.item.data.end.valueOf());
  5047. itemData.end = util.convert(props.item.data.end, dataset.convert['end']);
  5048. }
  5049. if ('group' in props.item.data) {
  5050. changed = changed || (props.group != props.item.data.group);
  5051. itemData.group = props.item.data.group;
  5052. }
  5053. // only apply changes when start or end is actually changed
  5054. if (changed) {
  5055. me.options.onMove(itemData, function (itemData) {
  5056. if (itemData) {
  5057. // apply changes
  5058. itemData[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  5059. changes.push(itemData);
  5060. }
  5061. else {
  5062. // restore original values
  5063. if ('start' in props) props.item.data.start = props.start;
  5064. if ('end' in props) props.item.data.end = props.end;
  5065. me.stackDirty = true; // force re-stacking of all items next repaint
  5066. me.emit('change');
  5067. }
  5068. });
  5069. }
  5070. });
  5071. this.touchParams.itemProps = null;
  5072. // apply the changes to the data (if there are changes)
  5073. if (changes.length) {
  5074. dataset.update(changes);
  5075. }
  5076. event.stopPropagation();
  5077. }
  5078. };
  5079. /**
  5080. * Find an item from an event target:
  5081. * searches for the attribute 'timeline-item' in the event target's element tree
  5082. * @param {Event} event
  5083. * @return {Item | null} item
  5084. */
  5085. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5086. var target = event.target;
  5087. while (target) {
  5088. if (target.hasOwnProperty('timeline-item')) {
  5089. return target['timeline-item'];
  5090. }
  5091. target = target.parentNode;
  5092. }
  5093. return null;
  5094. };
  5095. /**
  5096. * Find the Group from an event target:
  5097. * searches for the attribute 'timeline-group' in the event target's element tree
  5098. * @param {Event} event
  5099. * @return {Group | null} group
  5100. */
  5101. ItemSet.groupFromTarget = function groupFromTarget (event) {
  5102. var target = event.target;
  5103. while (target) {
  5104. if (target.hasOwnProperty('timeline-group')) {
  5105. return target['timeline-group'];
  5106. }
  5107. target = target.parentNode;
  5108. }
  5109. return null;
  5110. };
  5111. /**
  5112. * Find the ItemSet from an event target:
  5113. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5114. * @param {Event} event
  5115. * @return {ItemSet | null} item
  5116. */
  5117. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5118. var target = event.target;
  5119. while (target) {
  5120. if (target.hasOwnProperty('timeline-itemset')) {
  5121. return target['timeline-itemset'];
  5122. }
  5123. target = target.parentNode;
  5124. }
  5125. return null;
  5126. };
  5127. /**
  5128. * Find the DataSet to which this ItemSet is connected
  5129. * @returns {null | DataSet} dataset
  5130. * @private
  5131. */
  5132. ItemSet.prototype._myDataSet = function _myDataSet() {
  5133. // find the root DataSet
  5134. var dataset = this.itemsData;
  5135. while (dataset instanceof DataView) {
  5136. dataset = dataset.data;
  5137. }
  5138. return dataset;
  5139. };
  5140. /**
  5141. * @constructor Item
  5142. * @param {Object} data Object containing (optional) parameters type,
  5143. * start, end, content, group, className.
  5144. * @param {Object} [options] Options to set initial property values
  5145. * @param {Object} [defaultOptions] default options
  5146. * // TODO: describe available options
  5147. */
  5148. function Item (data, options, defaultOptions) {
  5149. this.id = null;
  5150. this.parent = null;
  5151. this.data = data;
  5152. this.dom = null;
  5153. this.options = options || {};
  5154. this.defaultOptions = defaultOptions || {};
  5155. this.selected = false;
  5156. this.displayed = false;
  5157. this.dirty = true;
  5158. this.top = null;
  5159. this.left = null;
  5160. this.width = null;
  5161. this.height = null;
  5162. }
  5163. /**
  5164. * Select current item
  5165. */
  5166. Item.prototype.select = function select() {
  5167. this.selected = true;
  5168. if (this.displayed) this.repaint();
  5169. };
  5170. /**
  5171. * Unselect current item
  5172. */
  5173. Item.prototype.unselect = function unselect() {
  5174. this.selected = false;
  5175. if (this.displayed) this.repaint();
  5176. };
  5177. /**
  5178. * Set a parent for the item
  5179. * @param {ItemSet | Group} parent
  5180. */
  5181. Item.prototype.setParent = function setParent(parent) {
  5182. if (this.displayed) {
  5183. this.hide();
  5184. this.parent = parent;
  5185. if (this.parent) {
  5186. this.show();
  5187. }
  5188. }
  5189. else {
  5190. this.parent = parent;
  5191. }
  5192. };
  5193. /**
  5194. * Check whether this item is visible inside given range
  5195. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5196. * @returns {boolean} True if visible
  5197. */
  5198. Item.prototype.isVisible = function isVisible (range) {
  5199. // Should be implemented by Item implementations
  5200. return false;
  5201. };
  5202. /**
  5203. * Show the Item in the DOM (when not already visible)
  5204. * @return {Boolean} changed
  5205. */
  5206. Item.prototype.show = function show() {
  5207. return false;
  5208. };
  5209. /**
  5210. * Hide the Item from the DOM (when visible)
  5211. * @return {Boolean} changed
  5212. */
  5213. Item.prototype.hide = function hide() {
  5214. return false;
  5215. };
  5216. /**
  5217. * Repaint the item
  5218. */
  5219. Item.prototype.repaint = function repaint() {
  5220. // should be implemented by the item
  5221. };
  5222. /**
  5223. * Reposition the Item horizontally
  5224. */
  5225. Item.prototype.repositionX = function repositionX() {
  5226. // should be implemented by the item
  5227. };
  5228. /**
  5229. * Reposition the Item vertically
  5230. */
  5231. Item.prototype.repositionY = function repositionY() {
  5232. // should be implemented by the item
  5233. };
  5234. /**
  5235. * Repaint a delete button on the top right of the item when the item is selected
  5236. * @param {HTMLElement} anchor
  5237. * @protected
  5238. */
  5239. Item.prototype._repaintDeleteButton = function (anchor) {
  5240. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  5241. // create and show button
  5242. var me = this;
  5243. var deleteButton = document.createElement('div');
  5244. deleteButton.className = 'delete';
  5245. deleteButton.title = 'Delete this item';
  5246. Hammer(deleteButton, {
  5247. preventDefault: true
  5248. }).on('tap', function (event) {
  5249. me.parent.removeFromDataSet(me);
  5250. event.stopPropagation();
  5251. });
  5252. anchor.appendChild(deleteButton);
  5253. this.dom.deleteButton = deleteButton;
  5254. }
  5255. else if (!this.selected && this.dom.deleteButton) {
  5256. // remove button
  5257. if (this.dom.deleteButton.parentNode) {
  5258. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5259. }
  5260. this.dom.deleteButton = null;
  5261. }
  5262. };
  5263. /**
  5264. * @constructor ItemBox
  5265. * @extends Item
  5266. * @param {Object} data Object containing parameters start
  5267. * content, className.
  5268. * @param {Object} [options] Options to set initial property values
  5269. * @param {Object} [defaultOptions] default options
  5270. * // TODO: describe available options
  5271. */
  5272. function ItemBox (data, options, defaultOptions) {
  5273. this.props = {
  5274. dot: {
  5275. width: 0,
  5276. height: 0
  5277. },
  5278. line: {
  5279. width: 0,
  5280. height: 0
  5281. }
  5282. };
  5283. // validate data
  5284. if (data) {
  5285. if (data.start == undefined) {
  5286. throw new Error('Property "start" missing in item ' + data);
  5287. }
  5288. }
  5289. Item.call(this, data, options, defaultOptions);
  5290. }
  5291. ItemBox.prototype = new Item (null);
  5292. /**
  5293. * Check whether this item is visible inside given range
  5294. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5295. * @returns {boolean} True if visible
  5296. */
  5297. ItemBox.prototype.isVisible = function isVisible (range) {
  5298. // determine visibility
  5299. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5300. var interval = (range.end - range.start) / 4;
  5301. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5302. };
  5303. /**
  5304. * Repaint the item
  5305. */
  5306. ItemBox.prototype.repaint = function repaint() {
  5307. var dom = this.dom;
  5308. if (!dom) {
  5309. // create DOM
  5310. this.dom = {};
  5311. dom = this.dom;
  5312. // create main box
  5313. dom.box = document.createElement('DIV');
  5314. // contents box (inside the background box). used for making margins
  5315. dom.content = document.createElement('DIV');
  5316. dom.content.className = 'content';
  5317. dom.box.appendChild(dom.content);
  5318. // line to axis
  5319. dom.line = document.createElement('DIV');
  5320. dom.line.className = 'line';
  5321. // dot on axis
  5322. dom.dot = document.createElement('DIV');
  5323. dom.dot.className = 'dot';
  5324. // attach this item as attribute
  5325. dom.box['timeline-item'] = this;
  5326. }
  5327. // append DOM to parent DOM
  5328. if (!this.parent) {
  5329. throw new Error('Cannot repaint item: no parent attached');
  5330. }
  5331. if (!dom.box.parentNode) {
  5332. var foreground = this.parent.getForeground();
  5333. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5334. foreground.appendChild(dom.box);
  5335. }
  5336. if (!dom.line.parentNode) {
  5337. var background = this.parent.getBackground();
  5338. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5339. background.appendChild(dom.line);
  5340. }
  5341. if (!dom.dot.parentNode) {
  5342. var axis = this.parent.getAxis();
  5343. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5344. axis.appendChild(dom.dot);
  5345. }
  5346. this.displayed = true;
  5347. // update contents
  5348. if (this.data.content != this.content) {
  5349. this.content = this.data.content;
  5350. if (this.content instanceof Element) {
  5351. dom.content.innerHTML = '';
  5352. dom.content.appendChild(this.content);
  5353. }
  5354. else if (this.data.content != undefined) {
  5355. dom.content.innerHTML = this.content;
  5356. }
  5357. else {
  5358. throw new Error('Property "content" missing in item ' + this.data.id);
  5359. }
  5360. this.dirty = true;
  5361. }
  5362. // update class
  5363. var className = (this.data.className? ' ' + this.data.className : '') +
  5364. (this.selected ? ' selected' : '');
  5365. if (this.className != className) {
  5366. this.className = className;
  5367. dom.box.className = 'item box' + className;
  5368. dom.line.className = 'item line' + className;
  5369. dom.dot.className = 'item dot' + className;
  5370. this.dirty = true;
  5371. }
  5372. // recalculate size
  5373. if (this.dirty) {
  5374. this.props.dot.height = dom.dot.offsetHeight;
  5375. this.props.dot.width = dom.dot.offsetWidth;
  5376. this.props.line.width = dom.line.offsetWidth;
  5377. this.width = dom.box.offsetWidth;
  5378. this.height = dom.box.offsetHeight;
  5379. this.dirty = false;
  5380. }
  5381. this._repaintDeleteButton(dom.box);
  5382. };
  5383. /**
  5384. * Show the item in the DOM (when not already displayed). The items DOM will
  5385. * be created when needed.
  5386. */
  5387. ItemBox.prototype.show = function show() {
  5388. if (!this.displayed) {
  5389. this.repaint();
  5390. }
  5391. };
  5392. /**
  5393. * Hide the item from the DOM (when visible)
  5394. */
  5395. ItemBox.prototype.hide = function hide() {
  5396. if (this.displayed) {
  5397. var dom = this.dom;
  5398. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5399. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5400. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5401. this.top = null;
  5402. this.left = null;
  5403. this.displayed = false;
  5404. }
  5405. };
  5406. /**
  5407. * Reposition the item horizontally
  5408. * @Override
  5409. */
  5410. ItemBox.prototype.repositionX = function repositionX() {
  5411. var start = this.defaultOptions.toScreen(this.data.start),
  5412. align = this.options.align || this.defaultOptions.align,
  5413. left,
  5414. box = this.dom.box,
  5415. line = this.dom.line,
  5416. dot = this.dom.dot;
  5417. // calculate left position of the box
  5418. if (align == 'right') {
  5419. this.left = start - this.width;
  5420. }
  5421. else if (align == 'left') {
  5422. this.left = start;
  5423. }
  5424. else {
  5425. // default or 'center'
  5426. this.left = start - this.width / 2;
  5427. }
  5428. // reposition box
  5429. box.style.left = this.left + 'px';
  5430. // reposition line
  5431. line.style.left = (start - this.props.line.width / 2) + 'px';
  5432. // reposition dot
  5433. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5434. };
  5435. /**
  5436. * Reposition the item vertically
  5437. * @Override
  5438. */
  5439. ItemBox.prototype.repositionY = function repositionY () {
  5440. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5441. box = this.dom.box,
  5442. line = this.dom.line,
  5443. dot = this.dom.dot;
  5444. if (orientation == 'top') {
  5445. box.style.top = (this.top || 0) + 'px';
  5446. box.style.bottom = '';
  5447. line.style.top = '0';
  5448. line.style.bottom = '';
  5449. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5450. }
  5451. else { // orientation 'bottom'
  5452. box.style.top = '';
  5453. box.style.bottom = (this.top || 0) + 'px';
  5454. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5455. line.style.bottom = '0';
  5456. line.style.height = '';
  5457. }
  5458. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5459. };
  5460. /**
  5461. * @constructor ItemPoint
  5462. * @extends Item
  5463. * @param {Object} data Object containing parameters start
  5464. * content, className.
  5465. * @param {Object} [options] Options to set initial property values
  5466. * @param {Object} [defaultOptions] default options
  5467. * // TODO: describe available options
  5468. */
  5469. function ItemPoint (data, options, defaultOptions) {
  5470. this.props = {
  5471. dot: {
  5472. top: 0,
  5473. width: 0,
  5474. height: 0
  5475. },
  5476. content: {
  5477. height: 0,
  5478. marginLeft: 0
  5479. }
  5480. };
  5481. // validate data
  5482. if (data) {
  5483. if (data.start == undefined) {
  5484. throw new Error('Property "start" missing in item ' + data);
  5485. }
  5486. }
  5487. Item.call(this, data, options, defaultOptions);
  5488. }
  5489. ItemPoint.prototype = new Item (null);
  5490. /**
  5491. * Check whether this item is visible inside given range
  5492. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5493. * @returns {boolean} True if visible
  5494. */
  5495. ItemPoint.prototype.isVisible = function isVisible (range) {
  5496. // determine visibility
  5497. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5498. var interval = (range.end - range.start) / 4;
  5499. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5500. };
  5501. /**
  5502. * Repaint the item
  5503. */
  5504. ItemPoint.prototype.repaint = function repaint() {
  5505. var dom = this.dom;
  5506. if (!dom) {
  5507. // create DOM
  5508. this.dom = {};
  5509. dom = this.dom;
  5510. // background box
  5511. dom.point = document.createElement('div');
  5512. // className is updated in repaint()
  5513. // contents box, right from the dot
  5514. dom.content = document.createElement('div');
  5515. dom.content.className = 'content';
  5516. dom.point.appendChild(dom.content);
  5517. // dot at start
  5518. dom.dot = document.createElement('div');
  5519. dom.point.appendChild(dom.dot);
  5520. // attach this item as attribute
  5521. dom.point['timeline-item'] = this;
  5522. }
  5523. // append DOM to parent DOM
  5524. if (!this.parent) {
  5525. throw new Error('Cannot repaint item: no parent attached');
  5526. }
  5527. if (!dom.point.parentNode) {
  5528. var foreground = this.parent.getForeground();
  5529. if (!foreground) {
  5530. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5531. }
  5532. foreground.appendChild(dom.point);
  5533. }
  5534. this.displayed = true;
  5535. // update contents
  5536. if (this.data.content != this.content) {
  5537. this.content = this.data.content;
  5538. if (this.content instanceof Element) {
  5539. dom.content.innerHTML = '';
  5540. dom.content.appendChild(this.content);
  5541. }
  5542. else if (this.data.content != undefined) {
  5543. dom.content.innerHTML = this.content;
  5544. }
  5545. else {
  5546. throw new Error('Property "content" missing in item ' + this.data.id);
  5547. }
  5548. this.dirty = true;
  5549. }
  5550. // update class
  5551. var className = (this.data.className? ' ' + this.data.className : '') +
  5552. (this.selected ? ' selected' : '');
  5553. if (this.className != className) {
  5554. this.className = className;
  5555. dom.point.className = 'item point' + className;
  5556. dom.dot.className = 'item dot' + className;
  5557. this.dirty = true;
  5558. }
  5559. // recalculate size
  5560. if (this.dirty) {
  5561. this.width = dom.point.offsetWidth;
  5562. this.height = dom.point.offsetHeight;
  5563. this.props.dot.width = dom.dot.offsetWidth;
  5564. this.props.dot.height = dom.dot.offsetHeight;
  5565. this.props.content.height = dom.content.offsetHeight;
  5566. // resize contents
  5567. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  5568. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5569. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5570. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  5571. this.dirty = false;
  5572. }
  5573. this._repaintDeleteButton(dom.point);
  5574. };
  5575. /**
  5576. * Show the item in the DOM (when not already visible). The items DOM will
  5577. * be created when needed.
  5578. */
  5579. ItemPoint.prototype.show = function show() {
  5580. if (!this.displayed) {
  5581. this.repaint();
  5582. }
  5583. };
  5584. /**
  5585. * Hide the item from the DOM (when visible)
  5586. */
  5587. ItemPoint.prototype.hide = function hide() {
  5588. if (this.displayed) {
  5589. if (this.dom.point.parentNode) {
  5590. this.dom.point.parentNode.removeChild(this.dom.point);
  5591. }
  5592. this.top = null;
  5593. this.left = null;
  5594. this.displayed = false;
  5595. }
  5596. };
  5597. /**
  5598. * Reposition the item horizontally
  5599. * @Override
  5600. */
  5601. ItemPoint.prototype.repositionX = function repositionX() {
  5602. var start = this.defaultOptions.toScreen(this.data.start);
  5603. this.left = start - this.props.dot.width;
  5604. // reposition point
  5605. this.dom.point.style.left = this.left + 'px';
  5606. };
  5607. /**
  5608. * Reposition the item vertically
  5609. * @Override
  5610. */
  5611. ItemPoint.prototype.repositionY = function repositionY () {
  5612. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5613. point = this.dom.point;
  5614. if (orientation == 'top') {
  5615. point.style.top = this.top + 'px';
  5616. point.style.bottom = '';
  5617. }
  5618. else {
  5619. point.style.top = '';
  5620. point.style.bottom = this.top + 'px';
  5621. }
  5622. };
  5623. /**
  5624. * @constructor ItemRange
  5625. * @extends Item
  5626. * @param {Object} data Object containing parameters start, end
  5627. * content, className.
  5628. * @param {Object} [options] Options to set initial property values
  5629. * @param {Object} [defaultOptions] default options
  5630. * // TODO: describe available options
  5631. */
  5632. function ItemRange (data, options, defaultOptions) {
  5633. this.props = {
  5634. content: {
  5635. width: 0
  5636. }
  5637. };
  5638. // validate data
  5639. if (data) {
  5640. if (data.start == undefined) {
  5641. throw new Error('Property "start" missing in item ' + data.id);
  5642. }
  5643. if (data.end == undefined) {
  5644. throw new Error('Property "end" missing in item ' + data.id);
  5645. }
  5646. }
  5647. Item.call(this, data, options, defaultOptions);
  5648. }
  5649. ItemRange.prototype = new Item (null);
  5650. ItemRange.prototype.baseClassName = 'item range';
  5651. /**
  5652. * Check whether this item is visible inside given range
  5653. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5654. * @returns {boolean} True if visible
  5655. */
  5656. ItemRange.prototype.isVisible = function isVisible (range) {
  5657. // determine visibility
  5658. return (this.data.start < range.end) && (this.data.end > range.start);
  5659. };
  5660. /**
  5661. * Repaint the item
  5662. */
  5663. ItemRange.prototype.repaint = function repaint() {
  5664. var dom = this.dom;
  5665. if (!dom) {
  5666. // create DOM
  5667. this.dom = {};
  5668. dom = this.dom;
  5669. // background box
  5670. dom.box = document.createElement('div');
  5671. // className is updated in repaint()
  5672. // contents box
  5673. dom.content = document.createElement('div');
  5674. dom.content.className = 'content';
  5675. dom.box.appendChild(dom.content);
  5676. // attach this item as attribute
  5677. dom.box['timeline-item'] = this;
  5678. }
  5679. // append DOM to parent DOM
  5680. if (!this.parent) {
  5681. throw new Error('Cannot repaint item: no parent attached');
  5682. }
  5683. if (!dom.box.parentNode) {
  5684. var foreground = this.parent.getForeground();
  5685. if (!foreground) {
  5686. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5687. }
  5688. foreground.appendChild(dom.box);
  5689. }
  5690. this.displayed = true;
  5691. // update contents
  5692. if (this.data.content != this.content) {
  5693. this.content = this.data.content;
  5694. if (this.content instanceof Element) {
  5695. dom.content.innerHTML = '';
  5696. dom.content.appendChild(this.content);
  5697. }
  5698. else if (this.data.content != undefined) {
  5699. dom.content.innerHTML = this.content;
  5700. }
  5701. else {
  5702. throw new Error('Property "content" missing in item ' + this.data.id);
  5703. }
  5704. this.dirty = true;
  5705. }
  5706. // update class
  5707. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5708. (this.selected ? ' selected' : '');
  5709. if (this.className != className) {
  5710. this.className = className;
  5711. dom.box.className = this.baseClassName + className;
  5712. this.dirty = true;
  5713. }
  5714. // recalculate size
  5715. if (this.dirty) {
  5716. this.props.content.width = this.dom.content.offsetWidth;
  5717. this.height = this.dom.box.offsetHeight;
  5718. this.dirty = false;
  5719. }
  5720. this._repaintDeleteButton(dom.box);
  5721. this._repaintDragLeft();
  5722. this._repaintDragRight();
  5723. };
  5724. /**
  5725. * Show the item in the DOM (when not already visible). The items DOM will
  5726. * be created when needed.
  5727. */
  5728. ItemRange.prototype.show = function show() {
  5729. if (!this.displayed) {
  5730. this.repaint();
  5731. }
  5732. };
  5733. /**
  5734. * Hide the item from the DOM (when visible)
  5735. * @return {Boolean} changed
  5736. */
  5737. ItemRange.prototype.hide = function hide() {
  5738. if (this.displayed) {
  5739. var box = this.dom.box;
  5740. if (box.parentNode) {
  5741. box.parentNode.removeChild(box);
  5742. }
  5743. this.top = null;
  5744. this.left = null;
  5745. this.displayed = false;
  5746. }
  5747. };
  5748. /**
  5749. * Reposition the item horizontally
  5750. * @Override
  5751. */
  5752. ItemRange.prototype.repositionX = function repositionX() {
  5753. var props = this.props,
  5754. parentWidth = this.parent.width,
  5755. start = this.defaultOptions.toScreen(this.data.start),
  5756. end = this.defaultOptions.toScreen(this.data.end),
  5757. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5758. contentLeft;
  5759. // limit the width of the this, as browsers cannot draw very wide divs
  5760. if (start < -parentWidth) {
  5761. start = -parentWidth;
  5762. }
  5763. if (end > 2 * parentWidth) {
  5764. end = 2 * parentWidth;
  5765. }
  5766. // when range exceeds left of the window, position the contents at the left of the visible area
  5767. if (start < 0) {
  5768. contentLeft = Math.min(-start,
  5769. (end - start - props.content.width - 2 * padding));
  5770. // TODO: remove the need for options.padding. it's terrible.
  5771. }
  5772. else {
  5773. contentLeft = 0;
  5774. }
  5775. this.left = start;
  5776. this.width = Math.max(end - start, 1);
  5777. this.dom.box.style.left = this.left + 'px';
  5778. this.dom.box.style.width = this.width + 'px';
  5779. this.dom.content.style.left = contentLeft + 'px';
  5780. };
  5781. /**
  5782. * Reposition the item vertically
  5783. * @Override
  5784. */
  5785. ItemRange.prototype.repositionY = function repositionY() {
  5786. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5787. box = this.dom.box;
  5788. if (orientation == 'top') {
  5789. box.style.top = this.top + 'px';
  5790. box.style.bottom = '';
  5791. }
  5792. else {
  5793. box.style.top = '';
  5794. box.style.bottom = this.top + 'px';
  5795. }
  5796. };
  5797. /**
  5798. * Repaint a drag area on the left side of the range when the range is selected
  5799. * @protected
  5800. */
  5801. ItemRange.prototype._repaintDragLeft = function () {
  5802. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  5803. // create and show drag area
  5804. var dragLeft = document.createElement('div');
  5805. dragLeft.className = 'drag-left';
  5806. dragLeft.dragLeftItem = this;
  5807. // TODO: this should be redundant?
  5808. Hammer(dragLeft, {
  5809. preventDefault: true
  5810. }).on('drag', function () {
  5811. //console.log('drag left')
  5812. });
  5813. this.dom.box.appendChild(dragLeft);
  5814. this.dom.dragLeft = dragLeft;
  5815. }
  5816. else if (!this.selected && this.dom.dragLeft) {
  5817. // delete drag area
  5818. if (this.dom.dragLeft.parentNode) {
  5819. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5820. }
  5821. this.dom.dragLeft = null;
  5822. }
  5823. };
  5824. /**
  5825. * Repaint a drag area on the right side of the range when the range is selected
  5826. * @protected
  5827. */
  5828. ItemRange.prototype._repaintDragRight = function () {
  5829. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  5830. // create and show drag area
  5831. var dragRight = document.createElement('div');
  5832. dragRight.className = 'drag-right';
  5833. dragRight.dragRightItem = this;
  5834. // TODO: this should be redundant?
  5835. Hammer(dragRight, {
  5836. preventDefault: true
  5837. }).on('drag', function () {
  5838. //console.log('drag right')
  5839. });
  5840. this.dom.box.appendChild(dragRight);
  5841. this.dom.dragRight = dragRight;
  5842. }
  5843. else if (!this.selected && this.dom.dragRight) {
  5844. // delete drag area
  5845. if (this.dom.dragRight.parentNode) {
  5846. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5847. }
  5848. this.dom.dragRight = null;
  5849. }
  5850. };
  5851. /**
  5852. * @constructor ItemRangeOverflow
  5853. * @extends ItemRange
  5854. * @param {Object} data Object containing parameters start, end
  5855. * content, className.
  5856. * @param {Object} [options] Options to set initial property values
  5857. * @param {Object} [defaultOptions] default options
  5858. * // TODO: describe available options
  5859. */
  5860. function ItemRangeOverflow (data, options, defaultOptions) {
  5861. this.props = {
  5862. content: {
  5863. left: 0,
  5864. width: 0
  5865. }
  5866. };
  5867. ItemRange.call(this, data, options, defaultOptions);
  5868. }
  5869. ItemRangeOverflow.prototype = new ItemRange (null);
  5870. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5871. /**
  5872. * Reposition the item horizontally
  5873. * @Override
  5874. */
  5875. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5876. var parentWidth = this.parent.width,
  5877. start = this.defaultOptions.toScreen(this.data.start),
  5878. end = this.defaultOptions.toScreen(this.data.end),
  5879. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5880. contentLeft;
  5881. // limit the width of the this, as browsers cannot draw very wide divs
  5882. if (start < -parentWidth) {
  5883. start = -parentWidth;
  5884. }
  5885. if (end > 2 * parentWidth) {
  5886. end = 2 * parentWidth;
  5887. }
  5888. // when range exceeds left of the window, position the contents at the left of the visible area
  5889. contentLeft = Math.max(-start, 0);
  5890. this.left = start;
  5891. var boxWidth = Math.max(end - start, 1);
  5892. this.width = boxWidth + this.props.content.width;
  5893. // Note: The calculation of width is an optimistic calculation, giving
  5894. // a width which will not change when moving the Timeline
  5895. // So no restacking needed, which is nicer for the eye
  5896. this.dom.box.style.left = this.left + 'px';
  5897. this.dom.box.style.width = boxWidth + 'px';
  5898. this.dom.content.style.left = contentLeft + 'px';
  5899. };
  5900. /**
  5901. * @constructor Group
  5902. * @param {Number | String} groupId
  5903. * @param {Object} data
  5904. * @param {ItemSet} itemSet
  5905. */
  5906. function Group (groupId, data, itemSet) {
  5907. this.groupId = groupId;
  5908. this.itemSet = itemSet;
  5909. this.dom = {};
  5910. this.props = {
  5911. label: {
  5912. width: 0,
  5913. height: 0
  5914. }
  5915. };
  5916. this.items = {}; // items filtered by groupId of this group
  5917. this.visibleItems = []; // items currently visible in window
  5918. this.orderedItems = { // items sorted by start and by end
  5919. byStart: [],
  5920. byEnd: []
  5921. };
  5922. this._create();
  5923. this.setData(data);
  5924. }
  5925. /**
  5926. * Create DOM elements for the group
  5927. * @private
  5928. */
  5929. Group.prototype._create = function() {
  5930. var label = document.createElement('div');
  5931. label.className = 'vlabel';
  5932. this.dom.label = label;
  5933. var inner = document.createElement('div');
  5934. inner.className = 'inner';
  5935. label.appendChild(inner);
  5936. this.dom.inner = inner;
  5937. var foreground = document.createElement('div');
  5938. foreground.className = 'group';
  5939. foreground['timeline-group'] = this;
  5940. this.dom.foreground = foreground;
  5941. this.dom.background = document.createElement('div');
  5942. this.dom.axis = document.createElement('div');
  5943. // create a hidden marker to detect when the Timelines container is attached
  5944. // to the DOM, or the style of a parent of the Timeline is changed from
  5945. // display:none is changed to visible.
  5946. this.dom.marker = document.createElement('div');
  5947. this.dom.marker.style.visibility = 'hidden';
  5948. this.dom.marker.innerHTML = '?';
  5949. this.dom.background.appendChild(this.dom.marker);
  5950. };
  5951. /**
  5952. * Set the group data for this group
  5953. * @param {Object} data Group data, can contain properties content and className
  5954. */
  5955. Group.prototype.setData = function setData(data) {
  5956. // update contents
  5957. var content = data && data.content;
  5958. if (content instanceof Element) {
  5959. this.dom.inner.appendChild(content);
  5960. }
  5961. else if (content != undefined) {
  5962. this.dom.inner.innerHTML = content;
  5963. }
  5964. else {
  5965. this.dom.inner.innerHTML = this.groupId;
  5966. }
  5967. // update className
  5968. var className = data && data.className;
  5969. if (className) {
  5970. util.addClassName(this.dom.label, className);
  5971. }
  5972. };
  5973. /**
  5974. * Get the foreground container element
  5975. * @return {HTMLElement} foreground
  5976. */
  5977. Group.prototype.getForeground = function getForeground() {
  5978. return this.dom.foreground;
  5979. };
  5980. /**
  5981. * Get the background container element
  5982. * @return {HTMLElement} background
  5983. */
  5984. Group.prototype.getBackground = function getBackground() {
  5985. return this.dom.background;
  5986. };
  5987. /**
  5988. * Get the axis container element
  5989. * @return {HTMLElement} axis
  5990. */
  5991. Group.prototype.getAxis = function getAxis() {
  5992. return this.dom.axis;
  5993. };
  5994. /**
  5995. * Get the width of the group label
  5996. * @return {number} width
  5997. */
  5998. Group.prototype.getLabelWidth = function getLabelWidth() {
  5999. return this.props.label.width;
  6000. };
  6001. /**
  6002. * Repaint this group
  6003. * @param {{start: number, end: number}} range
  6004. * @param {{item: number, axis: number}} margin
  6005. * @param {boolean} [restack=false] Force restacking of all items
  6006. * @return {boolean} Returns true if the group is resized
  6007. */
  6008. Group.prototype.repaint = function repaint(range, margin, restack) {
  6009. var resized = false;
  6010. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  6011. // force recalculation of the height of the items when the marker height changed
  6012. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  6013. var markerHeight = this.dom.marker.clientHeight;
  6014. if (markerHeight != this.lastMarkerHeight) {
  6015. this.lastMarkerHeight = markerHeight;
  6016. util.forEach(this.items, function (item) {
  6017. item.dirty = true;
  6018. if (item.displayed) item.repaint();
  6019. });
  6020. restack = true;
  6021. }
  6022. // reposition visible items vertically
  6023. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  6024. stack.stack(this.visibleItems, margin, restack);
  6025. }
  6026. else { // no stacking
  6027. stack.nostack(this.visibleItems, margin);
  6028. }
  6029. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  6030. var item = this.visibleItems[i];
  6031. item.repositionY();
  6032. }
  6033. // recalculate the height of the group
  6034. var height;
  6035. var visibleItems = this.visibleItems;
  6036. if (visibleItems.length) {
  6037. var min = visibleItems[0].top;
  6038. var max = visibleItems[0].top + visibleItems[0].height;
  6039. util.forEach(visibleItems, function (item) {
  6040. min = Math.min(min, item.top);
  6041. max = Math.max(max, (item.top + item.height));
  6042. });
  6043. height = (max - min) + margin.axis + margin.item;
  6044. }
  6045. else {
  6046. height = margin.axis + margin.item;
  6047. }
  6048. height = Math.max(height, this.props.label.height);
  6049. // calculate actual size and position
  6050. var foreground = this.dom.foreground;
  6051. this.top = foreground.offsetTop;
  6052. this.left = foreground.offsetLeft;
  6053. this.width = foreground.offsetWidth;
  6054. resized = util.updateProperty(this, 'height', height) || resized;
  6055. // recalculate size of label
  6056. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  6057. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  6058. // apply new height
  6059. foreground.style.height = height + 'px';
  6060. this.dom.label.style.height = height + 'px';
  6061. return resized;
  6062. };
  6063. /**
  6064. * Show this group: attach to the DOM
  6065. */
  6066. Group.prototype.show = function show() {
  6067. if (!this.dom.label.parentNode) {
  6068. this.itemSet.getLabelSet().appendChild(this.dom.label);
  6069. }
  6070. if (!this.dom.foreground.parentNode) {
  6071. this.itemSet.getForeground().appendChild(this.dom.foreground);
  6072. }
  6073. if (!this.dom.background.parentNode) {
  6074. this.itemSet.getBackground().appendChild(this.dom.background);
  6075. }
  6076. if (!this.dom.axis.parentNode) {
  6077. this.itemSet.getAxis().appendChild(this.dom.axis);
  6078. }
  6079. };
  6080. /**
  6081. * Hide this group: remove from the DOM
  6082. */
  6083. Group.prototype.hide = function hide() {
  6084. var label = this.dom.label;
  6085. if (label.parentNode) {
  6086. label.parentNode.removeChild(label);
  6087. }
  6088. var foreground = this.dom.foreground;
  6089. if (foreground.parentNode) {
  6090. foreground.parentNode.removeChild(foreground);
  6091. }
  6092. var background = this.dom.background;
  6093. if (background.parentNode) {
  6094. background.parentNode.removeChild(background);
  6095. }
  6096. var axis = this.dom.axis;
  6097. if (axis.parentNode) {
  6098. axis.parentNode.removeChild(axis);
  6099. }
  6100. };
  6101. /**
  6102. * Add an item to the group
  6103. * @param {Item} item
  6104. */
  6105. Group.prototype.add = function add(item) {
  6106. this.items[item.id] = item;
  6107. item.setParent(this);
  6108. if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) {
  6109. var range = this.itemSet.range; // TODO: not nice accessing the range like this
  6110. this._checkIfVisible(item, this.visibleItems, range);
  6111. }
  6112. };
  6113. /**
  6114. * Remove an item from the group
  6115. * @param {Item} item
  6116. */
  6117. Group.prototype.remove = function remove(item) {
  6118. delete this.items[item.id];
  6119. item.setParent(this.itemSet);
  6120. // remove from visible items
  6121. var index = this.visibleItems.indexOf(item);
  6122. if (index != -1) this.visibleItems.splice(index, 1);
  6123. // TODO: also remove from ordered items?
  6124. };
  6125. /**
  6126. * Remove an item from the corresponding DataSet
  6127. * @param {Item} item
  6128. */
  6129. Group.prototype.removeFromDataSet = function removeFromDataSet(item) {
  6130. this.itemSet.removeItem(item.id);
  6131. };
  6132. /**
  6133. * Reorder the items
  6134. */
  6135. Group.prototype.order = function order() {
  6136. var array = util.toArray(this.items);
  6137. this.orderedItems.byStart = array;
  6138. this.orderedItems.byEnd = this._constructByEndArray(array);
  6139. stack.orderByStart(this.orderedItems.byStart);
  6140. stack.orderByEnd(this.orderedItems.byEnd);
  6141. };
  6142. /**
  6143. * Create an array containing all items being a range (having an end date)
  6144. * @param {Item[]} array
  6145. * @returns {ItemRange[]}
  6146. * @private
  6147. */
  6148. Group.prototype._constructByEndArray = function _constructByEndArray(array) {
  6149. var endArray = [];
  6150. for (var i = 0; i < array.length; i++) {
  6151. if (array[i] instanceof ItemRange) {
  6152. endArray.push(array[i]);
  6153. }
  6154. }
  6155. return endArray;
  6156. };
  6157. /**
  6158. * Update the visible items
  6159. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  6160. * @param {Item[]} visibleItems The previously visible items.
  6161. * @param {{start: number, end: number}} range Visible range
  6162. * @return {Item[]} visibleItems The new visible items.
  6163. * @private
  6164. */
  6165. Group.prototype._updateVisibleItems = function _updateVisibleItems(orderedItems, visibleItems, range) {
  6166. var initialPosByStart,
  6167. newVisibleItems = [],
  6168. i;
  6169. // first check if the items that were in view previously are still in view.
  6170. // this handles the case for the ItemRange that is both before and after the current one.
  6171. if (visibleItems.length > 0) {
  6172. for (i = 0; i < visibleItems.length; i++) {
  6173. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  6174. }
  6175. }
  6176. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  6177. if (newVisibleItems.length == 0) {
  6178. initialPosByStart = this._binarySearch(orderedItems, range, false);
  6179. }
  6180. else {
  6181. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  6182. }
  6183. // use visible search to find a visible ItemRange (only based on endTime)
  6184. var initialPosByEnd = this._binarySearch(orderedItems, range, true);
  6185. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6186. if (initialPosByStart != -1) {
  6187. for (i = initialPosByStart; i >= 0; i--) {
  6188. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6189. }
  6190. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  6191. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6192. }
  6193. }
  6194. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6195. if (initialPosByEnd != -1) {
  6196. for (i = initialPosByEnd; i >= 0; i--) {
  6197. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6198. }
  6199. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  6200. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6201. }
  6202. }
  6203. return newVisibleItems;
  6204. };
  6205. /**
  6206. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  6207. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  6208. * 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
  6209. * if the time we selected (start or end) is within the current range).
  6210. *
  6211. * 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
  6212. * 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,
  6213. * either the start OR end time has to be in the range.
  6214. *
  6215. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems
  6216. * @param {{start: number, end: number}} range
  6217. * @param {Boolean} byEnd
  6218. * @returns {number}
  6219. * @private
  6220. */
  6221. Group.prototype._binarySearch = function _binarySearch(orderedItems, range, byEnd) {
  6222. var array = [];
  6223. var byTime = byEnd ? 'end' : 'start';
  6224. if (byEnd == true) {array = orderedItems.byEnd; }
  6225. else {array = orderedItems.byStart;}
  6226. var interval = range.end - range.start;
  6227. var found = false;
  6228. var low = 0;
  6229. var high = array.length;
  6230. var guess = Math.floor(0.5*(high+low));
  6231. var newGuess;
  6232. if (high == 0) {guess = -1;}
  6233. else if (high == 1) {
  6234. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6235. guess = 0;
  6236. }
  6237. else {
  6238. guess = -1;
  6239. }
  6240. }
  6241. else {
  6242. high -= 1;
  6243. while (found == false) {
  6244. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6245. found = true;
  6246. }
  6247. else {
  6248. if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low
  6249. low = Math.floor(0.5*(high+low));
  6250. }
  6251. else { // it is too big --> decrease high
  6252. high = Math.floor(0.5*(high+low));
  6253. }
  6254. newGuess = Math.floor(0.5*(high+low));
  6255. // not in list;
  6256. if (guess == newGuess) {
  6257. guess = -1;
  6258. found = true;
  6259. }
  6260. else {
  6261. guess = newGuess;
  6262. }
  6263. }
  6264. }
  6265. }
  6266. return guess;
  6267. };
  6268. /**
  6269. * this function checks if an item is invisible. If it is NOT we make it visible
  6270. * and add it to the global visible items. If it is, return true.
  6271. *
  6272. * @param {Item} item
  6273. * @param {Item[]} visibleItems
  6274. * @param {{start:number, end:number}} range
  6275. * @returns {boolean}
  6276. * @private
  6277. */
  6278. Group.prototype._checkIfInvisible = function _checkIfInvisible(item, visibleItems, range) {
  6279. if (item.isVisible(range)) {
  6280. if (!item.displayed) item.show();
  6281. item.repositionX();
  6282. if (visibleItems.indexOf(item) == -1) {
  6283. visibleItems.push(item);
  6284. }
  6285. return false;
  6286. }
  6287. else {
  6288. return true;
  6289. }
  6290. };
  6291. /**
  6292. * this function is very similar to the _checkIfInvisible() but it does not
  6293. * return booleans, hides the item if it should not be seen and always adds to
  6294. * the visibleItems.
  6295. * this one is for brute forcing and hiding.
  6296. *
  6297. * @param {Item} item
  6298. * @param {Array} visibleItems
  6299. * @param {{start:number, end:number}} range
  6300. * @private
  6301. */
  6302. Group.prototype._checkIfVisible = function _checkIfVisible(item, visibleItems, range) {
  6303. if (item.isVisible(range)) {
  6304. if (!item.displayed) item.show();
  6305. // reposition item horizontally
  6306. item.repositionX();
  6307. visibleItems.push(item);
  6308. }
  6309. else {
  6310. if (item.displayed) item.hide();
  6311. }
  6312. };
  6313. /**
  6314. * Create a timeline visualization
  6315. * @param {HTMLElement} container
  6316. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6317. * @param {Object} [options] See Timeline.setOptions for the available options.
  6318. * @constructor
  6319. */
  6320. function Timeline (container, items, options) {
  6321. // validate arguments
  6322. if (!container) throw new Error('No container element provided');
  6323. var me = this;
  6324. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6325. this.defaultOptions = {
  6326. orientation: 'bottom',
  6327. direction: 'horizontal', // 'horizontal' or 'vertical'
  6328. autoResize: true,
  6329. stack: true,
  6330. editable: {
  6331. updateTime: false,
  6332. updateGroup: false,
  6333. add: false,
  6334. remove: false
  6335. },
  6336. selectable: true,
  6337. start: null,
  6338. end: null,
  6339. min: null,
  6340. max: null,
  6341. zoomMin: 10, // milliseconds
  6342. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6343. // moveable: true, // TODO: option moveable
  6344. // zoomable: true, // TODO: option zoomable
  6345. showMinorLabels: true,
  6346. showMajorLabels: true,
  6347. showCurrentTime: false,
  6348. showCustomTime: false,
  6349. groupOrder: null,
  6350. width: null,
  6351. height: null,
  6352. maxHeight: null,
  6353. minHeight: null,
  6354. type: 'box',
  6355. align: 'center',
  6356. margin: {
  6357. axis: 20,
  6358. item: 10
  6359. },
  6360. padding: 5,
  6361. onAdd: function (item, callback) {
  6362. callback(item);
  6363. },
  6364. onUpdate: function (item, callback) {
  6365. callback(item);
  6366. },
  6367. onMove: function (item, callback) {
  6368. callback(item);
  6369. },
  6370. onRemove: function (item, callback) {
  6371. callback(item);
  6372. }
  6373. };
  6374. this.options = {};
  6375. util.deepExtend(this.options, this.defaultOptions);
  6376. util.deepExtend(this.options, {
  6377. snap: null, // will be specified after timeaxis is created
  6378. toScreen: me._toScreen.bind(me),
  6379. toTime: me._toTime.bind(me)
  6380. });
  6381. // root panel
  6382. var rootOptions = util.extend(Object.create(this.options), {
  6383. height: function () {
  6384. if (me.options.height) {
  6385. // fixed height
  6386. return me.options.height;
  6387. }
  6388. else {
  6389. // auto height
  6390. // TODO: implement a css based solution to automatically have the right hight
  6391. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6392. }
  6393. }
  6394. });
  6395. this.rootPanel = new RootPanel(container, rootOptions);
  6396. // single select (or unselect) when tapping an item
  6397. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6398. // multi select when holding mouse/touch, or on ctrl+click
  6399. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6400. // add item on doubletap
  6401. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6402. // side panel
  6403. var sideOptions = util.extend(Object.create(this.options), {
  6404. top: function () {
  6405. return (sideOptions.orientation == 'top') ? '0' : '';
  6406. },
  6407. bottom: function () {
  6408. return (sideOptions.orientation == 'top') ? '' : '0';
  6409. },
  6410. left: '0',
  6411. right: null,
  6412. height: '100%',
  6413. width: function () {
  6414. if (me.itemSet) {
  6415. return me.itemSet.getLabelsWidth();
  6416. }
  6417. else {
  6418. return 0;
  6419. }
  6420. },
  6421. className: function () {
  6422. return 'side' + (me.groupsData ? '' : ' hidden');
  6423. }
  6424. });
  6425. this.sidePanel = new Panel(sideOptions);
  6426. this.rootPanel.appendChild(this.sidePanel);
  6427. // main panel (contains time axis and itemsets)
  6428. var mainOptions = util.extend(Object.create(this.options), {
  6429. left: function () {
  6430. // we align left to enable a smooth resizing of the window
  6431. return me.sidePanel.width;
  6432. },
  6433. right: null,
  6434. height: '100%',
  6435. width: function () {
  6436. return me.rootPanel.width - me.sidePanel.width;
  6437. },
  6438. className: 'main'
  6439. });
  6440. this.mainPanel = new Panel(mainOptions);
  6441. this.rootPanel.appendChild(this.mainPanel);
  6442. // range
  6443. // TODO: move range inside rootPanel?
  6444. var rangeOptions = Object.create(this.options);
  6445. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6446. this.range.setRange(
  6447. now.clone().add('days', -3).valueOf(),
  6448. now.clone().add('days', 4).valueOf()
  6449. );
  6450. this.range.on('rangechange', function (properties) {
  6451. me.rootPanel.repaint();
  6452. me.emit('rangechange', properties);
  6453. });
  6454. this.range.on('rangechanged', function (properties) {
  6455. me.rootPanel.repaint();
  6456. me.emit('rangechanged', properties);
  6457. });
  6458. // panel with time axis
  6459. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6460. range: this.range,
  6461. left: null,
  6462. top: null,
  6463. width: null,
  6464. height: null
  6465. });
  6466. this.timeAxis = new TimeAxis(timeAxisOptions);
  6467. this.timeAxis.setRange(this.range);
  6468. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6469. this.mainPanel.appendChild(this.timeAxis);
  6470. // content panel (contains itemset(s))
  6471. var contentOptions = util.extend(Object.create(this.options), {
  6472. top: function () {
  6473. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6474. },
  6475. bottom: function () {
  6476. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6477. },
  6478. left: null,
  6479. right: null,
  6480. height: null,
  6481. width: null,
  6482. className: 'content'
  6483. });
  6484. this.contentPanel = new Panel(contentOptions);
  6485. this.mainPanel.appendChild(this.contentPanel);
  6486. // content panel (contains the vertical lines of box items)
  6487. var backgroundOptions = util.extend(Object.create(this.options), {
  6488. top: function () {
  6489. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6490. },
  6491. bottom: function () {
  6492. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6493. },
  6494. left: null,
  6495. right: null,
  6496. height: function () {
  6497. return me.contentPanel.height;
  6498. },
  6499. width: null,
  6500. className: 'background'
  6501. });
  6502. this.backgroundPanel = new Panel(backgroundOptions);
  6503. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6504. // panel with axis holding the dots of item boxes
  6505. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6506. left: 0,
  6507. top: function () {
  6508. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6509. },
  6510. bottom: function () {
  6511. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6512. },
  6513. width: '100%',
  6514. height: 0,
  6515. className: 'axis'
  6516. });
  6517. this.axisPanel = new Panel(axisPanelOptions);
  6518. this.mainPanel.appendChild(this.axisPanel);
  6519. // content panel (contains itemset(s))
  6520. var sideContentOptions = util.extend(Object.create(this.options), {
  6521. top: function () {
  6522. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6523. },
  6524. bottom: function () {
  6525. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6526. },
  6527. left: null,
  6528. right: null,
  6529. height: null,
  6530. width: null,
  6531. className: 'side-content'
  6532. });
  6533. this.sideContentPanel = new Panel(sideContentOptions);
  6534. this.sidePanel.appendChild(this.sideContentPanel);
  6535. // current time bar
  6536. // Note: time bar will be attached in this.setOptions when selected
  6537. this.currentTime = new CurrentTime(this.range, rootOptions);
  6538. // custom time bar
  6539. // Note: time bar will be attached in this.setOptions when selected
  6540. this.customTime = new CustomTime(rootOptions);
  6541. this.customTime.on('timechange', function (time) {
  6542. me.emit('timechange', time);
  6543. });
  6544. this.customTime.on('timechanged', function (time) {
  6545. me.emit('timechanged', time);
  6546. });
  6547. // itemset containing items and groups
  6548. var itemOptions = util.extend(Object.create(this.options), {
  6549. left: null,
  6550. right: null,
  6551. top: null,
  6552. bottom: null,
  6553. width: null,
  6554. height: null
  6555. });
  6556. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  6557. this.itemSet.setRange(this.range);
  6558. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6559. this.contentPanel.appendChild(this.itemSet);
  6560. this.itemsData = null; // DataSet
  6561. this.groupsData = null; // DataSet
  6562. // apply options
  6563. if (options) {
  6564. this.setOptions(options);
  6565. }
  6566. // create itemset
  6567. if (items) {
  6568. this.setItems(items);
  6569. }
  6570. }
  6571. // turn Timeline into an event emitter
  6572. Emitter(Timeline.prototype);
  6573. /**
  6574. * Set options
  6575. * @param {Object} options TODO: describe the available options
  6576. */
  6577. Timeline.prototype.setOptions = function (options) {
  6578. util.deepExtend(this.options, options);
  6579. if ('editable' in options) {
  6580. var isBoolean = typeof options.editable === 'boolean';
  6581. this.options.editable = {
  6582. updateTime: isBoolean ? options.editable : (options.editable.updateTime || false),
  6583. updateGroup: isBoolean ? options.editable : (options.editable.updateGroup || false),
  6584. add: isBoolean ? options.editable : (options.editable.add || false),
  6585. remove: isBoolean ? options.editable : (options.editable.remove || false)
  6586. };
  6587. }
  6588. // force update of range (apply new min/max etc.)
  6589. // both start and end are optional
  6590. this.range.setRange(options.start, options.end);
  6591. if ('editable' in options || 'selectable' in options) {
  6592. if (this.options.selectable) {
  6593. // force update of selection
  6594. this.setSelection(this.getSelection());
  6595. }
  6596. else {
  6597. // remove selection
  6598. this.setSelection([]);
  6599. }
  6600. }
  6601. // force the itemSet to refresh: options like orientation and margins may be changed
  6602. this.itemSet.markDirty();
  6603. // validate the callback functions
  6604. var validateCallback = (function (fn) {
  6605. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6606. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6607. }
  6608. }).bind(this);
  6609. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6610. // add/remove the current time bar
  6611. if (this.options.showCurrentTime) {
  6612. if (!this.mainPanel.hasChild(this.currentTime)) {
  6613. this.mainPanel.appendChild(this.currentTime);
  6614. this.currentTime.start();
  6615. }
  6616. }
  6617. else {
  6618. if (this.mainPanel.hasChild(this.currentTime)) {
  6619. this.currentTime.stop();
  6620. this.mainPanel.removeChild(this.currentTime);
  6621. }
  6622. }
  6623. // add/remove the custom time bar
  6624. if (this.options.showCustomTime) {
  6625. if (!this.mainPanel.hasChild(this.customTime)) {
  6626. this.mainPanel.appendChild(this.customTime);
  6627. }
  6628. }
  6629. else {
  6630. if (this.mainPanel.hasChild(this.customTime)) {
  6631. this.mainPanel.removeChild(this.customTime);
  6632. }
  6633. }
  6634. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  6635. if (options && options.order) {
  6636. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  6637. }
  6638. // repaint everything
  6639. this.rootPanel.repaint();
  6640. };
  6641. /**
  6642. * Set a custom time bar
  6643. * @param {Date} time
  6644. */
  6645. Timeline.prototype.setCustomTime = function (time) {
  6646. if (!this.customTime) {
  6647. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6648. }
  6649. this.customTime.setCustomTime(time);
  6650. };
  6651. /**
  6652. * Retrieve the current custom time.
  6653. * @return {Date} customTime
  6654. */
  6655. Timeline.prototype.getCustomTime = function() {
  6656. if (!this.customTime) {
  6657. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6658. }
  6659. return this.customTime.getCustomTime();
  6660. };
  6661. /**
  6662. * Set items
  6663. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6664. */
  6665. Timeline.prototype.setItems = function(items) {
  6666. var initialLoad = (this.itemsData == null);
  6667. // convert to type DataSet when needed
  6668. var newDataSet;
  6669. if (!items) {
  6670. newDataSet = null;
  6671. }
  6672. else if (items instanceof DataSet || items instanceof DataView) {
  6673. newDataSet = items;
  6674. }
  6675. else {
  6676. // turn an array into a dataset
  6677. newDataSet = new DataSet(items, {
  6678. convert: {
  6679. start: 'Date',
  6680. end: 'Date'
  6681. }
  6682. });
  6683. }
  6684. // set items
  6685. this.itemsData = newDataSet;
  6686. this.itemSet.setItems(newDataSet);
  6687. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6688. this.fit();
  6689. var start = (this.options.start != undefined) ? util.convert(this.options.start, 'Date') : null;
  6690. var end = (this.options.end != undefined) ? util.convert(this.options.end, 'Date') : null;
  6691. this.setWindow(start, end);
  6692. }
  6693. };
  6694. /**
  6695. * Set groups
  6696. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6697. */
  6698. Timeline.prototype.setGroups = function setGroups(groups) {
  6699. // convert to type DataSet when needed
  6700. var newDataSet;
  6701. if (!groups) {
  6702. newDataSet = null;
  6703. }
  6704. else if (groups instanceof DataSet || groups instanceof DataView) {
  6705. newDataSet = groups;
  6706. }
  6707. else {
  6708. // turn an array into a dataset
  6709. newDataSet = new DataSet(groups);
  6710. }
  6711. this.groupsData = newDataSet;
  6712. this.itemSet.setGroups(newDataSet);
  6713. };
  6714. /**
  6715. * Clear the Timeline. By Default, items, groups and options are cleared.
  6716. * Example usage:
  6717. *
  6718. * timeline.clear(); // clear items, groups, and options
  6719. * timeline.clear({options: true}); // clear options only
  6720. *
  6721. * @param {Object} [what] Optionally specify what to clear. By default:
  6722. * {items: true, groups: true, options: true}
  6723. */
  6724. Timeline.prototype.clear = function clear(what) {
  6725. // clear items
  6726. if (!what || what.items) {
  6727. this.setItems(null);
  6728. }
  6729. // clear groups
  6730. if (!what || what.groups) {
  6731. this.setGroups(null);
  6732. }
  6733. // clear options
  6734. if (!what || what.options) {
  6735. this.setOptions(this.defaultOptions);
  6736. }
  6737. };
  6738. /**
  6739. * Set Timeline window such that it fits all items
  6740. */
  6741. Timeline.prototype.fit = function fit() {
  6742. // apply the data range as range
  6743. var dataRange = this.getItemRange();
  6744. // add 5% space on both sides
  6745. var start = dataRange.min;
  6746. var end = dataRange.max;
  6747. if (start != null && end != null) {
  6748. var interval = (end.valueOf() - start.valueOf());
  6749. if (interval <= 0) {
  6750. // prevent an empty interval
  6751. interval = 24 * 60 * 60 * 1000; // 1 day
  6752. }
  6753. start = new Date(start.valueOf() - interval * 0.05);
  6754. end = new Date(end.valueOf() + interval * 0.05);
  6755. }
  6756. // skip range set if there is no start and end date
  6757. if (start === null && end === null) {
  6758. return;
  6759. }
  6760. this.range.setRange(start, end);
  6761. };
  6762. /**
  6763. * Get the data range of the item set.
  6764. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6765. * When no minimum is found, min==null
  6766. * When no maximum is found, max==null
  6767. */
  6768. Timeline.prototype.getItemRange = function getItemRange() {
  6769. // calculate min from start filed
  6770. var itemsData = this.itemsData,
  6771. min = null,
  6772. max = null;
  6773. if (itemsData) {
  6774. // calculate the minimum value of the field 'start'
  6775. var minItem = itemsData.min('start');
  6776. min = minItem ? minItem.start.valueOf() : null;
  6777. // calculate maximum value of fields 'start' and 'end'
  6778. var maxStartItem = itemsData.max('start');
  6779. if (maxStartItem) {
  6780. max = maxStartItem.start.valueOf();
  6781. }
  6782. var maxEndItem = itemsData.max('end');
  6783. if (maxEndItem) {
  6784. if (max == null) {
  6785. max = maxEndItem.end.valueOf();
  6786. }
  6787. else {
  6788. max = Math.max(max, maxEndItem.end.valueOf());
  6789. }
  6790. }
  6791. }
  6792. return {
  6793. min: (min != null) ? new Date(min) : null,
  6794. max: (max != null) ? new Date(max) : null
  6795. };
  6796. };
  6797. /**
  6798. * Set selected items by their id. Replaces the current selection
  6799. * Unknown id's are silently ignored.
  6800. * @param {Array} [ids] An array with zero or more id's of the items to be
  6801. * selected. If ids is an empty array, all items will be
  6802. * unselected.
  6803. */
  6804. Timeline.prototype.setSelection = function setSelection (ids) {
  6805. this.itemSet.setSelection(ids);
  6806. };
  6807. /**
  6808. * Get the selected items by their id
  6809. * @return {Array} ids The ids of the selected items
  6810. */
  6811. Timeline.prototype.getSelection = function getSelection() {
  6812. return this.itemSet.getSelection();
  6813. };
  6814. /**
  6815. * Set the visible window. Both parameters are optional, you can change only
  6816. * start or only end. Syntax:
  6817. *
  6818. * TimeLine.setWindow(start, end)
  6819. * TimeLine.setWindow(range)
  6820. *
  6821. * Where start and end can be a Date, number, or string, and range is an
  6822. * object with properties start and end.
  6823. *
  6824. * @param {Date | Number | String | Object} [start] Start date of visible window
  6825. * @param {Date | Number | String} [end] End date of visible window
  6826. */
  6827. Timeline.prototype.setWindow = function setWindow(start, end) {
  6828. if (arguments.length == 1) {
  6829. var range = arguments[0];
  6830. this.range.setRange(range.start, range.end);
  6831. }
  6832. else {
  6833. this.range.setRange(start, end);
  6834. }
  6835. };
  6836. /**
  6837. * Get the visible window
  6838. * @return {{start: Date, end: Date}} Visible range
  6839. */
  6840. Timeline.prototype.getWindow = function setWindow() {
  6841. var range = this.range.getRange();
  6842. return {
  6843. start: new Date(range.start),
  6844. end: new Date(range.end)
  6845. };
  6846. };
  6847. /**
  6848. * Force a repaint of the Timeline. Can be useful to manually repaint when
  6849. * option autoResize=false
  6850. */
  6851. Timeline.prototype.repaint = function repaint() {
  6852. this.rootPanel.repaint();
  6853. };
  6854. /**
  6855. * Handle selecting/deselecting an item when tapping it
  6856. * @param {Event} event
  6857. * @private
  6858. */
  6859. // TODO: move this function to ItemSet
  6860. Timeline.prototype._onSelectItem = function (event) {
  6861. if (!this.options.selectable) return;
  6862. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6863. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6864. if (ctrlKey || shiftKey) {
  6865. this._onMultiSelectItem(event);
  6866. return;
  6867. }
  6868. var oldSelection = this.getSelection();
  6869. var item = ItemSet.itemFromTarget(event);
  6870. var selection = item ? [item.id] : [];
  6871. this.setSelection(selection);
  6872. var newSelection = this.getSelection();
  6873. // if selection is changed, emit a select event
  6874. if (!util.equalArray(oldSelection, newSelection)) {
  6875. this.emit('select', {
  6876. items: this.getSelection()
  6877. });
  6878. }
  6879. event.stopPropagation();
  6880. };
  6881. /**
  6882. * Handle creation and updates of an item on double tap
  6883. * @param event
  6884. * @private
  6885. */
  6886. Timeline.prototype._onAddItem = function (event) {
  6887. if (!this.options.selectable) return;
  6888. if (!this.options.editable.add) return;
  6889. var me = this,
  6890. item = ItemSet.itemFromTarget(event);
  6891. if (item) {
  6892. // update item
  6893. // execute async handler to update the item (or cancel it)
  6894. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6895. this.options.onUpdate(itemData, function (itemData) {
  6896. if (itemData) {
  6897. me.itemsData.update(itemData);
  6898. }
  6899. });
  6900. }
  6901. else {
  6902. // add item
  6903. var xAbs = vis.util.getAbsoluteLeft(this.contentPanel.frame);
  6904. var x = event.gesture.center.pageX - xAbs;
  6905. var newItem = {
  6906. start: this.timeAxis.snap(this._toTime(x)),
  6907. content: 'new item'
  6908. };
  6909. // when default type is a range, add a default end date to the new item
  6910. if (this.options.type === 'range' || this.options.type == 'rangeoverflow') {
  6911. newItem.end = this.timeAxis.snap(this._toTime(x + this.rootPanel.width / 5));
  6912. }
  6913. var id = util.randomUUID();
  6914. newItem[this.itemsData.fieldId] = id;
  6915. var group = ItemSet.groupFromTarget(event);
  6916. if (group) {
  6917. newItem.group = group.groupId;
  6918. }
  6919. // execute async handler to customize (or cancel) adding an item
  6920. this.options.onAdd(newItem, function (item) {
  6921. if (item) {
  6922. me.itemsData.add(newItem);
  6923. // TODO: need to trigger a repaint?
  6924. }
  6925. });
  6926. }
  6927. };
  6928. /**
  6929. * Handle selecting/deselecting multiple items when holding an item
  6930. * @param {Event} event
  6931. * @private
  6932. */
  6933. // TODO: move this function to ItemSet
  6934. Timeline.prototype._onMultiSelectItem = function (event) {
  6935. if (!this.options.selectable) return;
  6936. var selection,
  6937. item = ItemSet.itemFromTarget(event);
  6938. if (item) {
  6939. // multi select items
  6940. selection = this.getSelection(); // current selection
  6941. var index = selection.indexOf(item.id);
  6942. if (index == -1) {
  6943. // item is not yet selected -> select it
  6944. selection.push(item.id);
  6945. }
  6946. else {
  6947. // item is already selected -> deselect it
  6948. selection.splice(index, 1);
  6949. }
  6950. this.setSelection(selection);
  6951. this.emit('select', {
  6952. items: this.getSelection()
  6953. });
  6954. event.stopPropagation();
  6955. }
  6956. };
  6957. /**
  6958. * Convert a position on screen (pixels) to a datetime
  6959. * @param {int} x Position on the screen in pixels
  6960. * @return {Date} time The datetime the corresponds with given position x
  6961. * @private
  6962. */
  6963. Timeline.prototype._toTime = function _toTime(x) {
  6964. var conversion = this.range.conversion(this.mainPanel.width);
  6965. return new Date(x / conversion.scale + conversion.offset);
  6966. };
  6967. /**
  6968. * Convert a datetime (Date object) into a position on the screen
  6969. * @param {Date} time A date
  6970. * @return {int} x The position on the screen in pixels which corresponds
  6971. * with the given date.
  6972. * @private
  6973. */
  6974. Timeline.prototype._toScreen = function _toScreen(time) {
  6975. var conversion = this.range.conversion(this.mainPanel.width);
  6976. return (time.valueOf() - conversion.offset) * conversion.scale;
  6977. };
  6978. (function(exports) {
  6979. /**
  6980. * Parse a text source containing data in DOT language into a JSON object.
  6981. * The object contains two lists: one with nodes and one with edges.
  6982. *
  6983. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6984. *
  6985. * @param {String} data Text containing a graph in DOT-notation
  6986. * @return {Object} graph An object containing two parameters:
  6987. * {Object[]} nodes
  6988. * {Object[]} edges
  6989. */
  6990. function parseDOT (data) {
  6991. dot = data;
  6992. return parseGraph();
  6993. }
  6994. // token types enumeration
  6995. var TOKENTYPE = {
  6996. NULL : 0,
  6997. DELIMITER : 1,
  6998. IDENTIFIER: 2,
  6999. UNKNOWN : 3
  7000. };
  7001. // map with all delimiters
  7002. var DELIMITERS = {
  7003. '{': true,
  7004. '}': true,
  7005. '[': true,
  7006. ']': true,
  7007. ';': true,
  7008. '=': true,
  7009. ',': true,
  7010. '->': true,
  7011. '--': true
  7012. };
  7013. var dot = ''; // current dot file
  7014. var index = 0; // current index in dot file
  7015. var c = ''; // current token character in expr
  7016. var token = ''; // current token
  7017. var tokenType = TOKENTYPE.NULL; // type of the token
  7018. /**
  7019. * Get the first character from the dot file.
  7020. * The character is stored into the char c. If the end of the dot file is
  7021. * reached, the function puts an empty string in c.
  7022. */
  7023. function first() {
  7024. index = 0;
  7025. c = dot.charAt(0);
  7026. }
  7027. /**
  7028. * Get the next character from the dot file.
  7029. * The character is stored into the char c. If the end of the dot file is
  7030. * reached, the function puts an empty string in c.
  7031. */
  7032. function next() {
  7033. index++;
  7034. c = dot.charAt(index);
  7035. }
  7036. /**
  7037. * Preview the next character from the dot file.
  7038. * @return {String} cNext
  7039. */
  7040. function nextPreview() {
  7041. return dot.charAt(index + 1);
  7042. }
  7043. /**
  7044. * Test whether given character is alphabetic or numeric
  7045. * @param {String} c
  7046. * @return {Boolean} isAlphaNumeric
  7047. */
  7048. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7049. function isAlphaNumeric(c) {
  7050. return regexAlphaNumeric.test(c);
  7051. }
  7052. /**
  7053. * Merge all properties of object b into object b
  7054. * @param {Object} a
  7055. * @param {Object} b
  7056. * @return {Object} a
  7057. */
  7058. function merge (a, b) {
  7059. if (!a) {
  7060. a = {};
  7061. }
  7062. if (b) {
  7063. for (var name in b) {
  7064. if (b.hasOwnProperty(name)) {
  7065. a[name] = b[name];
  7066. }
  7067. }
  7068. }
  7069. return a;
  7070. }
  7071. /**
  7072. * Set a value in an object, where the provided parameter name can be a
  7073. * path with nested parameters. For example:
  7074. *
  7075. * var obj = {a: 2};
  7076. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7077. *
  7078. * @param {Object} obj
  7079. * @param {String} path A parameter name or dot-separated parameter path,
  7080. * like "color.highlight.border".
  7081. * @param {*} value
  7082. */
  7083. function setValue(obj, path, value) {
  7084. var keys = path.split('.');
  7085. var o = obj;
  7086. while (keys.length) {
  7087. var key = keys.shift();
  7088. if (keys.length) {
  7089. // this isn't the end point
  7090. if (!o[key]) {
  7091. o[key] = {};
  7092. }
  7093. o = o[key];
  7094. }
  7095. else {
  7096. // this is the end point
  7097. o[key] = value;
  7098. }
  7099. }
  7100. }
  7101. /**
  7102. * Add a node to a graph object. If there is already a node with
  7103. * the same id, their attributes will be merged.
  7104. * @param {Object} graph
  7105. * @param {Object} node
  7106. */
  7107. function addNode(graph, node) {
  7108. var i, len;
  7109. var current = null;
  7110. // find root graph (in case of subgraph)
  7111. var graphs = [graph]; // list with all graphs from current graph to root graph
  7112. var root = graph;
  7113. while (root.parent) {
  7114. graphs.push(root.parent);
  7115. root = root.parent;
  7116. }
  7117. // find existing node (at root level) by its id
  7118. if (root.nodes) {
  7119. for (i = 0, len = root.nodes.length; i < len; i++) {
  7120. if (node.id === root.nodes[i].id) {
  7121. current = root.nodes[i];
  7122. break;
  7123. }
  7124. }
  7125. }
  7126. if (!current) {
  7127. // this is a new node
  7128. current = {
  7129. id: node.id
  7130. };
  7131. if (graph.node) {
  7132. // clone default attributes
  7133. current.attr = merge(current.attr, graph.node);
  7134. }
  7135. }
  7136. // add node to this (sub)graph and all its parent graphs
  7137. for (i = graphs.length - 1; i >= 0; i--) {
  7138. var g = graphs[i];
  7139. if (!g.nodes) {
  7140. g.nodes = [];
  7141. }
  7142. if (g.nodes.indexOf(current) == -1) {
  7143. g.nodes.push(current);
  7144. }
  7145. }
  7146. // merge attributes
  7147. if (node.attr) {
  7148. current.attr = merge(current.attr, node.attr);
  7149. }
  7150. }
  7151. /**
  7152. * Add an edge to a graph object
  7153. * @param {Object} graph
  7154. * @param {Object} edge
  7155. */
  7156. function addEdge(graph, edge) {
  7157. if (!graph.edges) {
  7158. graph.edges = [];
  7159. }
  7160. graph.edges.push(edge);
  7161. if (graph.edge) {
  7162. var attr = merge({}, graph.edge); // clone default attributes
  7163. edge.attr = merge(attr, edge.attr); // merge attributes
  7164. }
  7165. }
  7166. /**
  7167. * Create an edge to a graph object
  7168. * @param {Object} graph
  7169. * @param {String | Number | Object} from
  7170. * @param {String | Number | Object} to
  7171. * @param {String} type
  7172. * @param {Object | null} attr
  7173. * @return {Object} edge
  7174. */
  7175. function createEdge(graph, from, to, type, attr) {
  7176. var edge = {
  7177. from: from,
  7178. to: to,
  7179. type: type
  7180. };
  7181. if (graph.edge) {
  7182. edge.attr = merge({}, graph.edge); // clone default attributes
  7183. }
  7184. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7185. return edge;
  7186. }
  7187. /**
  7188. * Get next token in the current dot file.
  7189. * The token and token type are available as token and tokenType
  7190. */
  7191. function getToken() {
  7192. tokenType = TOKENTYPE.NULL;
  7193. token = '';
  7194. // skip over whitespaces
  7195. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7196. next();
  7197. }
  7198. do {
  7199. var isComment = false;
  7200. // skip comment
  7201. if (c == '#') {
  7202. // find the previous non-space character
  7203. var i = index - 1;
  7204. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7205. i--;
  7206. }
  7207. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7208. // the # is at the start of a line, this is indeed a line comment
  7209. while (c != '' && c != '\n') {
  7210. next();
  7211. }
  7212. isComment = true;
  7213. }
  7214. }
  7215. if (c == '/' && nextPreview() == '/') {
  7216. // skip line comment
  7217. while (c != '' && c != '\n') {
  7218. next();
  7219. }
  7220. isComment = true;
  7221. }
  7222. if (c == '/' && nextPreview() == '*') {
  7223. // skip block comment
  7224. while (c != '') {
  7225. if (c == '*' && nextPreview() == '/') {
  7226. // end of block comment found. skip these last two characters
  7227. next();
  7228. next();
  7229. break;
  7230. }
  7231. else {
  7232. next();
  7233. }
  7234. }
  7235. isComment = true;
  7236. }
  7237. // skip over whitespaces
  7238. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7239. next();
  7240. }
  7241. }
  7242. while (isComment);
  7243. // check for end of dot file
  7244. if (c == '') {
  7245. // token is still empty
  7246. tokenType = TOKENTYPE.DELIMITER;
  7247. return;
  7248. }
  7249. // check for delimiters consisting of 2 characters
  7250. var c2 = c + nextPreview();
  7251. if (DELIMITERS[c2]) {
  7252. tokenType = TOKENTYPE.DELIMITER;
  7253. token = c2;
  7254. next();
  7255. next();
  7256. return;
  7257. }
  7258. // check for delimiters consisting of 1 character
  7259. if (DELIMITERS[c]) {
  7260. tokenType = TOKENTYPE.DELIMITER;
  7261. token = c;
  7262. next();
  7263. return;
  7264. }
  7265. // check for an identifier (number or string)
  7266. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7267. if (isAlphaNumeric(c) || c == '-') {
  7268. token += c;
  7269. next();
  7270. while (isAlphaNumeric(c)) {
  7271. token += c;
  7272. next();
  7273. }
  7274. if (token == 'false') {
  7275. token = false; // convert to boolean
  7276. }
  7277. else if (token == 'true') {
  7278. token = true; // convert to boolean
  7279. }
  7280. else if (!isNaN(Number(token))) {
  7281. token = Number(token); // convert to number
  7282. }
  7283. tokenType = TOKENTYPE.IDENTIFIER;
  7284. return;
  7285. }
  7286. // check for a string enclosed by double quotes
  7287. if (c == '"') {
  7288. next();
  7289. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7290. token += c;
  7291. if (c == '"') { // skip the escape character
  7292. next();
  7293. }
  7294. next();
  7295. }
  7296. if (c != '"') {
  7297. throw newSyntaxError('End of string " expected');
  7298. }
  7299. next();
  7300. tokenType = TOKENTYPE.IDENTIFIER;
  7301. return;
  7302. }
  7303. // something unknown is found, wrong characters, a syntax error
  7304. tokenType = TOKENTYPE.UNKNOWN;
  7305. while (c != '') {
  7306. token += c;
  7307. next();
  7308. }
  7309. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7310. }
  7311. /**
  7312. * Parse a graph.
  7313. * @returns {Object} graph
  7314. */
  7315. function parseGraph() {
  7316. var graph = {};
  7317. first();
  7318. getToken();
  7319. // optional strict keyword
  7320. if (token == 'strict') {
  7321. graph.strict = true;
  7322. getToken();
  7323. }
  7324. // graph or digraph keyword
  7325. if (token == 'graph' || token == 'digraph') {
  7326. graph.type = token;
  7327. getToken();
  7328. }
  7329. // optional graph id
  7330. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7331. graph.id = token;
  7332. getToken();
  7333. }
  7334. // open angle bracket
  7335. if (token != '{') {
  7336. throw newSyntaxError('Angle bracket { expected');
  7337. }
  7338. getToken();
  7339. // statements
  7340. parseStatements(graph);
  7341. // close angle bracket
  7342. if (token != '}') {
  7343. throw newSyntaxError('Angle bracket } expected');
  7344. }
  7345. getToken();
  7346. // end of file
  7347. if (token !== '') {
  7348. throw newSyntaxError('End of file expected');
  7349. }
  7350. getToken();
  7351. // remove temporary default properties
  7352. delete graph.node;
  7353. delete graph.edge;
  7354. delete graph.graph;
  7355. return graph;
  7356. }
  7357. /**
  7358. * Parse a list with statements.
  7359. * @param {Object} graph
  7360. */
  7361. function parseStatements (graph) {
  7362. while (token !== '' && token != '}') {
  7363. parseStatement(graph);
  7364. if (token == ';') {
  7365. getToken();
  7366. }
  7367. }
  7368. }
  7369. /**
  7370. * Parse a single statement. Can be a an attribute statement, node
  7371. * statement, a series of node statements and edge statements, or a
  7372. * parameter.
  7373. * @param {Object} graph
  7374. */
  7375. function parseStatement(graph) {
  7376. // parse subgraph
  7377. var subgraph = parseSubgraph(graph);
  7378. if (subgraph) {
  7379. // edge statements
  7380. parseEdge(graph, subgraph);
  7381. return;
  7382. }
  7383. // parse an attribute statement
  7384. var attr = parseAttributeStatement(graph);
  7385. if (attr) {
  7386. return;
  7387. }
  7388. // parse node
  7389. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7390. throw newSyntaxError('Identifier expected');
  7391. }
  7392. var id = token; // id can be a string or a number
  7393. getToken();
  7394. if (token == '=') {
  7395. // id statement
  7396. getToken();
  7397. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7398. throw newSyntaxError('Identifier expected');
  7399. }
  7400. graph[id] = token;
  7401. getToken();
  7402. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7403. }
  7404. else {
  7405. parseNodeStatement(graph, id);
  7406. }
  7407. }
  7408. /**
  7409. * Parse a subgraph
  7410. * @param {Object} graph parent graph object
  7411. * @return {Object | null} subgraph
  7412. */
  7413. function parseSubgraph (graph) {
  7414. var subgraph = null;
  7415. // optional subgraph keyword
  7416. if (token == 'subgraph') {
  7417. subgraph = {};
  7418. subgraph.type = 'subgraph';
  7419. getToken();
  7420. // optional graph id
  7421. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7422. subgraph.id = token;
  7423. getToken();
  7424. }
  7425. }
  7426. // open angle bracket
  7427. if (token == '{') {
  7428. getToken();
  7429. if (!subgraph) {
  7430. subgraph = {};
  7431. }
  7432. subgraph.parent = graph;
  7433. subgraph.node = graph.node;
  7434. subgraph.edge = graph.edge;
  7435. subgraph.graph = graph.graph;
  7436. // statements
  7437. parseStatements(subgraph);
  7438. // close angle bracket
  7439. if (token != '}') {
  7440. throw newSyntaxError('Angle bracket } expected');
  7441. }
  7442. getToken();
  7443. // remove temporary default properties
  7444. delete subgraph.node;
  7445. delete subgraph.edge;
  7446. delete subgraph.graph;
  7447. delete subgraph.parent;
  7448. // register at the parent graph
  7449. if (!graph.subgraphs) {
  7450. graph.subgraphs = [];
  7451. }
  7452. graph.subgraphs.push(subgraph);
  7453. }
  7454. return subgraph;
  7455. }
  7456. /**
  7457. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7458. * Available keywords are 'node', 'edge', 'graph'.
  7459. * The previous list with default attributes will be replaced
  7460. * @param {Object} graph
  7461. * @returns {String | null} keyword Returns the name of the parsed attribute
  7462. * (node, edge, graph), or null if nothing
  7463. * is parsed.
  7464. */
  7465. function parseAttributeStatement (graph) {
  7466. // attribute statements
  7467. if (token == 'node') {
  7468. getToken();
  7469. // node attributes
  7470. graph.node = parseAttributeList();
  7471. return 'node';
  7472. }
  7473. else if (token == 'edge') {
  7474. getToken();
  7475. // edge attributes
  7476. graph.edge = parseAttributeList();
  7477. return 'edge';
  7478. }
  7479. else if (token == 'graph') {
  7480. getToken();
  7481. // graph attributes
  7482. graph.graph = parseAttributeList();
  7483. return 'graph';
  7484. }
  7485. return null;
  7486. }
  7487. /**
  7488. * parse a node statement
  7489. * @param {Object} graph
  7490. * @param {String | Number} id
  7491. */
  7492. function parseNodeStatement(graph, id) {
  7493. // node statement
  7494. var node = {
  7495. id: id
  7496. };
  7497. var attr = parseAttributeList();
  7498. if (attr) {
  7499. node.attr = attr;
  7500. }
  7501. addNode(graph, node);
  7502. // edge statements
  7503. parseEdge(graph, id);
  7504. }
  7505. /**
  7506. * Parse an edge or a series of edges
  7507. * @param {Object} graph
  7508. * @param {String | Number} from Id of the from node
  7509. */
  7510. function parseEdge(graph, from) {
  7511. while (token == '->' || token == '--') {
  7512. var to;
  7513. var type = token;
  7514. getToken();
  7515. var subgraph = parseSubgraph(graph);
  7516. if (subgraph) {
  7517. to = subgraph;
  7518. }
  7519. else {
  7520. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7521. throw newSyntaxError('Identifier or subgraph expected');
  7522. }
  7523. to = token;
  7524. addNode(graph, {
  7525. id: to
  7526. });
  7527. getToken();
  7528. }
  7529. // parse edge attributes
  7530. var attr = parseAttributeList();
  7531. // create edge
  7532. var edge = createEdge(graph, from, to, type, attr);
  7533. addEdge(graph, edge);
  7534. from = to;
  7535. }
  7536. }
  7537. /**
  7538. * Parse a set with attributes,
  7539. * for example [label="1.000", shape=solid]
  7540. * @return {Object | null} attr
  7541. */
  7542. function parseAttributeList() {
  7543. var attr = null;
  7544. while (token == '[') {
  7545. getToken();
  7546. attr = {};
  7547. while (token !== '' && token != ']') {
  7548. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7549. throw newSyntaxError('Attribute name expected');
  7550. }
  7551. var name = token;
  7552. getToken();
  7553. if (token != '=') {
  7554. throw newSyntaxError('Equal sign = expected');
  7555. }
  7556. getToken();
  7557. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7558. throw newSyntaxError('Attribute value expected');
  7559. }
  7560. var value = token;
  7561. setValue(attr, name, value); // name can be a path
  7562. getToken();
  7563. if (token ==',') {
  7564. getToken();
  7565. }
  7566. }
  7567. if (token != ']') {
  7568. throw newSyntaxError('Bracket ] expected');
  7569. }
  7570. getToken();
  7571. }
  7572. return attr;
  7573. }
  7574. /**
  7575. * Create a syntax error with extra information on current token and index.
  7576. * @param {String} message
  7577. * @returns {SyntaxError} err
  7578. */
  7579. function newSyntaxError(message) {
  7580. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7581. }
  7582. /**
  7583. * Chop off text after a maximum length
  7584. * @param {String} text
  7585. * @param {Number} maxLength
  7586. * @returns {String}
  7587. */
  7588. function chop (text, maxLength) {
  7589. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7590. }
  7591. /**
  7592. * Execute a function fn for each pair of elements in two arrays
  7593. * @param {Array | *} array1
  7594. * @param {Array | *} array2
  7595. * @param {function} fn
  7596. */
  7597. function forEach2(array1, array2, fn) {
  7598. if (array1 instanceof Array) {
  7599. array1.forEach(function (elem1) {
  7600. if (array2 instanceof Array) {
  7601. array2.forEach(function (elem2) {
  7602. fn(elem1, elem2);
  7603. });
  7604. }
  7605. else {
  7606. fn(elem1, array2);
  7607. }
  7608. });
  7609. }
  7610. else {
  7611. if (array2 instanceof Array) {
  7612. array2.forEach(function (elem2) {
  7613. fn(array1, elem2);
  7614. });
  7615. }
  7616. else {
  7617. fn(array1, array2);
  7618. }
  7619. }
  7620. }
  7621. /**
  7622. * Convert a string containing a graph in DOT language into a map containing
  7623. * with nodes and edges in the format of graph.
  7624. * @param {String} data Text containing a graph in DOT-notation
  7625. * @return {Object} graphData
  7626. */
  7627. function DOTToGraph (data) {
  7628. // parse the DOT file
  7629. var dotData = parseDOT(data);
  7630. var graphData = {
  7631. nodes: [],
  7632. edges: [],
  7633. options: {}
  7634. };
  7635. // copy the nodes
  7636. if (dotData.nodes) {
  7637. dotData.nodes.forEach(function (dotNode) {
  7638. var graphNode = {
  7639. id: dotNode.id,
  7640. label: String(dotNode.label || dotNode.id)
  7641. };
  7642. merge(graphNode, dotNode.attr);
  7643. if (graphNode.image) {
  7644. graphNode.shape = 'image';
  7645. }
  7646. graphData.nodes.push(graphNode);
  7647. });
  7648. }
  7649. // copy the edges
  7650. if (dotData.edges) {
  7651. /**
  7652. * Convert an edge in DOT format to an edge with VisGraph format
  7653. * @param {Object} dotEdge
  7654. * @returns {Object} graphEdge
  7655. */
  7656. function convertEdge(dotEdge) {
  7657. var graphEdge = {
  7658. from: dotEdge.from,
  7659. to: dotEdge.to
  7660. };
  7661. merge(graphEdge, dotEdge.attr);
  7662. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7663. return graphEdge;
  7664. }
  7665. dotData.edges.forEach(function (dotEdge) {
  7666. var from, to;
  7667. if (dotEdge.from instanceof Object) {
  7668. from = dotEdge.from.nodes;
  7669. }
  7670. else {
  7671. from = {
  7672. id: dotEdge.from
  7673. }
  7674. }
  7675. if (dotEdge.to instanceof Object) {
  7676. to = dotEdge.to.nodes;
  7677. }
  7678. else {
  7679. to = {
  7680. id: dotEdge.to
  7681. }
  7682. }
  7683. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7684. dotEdge.from.edges.forEach(function (subEdge) {
  7685. var graphEdge = convertEdge(subEdge);
  7686. graphData.edges.push(graphEdge);
  7687. });
  7688. }
  7689. forEach2(from, to, function (from, to) {
  7690. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7691. var graphEdge = convertEdge(subEdge);
  7692. graphData.edges.push(graphEdge);
  7693. });
  7694. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7695. dotEdge.to.edges.forEach(function (subEdge) {
  7696. var graphEdge = convertEdge(subEdge);
  7697. graphData.edges.push(graphEdge);
  7698. });
  7699. }
  7700. });
  7701. }
  7702. // copy the options
  7703. if (dotData.attr) {
  7704. graphData.options = dotData.attr;
  7705. }
  7706. return graphData;
  7707. }
  7708. // exports
  7709. exports.parseDOT = parseDOT;
  7710. exports.DOTToGraph = DOTToGraph;
  7711. })(typeof util !== 'undefined' ? util : exports);
  7712. /**
  7713. * Canvas shapes used by the Graph
  7714. */
  7715. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7716. /**
  7717. * Draw a circle shape
  7718. */
  7719. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7720. this.beginPath();
  7721. this.arc(x, y, r, 0, 2*Math.PI, false);
  7722. };
  7723. /**
  7724. * Draw a square shape
  7725. * @param {Number} x horizontal center
  7726. * @param {Number} y vertical center
  7727. * @param {Number} r size, width and height of the square
  7728. */
  7729. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7730. this.beginPath();
  7731. this.rect(x - r, y - r, r * 2, r * 2);
  7732. };
  7733. /**
  7734. * Draw a triangle shape
  7735. * @param {Number} x horizontal center
  7736. * @param {Number} y vertical center
  7737. * @param {Number} r radius, half the length of the sides of the triangle
  7738. */
  7739. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7740. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7741. this.beginPath();
  7742. var s = r * 2;
  7743. var s2 = s / 2;
  7744. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7745. var h = Math.sqrt(s * s - s2 * s2); // height
  7746. this.moveTo(x, y - (h - ir));
  7747. this.lineTo(x + s2, y + ir);
  7748. this.lineTo(x - s2, y + ir);
  7749. this.lineTo(x, y - (h - ir));
  7750. this.closePath();
  7751. };
  7752. /**
  7753. * Draw a triangle shape in downward orientation
  7754. * @param {Number} x horizontal center
  7755. * @param {Number} y vertical center
  7756. * @param {Number} r radius
  7757. */
  7758. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7759. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7760. this.beginPath();
  7761. var s = r * 2;
  7762. var s2 = s / 2;
  7763. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7764. var h = Math.sqrt(s * s - s2 * s2); // height
  7765. this.moveTo(x, y + (h - ir));
  7766. this.lineTo(x + s2, y - ir);
  7767. this.lineTo(x - s2, y - ir);
  7768. this.lineTo(x, y + (h - ir));
  7769. this.closePath();
  7770. };
  7771. /**
  7772. * Draw a star shape, a star with 5 points
  7773. * @param {Number} x horizontal center
  7774. * @param {Number} y vertical center
  7775. * @param {Number} r radius, half the length of the sides of the triangle
  7776. */
  7777. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7778. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7779. this.beginPath();
  7780. for (var n = 0; n < 10; n++) {
  7781. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7782. this.lineTo(
  7783. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7784. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7785. );
  7786. }
  7787. this.closePath();
  7788. };
  7789. /**
  7790. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7791. */
  7792. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7793. var r2d = Math.PI/180;
  7794. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7795. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7796. this.beginPath();
  7797. this.moveTo(x+r,y);
  7798. this.lineTo(x+w-r,y);
  7799. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7800. this.lineTo(x+w,y+h-r);
  7801. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7802. this.lineTo(x+r,y+h);
  7803. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7804. this.lineTo(x,y+r);
  7805. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7806. };
  7807. /**
  7808. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7809. */
  7810. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7811. var kappa = .5522848,
  7812. ox = (w / 2) * kappa, // control point offset horizontal
  7813. oy = (h / 2) * kappa, // control point offset vertical
  7814. xe = x + w, // x-end
  7815. ye = y + h, // y-end
  7816. xm = x + w / 2, // x-middle
  7817. ym = y + h / 2; // y-middle
  7818. this.beginPath();
  7819. this.moveTo(x, ym);
  7820. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7821. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7822. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7823. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7824. };
  7825. /**
  7826. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7827. */
  7828. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7829. var f = 1/3;
  7830. var wEllipse = w;
  7831. var hEllipse = h * f;
  7832. var kappa = .5522848,
  7833. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7834. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7835. xe = x + wEllipse, // x-end
  7836. ye = y + hEllipse, // y-end
  7837. xm = x + wEllipse / 2, // x-middle
  7838. ym = y + hEllipse / 2, // y-middle
  7839. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7840. yeb = y + h; // y-end, bottom ellipse
  7841. this.beginPath();
  7842. this.moveTo(xe, ym);
  7843. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7844. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7845. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7846. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7847. this.lineTo(xe, ymb);
  7848. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7849. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7850. this.lineTo(x, ym);
  7851. };
  7852. /**
  7853. * Draw an arrow point (no line)
  7854. */
  7855. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7856. // tail
  7857. var xt = x - length * Math.cos(angle);
  7858. var yt = y - length * Math.sin(angle);
  7859. // inner tail
  7860. // TODO: allow to customize different shapes
  7861. var xi = x - length * 0.9 * Math.cos(angle);
  7862. var yi = y - length * 0.9 * Math.sin(angle);
  7863. // left
  7864. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7865. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7866. // right
  7867. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7868. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7869. this.beginPath();
  7870. this.moveTo(x, y);
  7871. this.lineTo(xl, yl);
  7872. this.lineTo(xi, yi);
  7873. this.lineTo(xr, yr);
  7874. this.closePath();
  7875. };
  7876. /**
  7877. * Sets up the dashedLine functionality for drawing
  7878. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7879. * @author David Jordan
  7880. * @date 2012-08-08
  7881. */
  7882. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7883. if (!dashArray) dashArray=[10,5];
  7884. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7885. var dashCount = dashArray.length;
  7886. this.moveTo(x, y);
  7887. var dx = (x2-x), dy = (y2-y);
  7888. var slope = dy/dx;
  7889. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7890. var dashIndex=0, draw=true;
  7891. while (distRemaining>=0.1){
  7892. var dashLength = dashArray[dashIndex++%dashCount];
  7893. if (dashLength > distRemaining) dashLength = distRemaining;
  7894. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7895. if (dx<0) xStep = -xStep;
  7896. x += xStep;
  7897. y += slope*xStep;
  7898. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7899. distRemaining -= dashLength;
  7900. draw = !draw;
  7901. }
  7902. };
  7903. // TODO: add diamond shape
  7904. }
  7905. /**
  7906. * @class Node
  7907. * A node. A node can be connected to other nodes via one or multiple edges.
  7908. * @param {object} properties An object containing properties for the node. All
  7909. * properties are optional, except for the id.
  7910. * {number} id Id of the node. Required
  7911. * {string} label Text label for the node
  7912. * {number} x Horizontal position of the node
  7913. * {number} y Vertical position of the node
  7914. * {string} shape Node shape, available:
  7915. * "database", "circle", "ellipse",
  7916. * "box", "image", "text", "dot",
  7917. * "star", "triangle", "triangleDown",
  7918. * "square"
  7919. * {string} image An image url
  7920. * {string} title An title text, can be HTML
  7921. * {anytype} group A group name or number
  7922. * @param {Graph.Images} imagelist A list with images. Only needed
  7923. * when the node has an image
  7924. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7925. * retrieving group properties
  7926. * @param {Object} constants An object with default values for
  7927. * example for the color
  7928. *
  7929. */
  7930. function Node(properties, imagelist, grouplist, constants) {
  7931. this.selected = false;
  7932. this.edges = []; // all edges connected to this node
  7933. this.dynamicEdges = [];
  7934. this.reroutedEdges = {};
  7935. this.group = constants.nodes.group;
  7936. this.fontSize = constants.nodes.fontSize;
  7937. this.fontFace = constants.nodes.fontFace;
  7938. this.fontColor = constants.nodes.fontColor;
  7939. this.fontDrawThreshold = 3;
  7940. this.color = constants.nodes.color;
  7941. // set defaults for the properties
  7942. this.id = undefined;
  7943. this.shape = constants.nodes.shape;
  7944. this.image = constants.nodes.image;
  7945. this.x = null;
  7946. this.y = null;
  7947. this.xFixed = false;
  7948. this.yFixed = false;
  7949. this.horizontalAlignLeft = true; // these are for the navigation controls
  7950. this.verticalAlignTop = true; // these are for the navigation controls
  7951. this.radius = constants.nodes.radius;
  7952. this.baseRadiusValue = constants.nodes.radius;
  7953. this.radiusFixed = false;
  7954. this.radiusMin = constants.nodes.radiusMin;
  7955. this.radiusMax = constants.nodes.radiusMax;
  7956. this.level = -1;
  7957. this.preassignedLevel = false;
  7958. this.imagelist = imagelist;
  7959. this.grouplist = grouplist;
  7960. // physics properties
  7961. this.fx = 0.0; // external force x
  7962. this.fy = 0.0; // external force y
  7963. this.vx = 0.0; // velocity x
  7964. this.vy = 0.0; // velocity y
  7965. this.minForce = constants.minForce;
  7966. this.damping = constants.physics.damping;
  7967. this.mass = 1; // kg
  7968. this.fixedData = {x:null,y:null};
  7969. this.setProperties(properties, constants);
  7970. // creating the variables for clustering
  7971. this.resetCluster();
  7972. this.dynamicEdgesLength = 0;
  7973. this.clusterSession = 0;
  7974. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7975. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7976. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7977. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7978. this.growthIndicator = 0;
  7979. // variables to tell the node about the graph.
  7980. this.graphScaleInv = 1;
  7981. this.graphScale = 1;
  7982. this.canvasTopLeft = {"x": -300, "y": -300};
  7983. this.canvasBottomRight = {"x": 300, "y": 300};
  7984. this.parentEdgeId = null;
  7985. }
  7986. /**
  7987. * (re)setting the clustering variables and objects
  7988. */
  7989. Node.prototype.resetCluster = function() {
  7990. // clustering variables
  7991. this.formationScale = undefined; // this is used to determine when to open the cluster
  7992. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7993. this.containedNodes = {};
  7994. this.containedEdges = {};
  7995. this.clusterSessions = [];
  7996. };
  7997. /**
  7998. * Attach a edge to the node
  7999. * @param {Edge} edge
  8000. */
  8001. Node.prototype.attachEdge = function(edge) {
  8002. if (this.edges.indexOf(edge) == -1) {
  8003. this.edges.push(edge);
  8004. }
  8005. if (this.dynamicEdges.indexOf(edge) == -1) {
  8006. this.dynamicEdges.push(edge);
  8007. }
  8008. this.dynamicEdgesLength = this.dynamicEdges.length;
  8009. };
  8010. /**
  8011. * Detach a edge from the node
  8012. * @param {Edge} edge
  8013. */
  8014. Node.prototype.detachEdge = function(edge) {
  8015. var index = this.edges.indexOf(edge);
  8016. if (index != -1) {
  8017. this.edges.splice(index, 1);
  8018. this.dynamicEdges.splice(index, 1);
  8019. }
  8020. this.dynamicEdgesLength = this.dynamicEdges.length;
  8021. };
  8022. /**
  8023. * Set or overwrite properties for the node
  8024. * @param {Object} properties an object with properties
  8025. * @param {Object} constants and object with default, global properties
  8026. */
  8027. Node.prototype.setProperties = function(properties, constants) {
  8028. if (!properties) {
  8029. return;
  8030. }
  8031. this.originalLabel = undefined;
  8032. // basic properties
  8033. if (properties.id !== undefined) {this.id = properties.id;}
  8034. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8035. if (properties.title !== undefined) {this.title = properties.title;}
  8036. if (properties.group !== undefined) {this.group = properties.group;}
  8037. if (properties.x !== undefined) {this.x = properties.x;}
  8038. if (properties.y !== undefined) {this.y = properties.y;}
  8039. if (properties.value !== undefined) {this.value = properties.value;}
  8040. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  8041. // physics
  8042. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8043. // navigation controls properties
  8044. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8045. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8046. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8047. if (this.id === undefined) {
  8048. throw "Node must have an id";
  8049. }
  8050. // copy group properties
  8051. if (this.group) {
  8052. var groupObj = this.grouplist.get(this.group);
  8053. for (var prop in groupObj) {
  8054. if (groupObj.hasOwnProperty(prop)) {
  8055. this[prop] = groupObj[prop];
  8056. }
  8057. }
  8058. }
  8059. // individual shape properties
  8060. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8061. if (properties.image !== undefined) {this.image = properties.image;}
  8062. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8063. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  8064. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8065. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8066. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8067. if (this.image !== undefined && this.image != "") {
  8068. if (this.imagelist) {
  8069. this.imageObj = this.imagelist.load(this.image);
  8070. }
  8071. else {
  8072. throw "No imagelist provided";
  8073. }
  8074. }
  8075. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8076. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8077. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8078. if (this.shape == 'image') {
  8079. this.radiusMin = constants.nodes.widthMin;
  8080. this.radiusMax = constants.nodes.widthMax;
  8081. }
  8082. // choose draw method depending on the shape
  8083. switch (this.shape) {
  8084. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8085. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8086. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8087. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8088. // TODO: add diamond shape
  8089. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8090. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8091. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8092. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8093. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8094. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8095. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8096. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8097. }
  8098. // reset the size of the node, this can be changed
  8099. this._reset();
  8100. };
  8101. /**
  8102. * select this node
  8103. */
  8104. Node.prototype.select = function() {
  8105. this.selected = true;
  8106. this._reset();
  8107. };
  8108. /**
  8109. * unselect this node
  8110. */
  8111. Node.prototype.unselect = function() {
  8112. this.selected = false;
  8113. this._reset();
  8114. };
  8115. /**
  8116. * Reset the calculated size of the node, forces it to recalculate its size
  8117. */
  8118. Node.prototype.clearSizeCache = function() {
  8119. this._reset();
  8120. };
  8121. /**
  8122. * Reset the calculated size of the node, forces it to recalculate its size
  8123. * @private
  8124. */
  8125. Node.prototype._reset = function() {
  8126. this.width = undefined;
  8127. this.height = undefined;
  8128. };
  8129. /**
  8130. * get the title of this node.
  8131. * @return {string} title The title of the node, or undefined when no title
  8132. * has been set.
  8133. */
  8134. Node.prototype.getTitle = function() {
  8135. return typeof this.title === "function" ? this.title() : this.title;
  8136. };
  8137. /**
  8138. * Calculate the distance to the border of the Node
  8139. * @param {CanvasRenderingContext2D} ctx
  8140. * @param {Number} angle Angle in radians
  8141. * @returns {number} distance Distance to the border in pixels
  8142. */
  8143. Node.prototype.distanceToBorder = function (ctx, angle) {
  8144. var borderWidth = 1;
  8145. if (!this.width) {
  8146. this.resize(ctx);
  8147. }
  8148. switch (this.shape) {
  8149. case 'circle':
  8150. case 'dot':
  8151. return this.radius + borderWidth;
  8152. case 'ellipse':
  8153. var a = this.width / 2;
  8154. var b = this.height / 2;
  8155. var w = (Math.sin(angle) * a);
  8156. var h = (Math.cos(angle) * b);
  8157. return a * b / Math.sqrt(w * w + h * h);
  8158. // TODO: implement distanceToBorder for database
  8159. // TODO: implement distanceToBorder for triangle
  8160. // TODO: implement distanceToBorder for triangleDown
  8161. case 'box':
  8162. case 'image':
  8163. case 'text':
  8164. default:
  8165. if (this.width) {
  8166. return Math.min(
  8167. Math.abs(this.width / 2 / Math.cos(angle)),
  8168. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8169. // TODO: reckon with border radius too in case of box
  8170. }
  8171. else {
  8172. return 0;
  8173. }
  8174. }
  8175. // TODO: implement calculation of distance to border for all shapes
  8176. };
  8177. /**
  8178. * Set forces acting on the node
  8179. * @param {number} fx Force in horizontal direction
  8180. * @param {number} fy Force in vertical direction
  8181. */
  8182. Node.prototype._setForce = function(fx, fy) {
  8183. this.fx = fx;
  8184. this.fy = fy;
  8185. };
  8186. /**
  8187. * Add forces acting on the node
  8188. * @param {number} fx Force in horizontal direction
  8189. * @param {number} fy Force in vertical direction
  8190. * @private
  8191. */
  8192. Node.prototype._addForce = function(fx, fy) {
  8193. this.fx += fx;
  8194. this.fy += fy;
  8195. };
  8196. /**
  8197. * Perform one discrete step for the node
  8198. * @param {number} interval Time interval in seconds
  8199. */
  8200. Node.prototype.discreteStep = function(interval) {
  8201. if (!this.xFixed) {
  8202. var dx = this.damping * this.vx; // damping force
  8203. var ax = (this.fx - dx) / this.mass; // acceleration
  8204. this.vx += ax * interval; // velocity
  8205. this.x += this.vx * interval; // position
  8206. }
  8207. if (!this.yFixed) {
  8208. var dy = this.damping * this.vy; // damping force
  8209. var ay = (this.fy - dy) / this.mass; // acceleration
  8210. this.vy += ay * interval; // velocity
  8211. this.y += this.vy * interval; // position
  8212. }
  8213. };
  8214. /**
  8215. * Perform one discrete step for the node
  8216. * @param {number} interval Time interval in seconds
  8217. * @param {number} maxVelocity The speed limit imposed on the velocity
  8218. */
  8219. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8220. if (!this.xFixed) {
  8221. var dx = this.damping * this.vx; // damping force
  8222. var ax = (this.fx - dx) / this.mass; // acceleration
  8223. this.vx += ax * interval; // velocity
  8224. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8225. this.x += this.vx * interval; // position
  8226. }
  8227. else {
  8228. this.fx = 0;
  8229. }
  8230. if (!this.yFixed) {
  8231. var dy = this.damping * this.vy; // damping force
  8232. var ay = (this.fy - dy) / this.mass; // acceleration
  8233. this.vy += ay * interval; // velocity
  8234. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8235. this.y += this.vy * interval; // position
  8236. }
  8237. else {
  8238. this.fy = 0;
  8239. }
  8240. };
  8241. /**
  8242. * Check if this node has a fixed x and y position
  8243. * @return {boolean} true if fixed, false if not
  8244. */
  8245. Node.prototype.isFixed = function() {
  8246. return (this.xFixed && this.yFixed);
  8247. };
  8248. /**
  8249. * Check if this node is moving
  8250. * @param {number} vmin the minimum velocity considered as "moving"
  8251. * @return {boolean} true if moving, false if it has no velocity
  8252. */
  8253. // TODO: replace this method with calculating the kinetic energy
  8254. Node.prototype.isMoving = function(vmin) {
  8255. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8256. };
  8257. /**
  8258. * check if this node is selecte
  8259. * @return {boolean} selected True if node is selected, else false
  8260. */
  8261. Node.prototype.isSelected = function() {
  8262. return this.selected;
  8263. };
  8264. /**
  8265. * Retrieve the value of the node. Can be undefined
  8266. * @return {Number} value
  8267. */
  8268. Node.prototype.getValue = function() {
  8269. return this.value;
  8270. };
  8271. /**
  8272. * Calculate the distance from the nodes location to the given location (x,y)
  8273. * @param {Number} x
  8274. * @param {Number} y
  8275. * @return {Number} value
  8276. */
  8277. Node.prototype.getDistance = function(x, y) {
  8278. var dx = this.x - x,
  8279. dy = this.y - y;
  8280. return Math.sqrt(dx * dx + dy * dy);
  8281. };
  8282. /**
  8283. * Adjust the value range of the node. The node will adjust it's radius
  8284. * based on its value.
  8285. * @param {Number} min
  8286. * @param {Number} max
  8287. */
  8288. Node.prototype.setValueRange = function(min, max) {
  8289. if (!this.radiusFixed && this.value !== undefined) {
  8290. if (max == min) {
  8291. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8292. }
  8293. else {
  8294. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8295. this.radius = (this.value - min) * scale + this.radiusMin;
  8296. }
  8297. }
  8298. this.baseRadiusValue = this.radius;
  8299. };
  8300. /**
  8301. * Draw this node in the given canvas
  8302. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8303. * @param {CanvasRenderingContext2D} ctx
  8304. */
  8305. Node.prototype.draw = function(ctx) {
  8306. throw "Draw method not initialized for node";
  8307. };
  8308. /**
  8309. * Recalculate the size of this node in the given canvas
  8310. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8311. * @param {CanvasRenderingContext2D} ctx
  8312. */
  8313. Node.prototype.resize = function(ctx) {
  8314. throw "Resize method not initialized for node";
  8315. };
  8316. /**
  8317. * Check if this object is overlapping with the provided object
  8318. * @param {Object} obj an object with parameters left, top, right, bottom
  8319. * @return {boolean} True if location is located on node
  8320. */
  8321. Node.prototype.isOverlappingWith = function(obj) {
  8322. return (this.left < obj.right &&
  8323. this.left + this.width > obj.left &&
  8324. this.top < obj.bottom &&
  8325. this.top + this.height > obj.top);
  8326. };
  8327. Node.prototype._resizeImage = function (ctx) {
  8328. // TODO: pre calculate the image size
  8329. if (!this.width || !this.height) { // undefined or 0
  8330. var width, height;
  8331. if (this.value) {
  8332. this.radius = this.baseRadiusValue;
  8333. var scale = this.imageObj.height / this.imageObj.width;
  8334. if (scale !== undefined) {
  8335. width = this.radius || this.imageObj.width;
  8336. height = this.radius * scale || this.imageObj.height;
  8337. }
  8338. else {
  8339. width = 0;
  8340. height = 0;
  8341. }
  8342. }
  8343. else {
  8344. width = this.imageObj.width;
  8345. height = this.imageObj.height;
  8346. }
  8347. this.width = width;
  8348. this.height = height;
  8349. this.growthIndicator = 0;
  8350. if (this.width > 0 && this.height > 0) {
  8351. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8352. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8353. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8354. this.growthIndicator = this.width - width;
  8355. }
  8356. }
  8357. };
  8358. Node.prototype._drawImage = function (ctx) {
  8359. this._resizeImage(ctx);
  8360. this.left = this.x - this.width / 2;
  8361. this.top = this.y - this.height / 2;
  8362. var yLabel;
  8363. if (this.imageObj.width != 0 ) {
  8364. // draw the shade
  8365. if (this.clusterSize > 1) {
  8366. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8367. lineWidth *= this.graphScaleInv;
  8368. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8369. ctx.globalAlpha = 0.5;
  8370. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8371. }
  8372. // draw the image
  8373. ctx.globalAlpha = 1.0;
  8374. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8375. yLabel = this.y + this.height / 2;
  8376. }
  8377. else {
  8378. // image still loading... just draw the label for now
  8379. yLabel = this.y;
  8380. }
  8381. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8382. };
  8383. Node.prototype._resizeBox = function (ctx) {
  8384. if (!this.width) {
  8385. var margin = 5;
  8386. var textSize = this.getTextSize(ctx);
  8387. this.width = textSize.width + 2 * margin;
  8388. this.height = textSize.height + 2 * margin;
  8389. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8390. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8391. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8392. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8393. }
  8394. };
  8395. Node.prototype._drawBox = function (ctx) {
  8396. this._resizeBox(ctx);
  8397. this.left = this.x - this.width / 2;
  8398. this.top = this.y - this.height / 2;
  8399. var clusterLineWidth = 2.5;
  8400. var selectionLineWidth = 2;
  8401. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8402. // draw the outer border
  8403. if (this.clusterSize > 1) {
  8404. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8405. ctx.lineWidth *= this.graphScaleInv;
  8406. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8407. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8408. ctx.stroke();
  8409. }
  8410. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8411. ctx.lineWidth *= this.graphScaleInv;
  8412. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8413. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8414. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8415. ctx.fill();
  8416. ctx.stroke();
  8417. this._label(ctx, this.label, this.x, this.y);
  8418. };
  8419. Node.prototype._resizeDatabase = function (ctx) {
  8420. if (!this.width) {
  8421. var margin = 5;
  8422. var textSize = this.getTextSize(ctx);
  8423. var size = textSize.width + 2 * margin;
  8424. this.width = size;
  8425. this.height = size;
  8426. // scaling used for clustering
  8427. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8428. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8429. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8430. this.growthIndicator = this.width - size;
  8431. }
  8432. };
  8433. Node.prototype._drawDatabase = function (ctx) {
  8434. this._resizeDatabase(ctx);
  8435. this.left = this.x - this.width / 2;
  8436. this.top = this.y - this.height / 2;
  8437. var clusterLineWidth = 2.5;
  8438. var selectionLineWidth = 2;
  8439. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8440. // draw the outer border
  8441. if (this.clusterSize > 1) {
  8442. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8443. ctx.lineWidth *= this.graphScaleInv;
  8444. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8445. 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);
  8446. ctx.stroke();
  8447. }
  8448. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8449. ctx.lineWidth *= this.graphScaleInv;
  8450. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8451. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8452. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8453. ctx.fill();
  8454. ctx.stroke();
  8455. this._label(ctx, this.label, this.x, this.y);
  8456. };
  8457. Node.prototype._resizeCircle = function (ctx) {
  8458. if (!this.width) {
  8459. var margin = 5;
  8460. var textSize = this.getTextSize(ctx);
  8461. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8462. this.radius = diameter / 2;
  8463. this.width = diameter;
  8464. this.height = diameter;
  8465. // scaling used for clustering
  8466. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8467. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8468. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8469. this.growthIndicator = this.radius - 0.5*diameter;
  8470. }
  8471. };
  8472. Node.prototype._drawCircle = function (ctx) {
  8473. this._resizeCircle(ctx);
  8474. this.left = this.x - this.width / 2;
  8475. this.top = this.y - this.height / 2;
  8476. var clusterLineWidth = 2.5;
  8477. var selectionLineWidth = 2;
  8478. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8479. // draw the outer border
  8480. if (this.clusterSize > 1) {
  8481. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8482. ctx.lineWidth *= this.graphScaleInv;
  8483. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8484. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8485. ctx.stroke();
  8486. }
  8487. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8488. ctx.lineWidth *= this.graphScaleInv;
  8489. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8490. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8491. ctx.circle(this.x, this.y, this.radius);
  8492. ctx.fill();
  8493. ctx.stroke();
  8494. this._label(ctx, this.label, this.x, this.y);
  8495. };
  8496. Node.prototype._resizeEllipse = function (ctx) {
  8497. if (!this.width) {
  8498. var textSize = this.getTextSize(ctx);
  8499. this.width = textSize.width * 1.5;
  8500. this.height = textSize.height * 2;
  8501. if (this.width < this.height) {
  8502. this.width = this.height;
  8503. }
  8504. var defaultSize = this.width;
  8505. // scaling used for clustering
  8506. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8507. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8508. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8509. this.growthIndicator = this.width - defaultSize;
  8510. }
  8511. };
  8512. Node.prototype._drawEllipse = function (ctx) {
  8513. this._resizeEllipse(ctx);
  8514. this.left = this.x - this.width / 2;
  8515. this.top = this.y - this.height / 2;
  8516. var clusterLineWidth = 2.5;
  8517. var selectionLineWidth = 2;
  8518. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8519. // draw the outer border
  8520. if (this.clusterSize > 1) {
  8521. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8522. ctx.lineWidth *= this.graphScaleInv;
  8523. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8524. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8525. ctx.stroke();
  8526. }
  8527. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8528. ctx.lineWidth *= this.graphScaleInv;
  8529. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8530. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8531. ctx.ellipse(this.left, this.top, this.width, this.height);
  8532. ctx.fill();
  8533. ctx.stroke();
  8534. this._label(ctx, this.label, this.x, this.y);
  8535. };
  8536. Node.prototype._drawDot = function (ctx) {
  8537. this._drawShape(ctx, 'circle');
  8538. };
  8539. Node.prototype._drawTriangle = function (ctx) {
  8540. this._drawShape(ctx, 'triangle');
  8541. };
  8542. Node.prototype._drawTriangleDown = function (ctx) {
  8543. this._drawShape(ctx, 'triangleDown');
  8544. };
  8545. Node.prototype._drawSquare = function (ctx) {
  8546. this._drawShape(ctx, 'square');
  8547. };
  8548. Node.prototype._drawStar = function (ctx) {
  8549. this._drawShape(ctx, 'star');
  8550. };
  8551. Node.prototype._resizeShape = function (ctx) {
  8552. if (!this.width) {
  8553. this.radius = this.baseRadiusValue;
  8554. var size = 2 * this.radius;
  8555. this.width = size;
  8556. this.height = size;
  8557. // scaling used for clustering
  8558. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8559. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8560. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8561. this.growthIndicator = this.width - size;
  8562. }
  8563. };
  8564. Node.prototype._drawShape = function (ctx, shape) {
  8565. this._resizeShape(ctx);
  8566. this.left = this.x - this.width / 2;
  8567. this.top = this.y - this.height / 2;
  8568. var clusterLineWidth = 2.5;
  8569. var selectionLineWidth = 2;
  8570. var radiusMultiplier = 2;
  8571. // choose draw method depending on the shape
  8572. switch (shape) {
  8573. case 'dot': radiusMultiplier = 2; break;
  8574. case 'square': radiusMultiplier = 2; break;
  8575. case 'triangle': radiusMultiplier = 3; break;
  8576. case 'triangleDown': radiusMultiplier = 3; break;
  8577. case 'star': radiusMultiplier = 4; break;
  8578. }
  8579. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8580. // draw the outer border
  8581. if (this.clusterSize > 1) {
  8582. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8583. ctx.lineWidth *= this.graphScaleInv;
  8584. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8585. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8586. ctx.stroke();
  8587. }
  8588. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8589. ctx.lineWidth *= this.graphScaleInv;
  8590. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8591. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8592. ctx[shape](this.x, this.y, this.radius);
  8593. ctx.fill();
  8594. ctx.stroke();
  8595. if (this.label) {
  8596. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8597. }
  8598. };
  8599. Node.prototype._resizeText = function (ctx) {
  8600. if (!this.width) {
  8601. var margin = 5;
  8602. var textSize = this.getTextSize(ctx);
  8603. this.width = textSize.width + 2 * margin;
  8604. this.height = textSize.height + 2 * margin;
  8605. // scaling used for clustering
  8606. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8607. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8608. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8609. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8610. }
  8611. };
  8612. Node.prototype._drawText = function (ctx) {
  8613. this._resizeText(ctx);
  8614. this.left = this.x - this.width / 2;
  8615. this.top = this.y - this.height / 2;
  8616. this._label(ctx, this.label, this.x, this.y);
  8617. };
  8618. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8619. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8620. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8621. ctx.fillStyle = this.fontColor || "black";
  8622. ctx.textAlign = align || "center";
  8623. ctx.textBaseline = baseline || "middle";
  8624. var lines = text.split('\n'),
  8625. lineCount = lines.length,
  8626. fontSize = (this.fontSize + 4),
  8627. yLine = y + (1 - lineCount) / 2 * fontSize;
  8628. for (var i = 0; i < lineCount; i++) {
  8629. ctx.fillText(lines[i], x, yLine);
  8630. yLine += fontSize;
  8631. }
  8632. }
  8633. };
  8634. Node.prototype.getTextSize = function(ctx) {
  8635. if (this.label !== undefined) {
  8636. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8637. var lines = this.label.split('\n'),
  8638. height = (this.fontSize + 4) * lines.length,
  8639. width = 0;
  8640. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8641. width = Math.max(width, ctx.measureText(lines[i]).width);
  8642. }
  8643. return {"width": width, "height": height};
  8644. }
  8645. else {
  8646. return {"width": 0, "height": 0};
  8647. }
  8648. };
  8649. /**
  8650. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8651. * there is a safety margin of 0.3 * width;
  8652. *
  8653. * @returns {boolean}
  8654. */
  8655. Node.prototype.inArea = function() {
  8656. if (this.width !== undefined) {
  8657. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8658. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8659. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8660. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8661. }
  8662. else {
  8663. return true;
  8664. }
  8665. };
  8666. /**
  8667. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8668. * @returns {boolean}
  8669. */
  8670. Node.prototype.inView = function() {
  8671. return (this.x >= this.canvasTopLeft.x &&
  8672. this.x < this.canvasBottomRight.x &&
  8673. this.y >= this.canvasTopLeft.y &&
  8674. this.y < this.canvasBottomRight.y);
  8675. };
  8676. /**
  8677. * This allows the zoom level of the graph to influence the rendering
  8678. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8679. *
  8680. * @param scale
  8681. * @param canvasTopLeft
  8682. * @param canvasBottomRight
  8683. */
  8684. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8685. this.graphScaleInv = 1.0/scale;
  8686. this.graphScale = scale;
  8687. this.canvasTopLeft = canvasTopLeft;
  8688. this.canvasBottomRight = canvasBottomRight;
  8689. };
  8690. /**
  8691. * This allows the zoom level of the graph to influence the rendering
  8692. *
  8693. * @param scale
  8694. */
  8695. Node.prototype.setScale = function(scale) {
  8696. this.graphScaleInv = 1.0/scale;
  8697. this.graphScale = scale;
  8698. };
  8699. /**
  8700. * set the velocity at 0. Is called when this node is contained in another during clustering
  8701. */
  8702. Node.prototype.clearVelocity = function() {
  8703. this.vx = 0;
  8704. this.vy = 0;
  8705. };
  8706. /**
  8707. * Basic preservation of (kinectic) energy
  8708. *
  8709. * @param massBeforeClustering
  8710. */
  8711. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8712. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8713. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8714. this.vx = Math.sqrt(energyBefore/this.mass);
  8715. energyBefore = this.vy * this.vy * massBeforeClustering;
  8716. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8717. this.vy = Math.sqrt(energyBefore/this.mass);
  8718. };
  8719. /**
  8720. * @class Edge
  8721. *
  8722. * A edge connects two nodes
  8723. * @param {Object} properties Object with properties. Must contain
  8724. * At least properties from and to.
  8725. * Available properties: from (number),
  8726. * to (number), label (string, color (string),
  8727. * width (number), style (string),
  8728. * length (number), title (string)
  8729. * @param {Graph} graph A graph object, used to find and edge to
  8730. * nodes.
  8731. * @param {Object} constants An object with default values for
  8732. * example for the color
  8733. */
  8734. function Edge (properties, graph, constants) {
  8735. if (!graph) {
  8736. throw "No graph provided";
  8737. }
  8738. this.graph = graph;
  8739. // initialize constants
  8740. this.widthMin = constants.edges.widthMin;
  8741. this.widthMax = constants.edges.widthMax;
  8742. // initialize variables
  8743. this.id = undefined;
  8744. this.fromId = undefined;
  8745. this.toId = undefined;
  8746. this.style = constants.edges.style;
  8747. this.title = undefined;
  8748. this.width = constants.edges.width;
  8749. this.value = undefined;
  8750. this.length = constants.physics.springLength;
  8751. this.customLength = false;
  8752. this.selected = false;
  8753. this.smooth = constants.smoothCurves;
  8754. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  8755. this.from = null; // a node
  8756. this.to = null; // a node
  8757. this.via = null; // a temp node
  8758. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8759. // by storing the original information we can revert to the original connection when the cluser is opened.
  8760. this.originalFromId = [];
  8761. this.originalToId = [];
  8762. this.connected = false;
  8763. // Added to support dashed lines
  8764. // David Jordan
  8765. // 2012-08-08
  8766. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8767. this.color = {color:constants.edges.color.color,
  8768. highlight:constants.edges.color.highlight};
  8769. this.widthFixed = false;
  8770. this.lengthFixed = false;
  8771. this.setProperties(properties, constants);
  8772. }
  8773. /**
  8774. * Set or overwrite properties for the edge
  8775. * @param {Object} properties an object with properties
  8776. * @param {Object} constants and object with default, global properties
  8777. */
  8778. Edge.prototype.setProperties = function(properties, constants) {
  8779. if (!properties) {
  8780. return;
  8781. }
  8782. if (properties.from !== undefined) {this.fromId = properties.from;}
  8783. if (properties.to !== undefined) {this.toId = properties.to;}
  8784. if (properties.id !== undefined) {this.id = properties.id;}
  8785. if (properties.style !== undefined) {this.style = properties.style;}
  8786. if (properties.label !== undefined) {this.label = properties.label;}
  8787. if (this.label) {
  8788. this.fontSize = constants.edges.fontSize;
  8789. this.fontFace = constants.edges.fontFace;
  8790. this.fontColor = constants.edges.fontColor;
  8791. this.fontFill = constants.edges.fontFill;
  8792. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8793. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8794. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8795. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8796. }
  8797. if (properties.title !== undefined) {this.title = properties.title;}
  8798. if (properties.width !== undefined) {this.width = properties.width;}
  8799. if (properties.value !== undefined) {this.value = properties.value;}
  8800. if (properties.length !== undefined) {this.length = properties.length;
  8801. this.customLength = true;}
  8802. // scale the arrow
  8803. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
  8804. // Added to support dashed lines
  8805. // David Jordan
  8806. // 2012-08-08
  8807. if (properties.dash) {
  8808. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8809. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8810. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8811. }
  8812. if (properties.color !== undefined) {
  8813. if (util.isString(properties.color)) {
  8814. this.color.color = properties.color;
  8815. this.color.highlight = properties.color;
  8816. }
  8817. else {
  8818. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8819. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8820. }
  8821. }
  8822. // A node is connected when it has a from and to node.
  8823. this.connect();
  8824. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8825. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8826. // set draw method based on style
  8827. switch (this.style) {
  8828. case 'line': this.draw = this._drawLine; break;
  8829. case 'arrow': this.draw = this._drawArrow; break;
  8830. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8831. case 'dash-line': this.draw = this._drawDashLine; break;
  8832. default: this.draw = this._drawLine; break;
  8833. }
  8834. };
  8835. /**
  8836. * Connect an edge to its nodes
  8837. */
  8838. Edge.prototype.connect = function () {
  8839. this.disconnect();
  8840. this.from = this.graph.nodes[this.fromId] || null;
  8841. this.to = this.graph.nodes[this.toId] || null;
  8842. this.connected = (this.from && this.to);
  8843. if (this.connected) {
  8844. this.from.attachEdge(this);
  8845. this.to.attachEdge(this);
  8846. }
  8847. else {
  8848. if (this.from) {
  8849. this.from.detachEdge(this);
  8850. }
  8851. if (this.to) {
  8852. this.to.detachEdge(this);
  8853. }
  8854. }
  8855. };
  8856. /**
  8857. * Disconnect an edge from its nodes
  8858. */
  8859. Edge.prototype.disconnect = function () {
  8860. if (this.from) {
  8861. this.from.detachEdge(this);
  8862. this.from = null;
  8863. }
  8864. if (this.to) {
  8865. this.to.detachEdge(this);
  8866. this.to = null;
  8867. }
  8868. this.connected = false;
  8869. };
  8870. /**
  8871. * get the title of this edge.
  8872. * @return {string} title The title of the edge, or undefined when no title
  8873. * has been set.
  8874. */
  8875. Edge.prototype.getTitle = function() {
  8876. return typeof this.title === "function" ? this.title() : this.title;
  8877. };
  8878. /**
  8879. * Retrieve the value of the edge. Can be undefined
  8880. * @return {Number} value
  8881. */
  8882. Edge.prototype.getValue = function() {
  8883. return this.value;
  8884. };
  8885. /**
  8886. * Adjust the value range of the edge. The edge will adjust it's width
  8887. * based on its value.
  8888. * @param {Number} min
  8889. * @param {Number} max
  8890. */
  8891. Edge.prototype.setValueRange = function(min, max) {
  8892. if (!this.widthFixed && this.value !== undefined) {
  8893. var scale = (this.widthMax - this.widthMin) / (max - min);
  8894. this.width = (this.value - min) * scale + this.widthMin;
  8895. }
  8896. };
  8897. /**
  8898. * Redraw a edge
  8899. * Draw this edge in the given canvas
  8900. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8901. * @param {CanvasRenderingContext2D} ctx
  8902. */
  8903. Edge.prototype.draw = function(ctx) {
  8904. throw "Method draw not initialized in edge";
  8905. };
  8906. /**
  8907. * Check if this object is overlapping with the provided object
  8908. * @param {Object} obj an object with parameters left, top
  8909. * @return {boolean} True if location is located on the edge
  8910. */
  8911. Edge.prototype.isOverlappingWith = function(obj) {
  8912. if (this.connected) {
  8913. var distMax = 10;
  8914. var xFrom = this.from.x;
  8915. var yFrom = this.from.y;
  8916. var xTo = this.to.x;
  8917. var yTo = this.to.y;
  8918. var xObj = obj.left;
  8919. var yObj = obj.top;
  8920. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8921. return (dist < distMax);
  8922. }
  8923. else {
  8924. return false
  8925. }
  8926. };
  8927. /**
  8928. * Redraw a edge as a line
  8929. * Draw this edge in the given canvas
  8930. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8931. * @param {CanvasRenderingContext2D} ctx
  8932. * @private
  8933. */
  8934. Edge.prototype._drawLine = function(ctx) {
  8935. // set style
  8936. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8937. else {ctx.strokeStyle = this.color.color;}
  8938. ctx.lineWidth = this._getLineWidth();
  8939. if (this.from != this.to) {
  8940. // draw line
  8941. this._line(ctx);
  8942. // draw label
  8943. var point;
  8944. if (this.label) {
  8945. if (this.smooth == true) {
  8946. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8947. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8948. point = {x:midpointX, y:midpointY};
  8949. }
  8950. else {
  8951. point = this._pointOnLine(0.5);
  8952. }
  8953. this._label(ctx, this.label, point.x, point.y);
  8954. }
  8955. }
  8956. else {
  8957. var x, y;
  8958. var radius = this.length / 4;
  8959. var node = this.from;
  8960. if (!node.width) {
  8961. node.resize(ctx);
  8962. }
  8963. if (node.width > node.height) {
  8964. x = node.x + node.width / 2;
  8965. y = node.y - radius;
  8966. }
  8967. else {
  8968. x = node.x + radius;
  8969. y = node.y - node.height / 2;
  8970. }
  8971. this._circle(ctx, x, y, radius);
  8972. point = this._pointOnCircle(x, y, radius, 0.5);
  8973. this._label(ctx, this.label, point.x, point.y);
  8974. }
  8975. };
  8976. /**
  8977. * Get the line width of the edge. Depends on width and whether one of the
  8978. * connected nodes is selected.
  8979. * @return {Number} width
  8980. * @private
  8981. */
  8982. Edge.prototype._getLineWidth = function() {
  8983. if (this.selected == true) {
  8984. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8985. }
  8986. else {
  8987. return this.width*this.graphScaleInv;
  8988. }
  8989. };
  8990. /**
  8991. * Draw a line between two nodes
  8992. * @param {CanvasRenderingContext2D} ctx
  8993. * @private
  8994. */
  8995. Edge.prototype._line = function (ctx) {
  8996. // draw a straight line
  8997. ctx.beginPath();
  8998. ctx.moveTo(this.from.x, this.from.y);
  8999. if (this.smooth == true) {
  9000. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9001. }
  9002. else {
  9003. ctx.lineTo(this.to.x, this.to.y);
  9004. }
  9005. ctx.stroke();
  9006. };
  9007. /**
  9008. * Draw a line from a node to itself, a circle
  9009. * @param {CanvasRenderingContext2D} ctx
  9010. * @param {Number} x
  9011. * @param {Number} y
  9012. * @param {Number} radius
  9013. * @private
  9014. */
  9015. Edge.prototype._circle = function (ctx, x, y, radius) {
  9016. // draw a circle
  9017. ctx.beginPath();
  9018. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9019. ctx.stroke();
  9020. };
  9021. /**
  9022. * Draw label with white background and with the middle at (x, y)
  9023. * @param {CanvasRenderingContext2D} ctx
  9024. * @param {String} text
  9025. * @param {Number} x
  9026. * @param {Number} y
  9027. * @private
  9028. */
  9029. Edge.prototype._label = function (ctx, text, x, y) {
  9030. if (text) {
  9031. // TODO: cache the calculated size
  9032. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9033. this.fontSize + "px " + this.fontFace;
  9034. ctx.fillStyle = this.fontFill;
  9035. var width = ctx.measureText(text).width;
  9036. var height = this.fontSize;
  9037. var left = x - width / 2;
  9038. var top = y - height / 2;
  9039. ctx.fillRect(left, top, width, height);
  9040. // draw text
  9041. ctx.fillStyle = this.fontColor || "black";
  9042. ctx.textAlign = "left";
  9043. ctx.textBaseline = "top";
  9044. ctx.fillText(text, left, top);
  9045. }
  9046. };
  9047. /**
  9048. * Redraw a edge as a dashed line
  9049. * Draw this edge in the given canvas
  9050. * @author David Jordan
  9051. * @date 2012-08-08
  9052. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9053. * @param {CanvasRenderingContext2D} ctx
  9054. * @private
  9055. */
  9056. Edge.prototype._drawDashLine = function(ctx) {
  9057. // set style
  9058. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9059. else {ctx.strokeStyle = this.color.color;}
  9060. ctx.lineWidth = this._getLineWidth();
  9061. // only firefox and chrome support this method, else we use the legacy one.
  9062. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9063. ctx.beginPath();
  9064. ctx.moveTo(this.from.x, this.from.y);
  9065. // configure the dash pattern
  9066. var pattern = [0];
  9067. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9068. pattern = [this.dash.length,this.dash.gap];
  9069. }
  9070. else {
  9071. pattern = [5,5];
  9072. }
  9073. // set dash settings for chrome or firefox
  9074. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9075. ctx.setLineDash(pattern);
  9076. ctx.lineDashOffset = 0;
  9077. } else { //Firefox
  9078. ctx.mozDash = pattern;
  9079. ctx.mozDashOffset = 0;
  9080. }
  9081. // draw the line
  9082. if (this.smooth == true) {
  9083. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9084. }
  9085. else {
  9086. ctx.lineTo(this.to.x, this.to.y);
  9087. }
  9088. ctx.stroke();
  9089. // restore the dash settings.
  9090. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9091. ctx.setLineDash([0]);
  9092. ctx.lineDashOffset = 0;
  9093. } else { //Firefox
  9094. ctx.mozDash = [0];
  9095. ctx.mozDashOffset = 0;
  9096. }
  9097. }
  9098. else { // unsupporting smooth lines
  9099. // draw dashed line
  9100. ctx.beginPath();
  9101. ctx.lineCap = 'round';
  9102. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9103. {
  9104. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9105. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9106. }
  9107. 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
  9108. {
  9109. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9110. [this.dash.length,this.dash.gap]);
  9111. }
  9112. else //If all else fails draw a line
  9113. {
  9114. ctx.moveTo(this.from.x, this.from.y);
  9115. ctx.lineTo(this.to.x, this.to.y);
  9116. }
  9117. ctx.stroke();
  9118. }
  9119. // draw label
  9120. if (this.label) {
  9121. var point;
  9122. if (this.smooth == true) {
  9123. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9124. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9125. point = {x:midpointX, y:midpointY};
  9126. }
  9127. else {
  9128. point = this._pointOnLine(0.5);
  9129. }
  9130. this._label(ctx, this.label, point.x, point.y);
  9131. }
  9132. };
  9133. /**
  9134. * Get a point on a line
  9135. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9136. * @return {Object} point
  9137. * @private
  9138. */
  9139. Edge.prototype._pointOnLine = function (percentage) {
  9140. return {
  9141. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9142. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9143. }
  9144. };
  9145. /**
  9146. * Get a point on a circle
  9147. * @param {Number} x
  9148. * @param {Number} y
  9149. * @param {Number} radius
  9150. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9151. * @return {Object} point
  9152. * @private
  9153. */
  9154. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9155. var angle = (percentage - 3/8) * 2 * Math.PI;
  9156. return {
  9157. x: x + radius * Math.cos(angle),
  9158. y: y - radius * Math.sin(angle)
  9159. }
  9160. };
  9161. /**
  9162. * Redraw a edge as a line with an arrow halfway the line
  9163. * Draw this edge in the given canvas
  9164. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9165. * @param {CanvasRenderingContext2D} ctx
  9166. * @private
  9167. */
  9168. Edge.prototype._drawArrowCenter = function(ctx) {
  9169. var point;
  9170. // set style
  9171. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9172. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9173. ctx.lineWidth = this._getLineWidth();
  9174. if (this.from != this.to) {
  9175. // draw line
  9176. this._line(ctx);
  9177. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9178. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9179. // draw an arrow halfway the line
  9180. if (this.smooth == true) {
  9181. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9182. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9183. point = {x:midpointX, y:midpointY};
  9184. }
  9185. else {
  9186. point = this._pointOnLine(0.5);
  9187. }
  9188. ctx.arrow(point.x, point.y, angle, length);
  9189. ctx.fill();
  9190. ctx.stroke();
  9191. // draw label
  9192. if (this.label) {
  9193. this._label(ctx, this.label, point.x, point.y);
  9194. }
  9195. }
  9196. else {
  9197. // draw circle
  9198. var x, y;
  9199. var radius = 0.25 * Math.max(100,this.length);
  9200. var node = this.from;
  9201. if (!node.width) {
  9202. node.resize(ctx);
  9203. }
  9204. if (node.width > node.height) {
  9205. x = node.x + node.width * 0.5;
  9206. y = node.y - radius;
  9207. }
  9208. else {
  9209. x = node.x + radius;
  9210. y = node.y - node.height * 0.5;
  9211. }
  9212. this._circle(ctx, x, y, radius);
  9213. // draw all arrows
  9214. var angle = 0.2 * Math.PI;
  9215. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9216. point = this._pointOnCircle(x, y, radius, 0.5);
  9217. ctx.arrow(point.x, point.y, angle, length);
  9218. ctx.fill();
  9219. ctx.stroke();
  9220. // draw label
  9221. if (this.label) {
  9222. point = this._pointOnCircle(x, y, radius, 0.5);
  9223. this._label(ctx, this.label, point.x, point.y);
  9224. }
  9225. }
  9226. };
  9227. /**
  9228. * Redraw a edge as a line with an arrow
  9229. * Draw this edge in the given canvas
  9230. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9231. * @param {CanvasRenderingContext2D} ctx
  9232. * @private
  9233. */
  9234. Edge.prototype._drawArrow = function(ctx) {
  9235. // set style
  9236. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9237. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9238. ctx.lineWidth = this._getLineWidth();
  9239. var angle, length;
  9240. //draw a line
  9241. if (this.from != this.to) {
  9242. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9243. var dx = (this.to.x - this.from.x);
  9244. var dy = (this.to.y - this.from.y);
  9245. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9246. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9247. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9248. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9249. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9250. if (this.smooth == true) {
  9251. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9252. dx = (this.to.x - this.via.x);
  9253. dy = (this.to.y - this.via.y);
  9254. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9255. }
  9256. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9257. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9258. var xTo,yTo;
  9259. if (this.smooth == true) {
  9260. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9261. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9262. }
  9263. else {
  9264. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9265. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9266. }
  9267. ctx.beginPath();
  9268. ctx.moveTo(xFrom,yFrom);
  9269. if (this.smooth == true) {
  9270. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9271. }
  9272. else {
  9273. ctx.lineTo(xTo, yTo);
  9274. }
  9275. ctx.stroke();
  9276. // draw arrow at the end of the line
  9277. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9278. ctx.arrow(xTo, yTo, angle, length);
  9279. ctx.fill();
  9280. ctx.stroke();
  9281. // draw label
  9282. if (this.label) {
  9283. var point;
  9284. if (this.smooth == true) {
  9285. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9286. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9287. point = {x:midpointX, y:midpointY};
  9288. }
  9289. else {
  9290. point = this._pointOnLine(0.5);
  9291. }
  9292. this._label(ctx, this.label, point.x, point.y);
  9293. }
  9294. }
  9295. else {
  9296. // draw circle
  9297. var node = this.from;
  9298. var x, y, arrow;
  9299. var radius = 0.25 * Math.max(100,this.length);
  9300. if (!node.width) {
  9301. node.resize(ctx);
  9302. }
  9303. if (node.width > node.height) {
  9304. x = node.x + node.width * 0.5;
  9305. y = node.y - radius;
  9306. arrow = {
  9307. x: x,
  9308. y: node.y,
  9309. angle: 0.9 * Math.PI
  9310. };
  9311. }
  9312. else {
  9313. x = node.x + radius;
  9314. y = node.y - node.height * 0.5;
  9315. arrow = {
  9316. x: node.x,
  9317. y: y,
  9318. angle: 0.6 * Math.PI
  9319. };
  9320. }
  9321. ctx.beginPath();
  9322. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9323. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9324. ctx.stroke();
  9325. // draw all arrows
  9326. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9327. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9328. ctx.fill();
  9329. ctx.stroke();
  9330. // draw label
  9331. if (this.label) {
  9332. point = this._pointOnCircle(x, y, radius, 0.5);
  9333. this._label(ctx, this.label, point.x, point.y);
  9334. }
  9335. }
  9336. };
  9337. /**
  9338. * Calculate the distance between a point (x3,y3) and a line segment from
  9339. * (x1,y1) to (x2,y2).
  9340. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9341. * @param {number} x1
  9342. * @param {number} y1
  9343. * @param {number} x2
  9344. * @param {number} y2
  9345. * @param {number} x3
  9346. * @param {number} y3
  9347. * @private
  9348. */
  9349. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9350. if (this.smooth == true) {
  9351. var minDistance = 1e9;
  9352. var i,t,x,y,dx,dy;
  9353. for (i = 0; i < 10; i++) {
  9354. t = 0.1*i;
  9355. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9356. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9357. dx = Math.abs(x3-x);
  9358. dy = Math.abs(y3-y);
  9359. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9360. }
  9361. return minDistance
  9362. }
  9363. else {
  9364. var px = x2-x1,
  9365. py = y2-y1,
  9366. something = px*px + py*py,
  9367. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9368. if (u > 1) {
  9369. u = 1;
  9370. }
  9371. else if (u < 0) {
  9372. u = 0;
  9373. }
  9374. var x = x1 + u * px,
  9375. y = y1 + u * py,
  9376. dx = x - x3,
  9377. dy = y - y3;
  9378. //# Note: If the actual distance does not matter,
  9379. //# if you only want to compare what this function
  9380. //# returns to other results of this function, you
  9381. //# can just return the squared distance instead
  9382. //# (i.e. remove the sqrt) to gain a little performance
  9383. return Math.sqrt(dx*dx + dy*dy);
  9384. }
  9385. };
  9386. /**
  9387. * This allows the zoom level of the graph to influence the rendering
  9388. *
  9389. * @param scale
  9390. */
  9391. Edge.prototype.setScale = function(scale) {
  9392. this.graphScaleInv = 1.0/scale;
  9393. };
  9394. Edge.prototype.select = function() {
  9395. this.selected = true;
  9396. };
  9397. Edge.prototype.unselect = function() {
  9398. this.selected = false;
  9399. };
  9400. Edge.prototype.positionBezierNode = function() {
  9401. if (this.via !== null) {
  9402. this.via.x = 0.5 * (this.from.x + this.to.x);
  9403. this.via.y = 0.5 * (this.from.y + this.to.y);
  9404. }
  9405. };
  9406. /**
  9407. * Popup is a class to create a popup window with some text
  9408. * @param {Element} container The container object.
  9409. * @param {Number} [x]
  9410. * @param {Number} [y]
  9411. * @param {String} [text]
  9412. * @param {Object} [style] An object containing borderColor,
  9413. * backgroundColor, etc.
  9414. */
  9415. function Popup(container, x, y, text, style) {
  9416. if (container) {
  9417. this.container = container;
  9418. }
  9419. else {
  9420. this.container = document.body;
  9421. }
  9422. // x, y and text are optional, see if a style object was passed in their place
  9423. if (style === undefined) {
  9424. if (typeof x === "object") {
  9425. style = x;
  9426. x = undefined;
  9427. } else if (typeof text === "object") {
  9428. style = text;
  9429. text = undefined;
  9430. } else {
  9431. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9432. style = {
  9433. fontColor: 'black',
  9434. fontSize: 14, // px
  9435. fontFace: 'verdana',
  9436. color: {
  9437. border: '#666',
  9438. background: '#FFFFC6'
  9439. }
  9440. }
  9441. }
  9442. }
  9443. this.x = 0;
  9444. this.y = 0;
  9445. this.padding = 5;
  9446. if (x !== undefined && y !== undefined ) {
  9447. this.setPosition(x, y);
  9448. }
  9449. if (text !== undefined) {
  9450. this.setText(text);
  9451. }
  9452. // create the frame
  9453. this.frame = document.createElement("div");
  9454. var styleAttr = this.frame.style;
  9455. styleAttr.position = "absolute";
  9456. styleAttr.visibility = "hidden";
  9457. styleAttr.border = "1px solid " + style.color.border;
  9458. styleAttr.color = style.fontColor;
  9459. styleAttr.fontSize = style.fontSize + "px";
  9460. styleAttr.fontFamily = style.fontFace;
  9461. styleAttr.padding = this.padding + "px";
  9462. styleAttr.backgroundColor = style.color.background;
  9463. styleAttr.borderRadius = "3px";
  9464. styleAttr.MozBorderRadius = "3px";
  9465. styleAttr.WebkitBorderRadius = "3px";
  9466. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9467. styleAttr.whiteSpace = "nowrap";
  9468. this.container.appendChild(this.frame);
  9469. }
  9470. /**
  9471. * @param {number} x Horizontal position of the popup window
  9472. * @param {number} y Vertical position of the popup window
  9473. */
  9474. Popup.prototype.setPosition = function(x, y) {
  9475. this.x = parseInt(x);
  9476. this.y = parseInt(y);
  9477. };
  9478. /**
  9479. * Set the text for the popup window. This can be HTML code
  9480. * @param {string} text
  9481. */
  9482. Popup.prototype.setText = function(text) {
  9483. this.frame.innerHTML = text;
  9484. };
  9485. /**
  9486. * Show the popup window
  9487. * @param {boolean} show Optional. Show or hide the window
  9488. */
  9489. Popup.prototype.show = function (show) {
  9490. if (show === undefined) {
  9491. show = true;
  9492. }
  9493. if (show) {
  9494. var height = this.frame.clientHeight;
  9495. var width = this.frame.clientWidth;
  9496. var maxHeight = this.frame.parentNode.clientHeight;
  9497. var maxWidth = this.frame.parentNode.clientWidth;
  9498. var top = (this.y - height);
  9499. if (top + height + this.padding > maxHeight) {
  9500. top = maxHeight - height - this.padding;
  9501. }
  9502. if (top < this.padding) {
  9503. top = this.padding;
  9504. }
  9505. var left = this.x;
  9506. if (left + width + this.padding > maxWidth) {
  9507. left = maxWidth - width - this.padding;
  9508. }
  9509. if (left < this.padding) {
  9510. left = this.padding;
  9511. }
  9512. this.frame.style.left = left + "px";
  9513. this.frame.style.top = top + "px";
  9514. this.frame.style.visibility = "visible";
  9515. }
  9516. else {
  9517. this.hide();
  9518. }
  9519. };
  9520. /**
  9521. * Hide the popup window
  9522. */
  9523. Popup.prototype.hide = function () {
  9524. this.frame.style.visibility = "hidden";
  9525. };
  9526. /**
  9527. * @class Groups
  9528. * This class can store groups and properties specific for groups.
  9529. */
  9530. function Groups() {
  9531. this.clear();
  9532. this.defaultIndex = 0;
  9533. }
  9534. /**
  9535. * default constants for group colors
  9536. */
  9537. Groups.DEFAULT = [
  9538. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9539. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9540. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9541. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9542. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9543. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9544. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9545. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9546. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9547. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9548. ];
  9549. /**
  9550. * Clear all groups
  9551. */
  9552. Groups.prototype.clear = function () {
  9553. this.groups = {};
  9554. this.groups.length = function()
  9555. {
  9556. var i = 0;
  9557. for ( var p in this ) {
  9558. if (this.hasOwnProperty(p)) {
  9559. i++;
  9560. }
  9561. }
  9562. return i;
  9563. }
  9564. };
  9565. /**
  9566. * get group properties of a groupname. If groupname is not found, a new group
  9567. * is added.
  9568. * @param {*} groupname Can be a number, string, Date, etc.
  9569. * @return {Object} group The created group, containing all group properties
  9570. */
  9571. Groups.prototype.get = function (groupname) {
  9572. var group = this.groups[groupname];
  9573. if (group == undefined) {
  9574. // create new group
  9575. var index = this.defaultIndex % Groups.DEFAULT.length;
  9576. this.defaultIndex++;
  9577. group = {};
  9578. group.color = Groups.DEFAULT[index];
  9579. this.groups[groupname] = group;
  9580. }
  9581. return group;
  9582. };
  9583. /**
  9584. * Add a custom group style
  9585. * @param {String} groupname
  9586. * @param {Object} style An object containing borderColor,
  9587. * backgroundColor, etc.
  9588. * @return {Object} group The created group object
  9589. */
  9590. Groups.prototype.add = function (groupname, style) {
  9591. this.groups[groupname] = style;
  9592. if (style.color) {
  9593. style.color = util.parseColor(style.color);
  9594. }
  9595. return style;
  9596. };
  9597. /**
  9598. * @class Images
  9599. * This class loads images and keeps them stored.
  9600. */
  9601. function Images() {
  9602. this.images = {};
  9603. this.callback = undefined;
  9604. }
  9605. /**
  9606. * Set an onload callback function. This will be called each time an image
  9607. * is loaded
  9608. * @param {function} callback
  9609. */
  9610. Images.prototype.setOnloadCallback = function(callback) {
  9611. this.callback = callback;
  9612. };
  9613. /**
  9614. *
  9615. * @param {string} url Url of the image
  9616. * @return {Image} img The image object
  9617. */
  9618. Images.prototype.load = function(url) {
  9619. var img = this.images[url];
  9620. if (img == undefined) {
  9621. // create the image
  9622. var images = this;
  9623. img = new Image();
  9624. this.images[url] = img;
  9625. img.onload = function() {
  9626. if (images.callback) {
  9627. images.callback(this);
  9628. }
  9629. };
  9630. img.src = url;
  9631. }
  9632. return img;
  9633. };
  9634. /**
  9635. * Created by Alex on 2/6/14.
  9636. */
  9637. var physicsMixin = {
  9638. /**
  9639. * Toggling barnes Hut calculation on and off.
  9640. *
  9641. * @private
  9642. */
  9643. _toggleBarnesHut: function () {
  9644. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9645. this._loadSelectedForceSolver();
  9646. this.moving = true;
  9647. this.start();
  9648. },
  9649. /**
  9650. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9651. *
  9652. * @private
  9653. */
  9654. _loadSelectedForceSolver: function () {
  9655. // this overloads the this._calculateNodeForces
  9656. if (this.constants.physics.barnesHut.enabled == true) {
  9657. this._clearMixin(repulsionMixin);
  9658. this._clearMixin(hierarchalRepulsionMixin);
  9659. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9660. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9661. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9662. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9663. this._loadMixin(barnesHutMixin);
  9664. }
  9665. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9666. this._clearMixin(barnesHutMixin);
  9667. this._clearMixin(repulsionMixin);
  9668. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9669. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9670. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9671. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9672. this._loadMixin(hierarchalRepulsionMixin);
  9673. }
  9674. else {
  9675. this._clearMixin(barnesHutMixin);
  9676. this._clearMixin(hierarchalRepulsionMixin);
  9677. this.barnesHutTree = undefined;
  9678. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9679. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9680. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9681. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9682. this._loadMixin(repulsionMixin);
  9683. }
  9684. },
  9685. /**
  9686. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9687. * if there is more than one node. If it is just one node, we dont calculate anything.
  9688. *
  9689. * @private
  9690. */
  9691. _initializeForceCalculation: function () {
  9692. // stop calculation if there is only one node
  9693. if (this.nodeIndices.length == 1) {
  9694. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9695. }
  9696. else {
  9697. // if there are too many nodes on screen, we cluster without repositioning
  9698. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9699. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9700. }
  9701. // we now start the force calculation
  9702. this._calculateForces();
  9703. }
  9704. },
  9705. /**
  9706. * Calculate the external forces acting on the nodes
  9707. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9708. * @private
  9709. */
  9710. _calculateForces: function () {
  9711. // Gravity is required to keep separated groups from floating off
  9712. // the forces are reset to zero in this loop by using _setForce instead
  9713. // of _addForce
  9714. this._calculateGravitationalForces();
  9715. this._calculateNodeForces();
  9716. if (this.constants.smoothCurves == true) {
  9717. this._calculateSpringForcesWithSupport();
  9718. }
  9719. else {
  9720. this._calculateSpringForces();
  9721. }
  9722. },
  9723. /**
  9724. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9725. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9726. * This function joins the datanodes and invisible (called support) nodes into one object.
  9727. * We do this so we do not contaminate this.nodes with the support nodes.
  9728. *
  9729. * @private
  9730. */
  9731. _updateCalculationNodes: function () {
  9732. if (this.constants.smoothCurves == true) {
  9733. this.calculationNodes = {};
  9734. this.calculationNodeIndices = [];
  9735. for (var nodeId in this.nodes) {
  9736. if (this.nodes.hasOwnProperty(nodeId)) {
  9737. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9738. }
  9739. }
  9740. var supportNodes = this.sectors['support']['nodes'];
  9741. for (var supportNodeId in supportNodes) {
  9742. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9743. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9744. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9745. }
  9746. else {
  9747. supportNodes[supportNodeId]._setForce(0, 0);
  9748. }
  9749. }
  9750. }
  9751. for (var idx in this.calculationNodes) {
  9752. if (this.calculationNodes.hasOwnProperty(idx)) {
  9753. this.calculationNodeIndices.push(idx);
  9754. }
  9755. }
  9756. }
  9757. else {
  9758. this.calculationNodes = this.nodes;
  9759. this.calculationNodeIndices = this.nodeIndices;
  9760. }
  9761. },
  9762. /**
  9763. * this function applies the central gravity effect to keep groups from floating off
  9764. *
  9765. * @private
  9766. */
  9767. _calculateGravitationalForces: function () {
  9768. var dx, dy, distance, node, i;
  9769. var nodes = this.calculationNodes;
  9770. var gravity = this.constants.physics.centralGravity;
  9771. var gravityForce = 0;
  9772. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9773. node = nodes[this.calculationNodeIndices[i]];
  9774. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9775. // gravity does not apply when we are in a pocket sector
  9776. if (this._sector() == "default" && gravity != 0) {
  9777. dx = -node.x;
  9778. dy = -node.y;
  9779. distance = Math.sqrt(dx * dx + dy * dy);
  9780. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9781. node.fx = dx * gravityForce;
  9782. node.fy = dy * gravityForce;
  9783. }
  9784. else {
  9785. node.fx = 0;
  9786. node.fy = 0;
  9787. }
  9788. }
  9789. },
  9790. /**
  9791. * this function calculates the effects of the springs in the case of unsmooth curves.
  9792. *
  9793. * @private
  9794. */
  9795. _calculateSpringForces: function () {
  9796. var edgeLength, edge, edgeId;
  9797. var dx, dy, fx, fy, springForce, distance;
  9798. var edges = this.edges;
  9799. // forces caused by the edges, modelled as springs
  9800. for (edgeId in edges) {
  9801. if (edges.hasOwnProperty(edgeId)) {
  9802. edge = edges[edgeId];
  9803. if (edge.connected) {
  9804. // only calculate forces if nodes are in the same sector
  9805. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9806. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9807. // this implies that the edges between big clusters are longer
  9808. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9809. dx = (edge.from.x - edge.to.x);
  9810. dy = (edge.from.y - edge.to.y);
  9811. distance = Math.sqrt(dx * dx + dy * dy);
  9812. if (distance == 0) {
  9813. distance = 0.01;
  9814. }
  9815. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  9816. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  9817. fx = dx * springForce;
  9818. fy = dy * springForce;
  9819. edge.from.fx += fx;
  9820. edge.from.fy += fy;
  9821. edge.to.fx -= fx;
  9822. edge.to.fy -= fy;
  9823. }
  9824. }
  9825. }
  9826. }
  9827. },
  9828. /**
  9829. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9830. *
  9831. * @private
  9832. */
  9833. _calculateSpringForcesWithSupport: function () {
  9834. var edgeLength, edge, edgeId, combinedClusterSize;
  9835. var edges = this.edges;
  9836. // forces caused by the edges, modelled as springs
  9837. for (edgeId in edges) {
  9838. if (edges.hasOwnProperty(edgeId)) {
  9839. edge = edges[edgeId];
  9840. if (edge.connected) {
  9841. // only calculate forces if nodes are in the same sector
  9842. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9843. if (edge.via != null) {
  9844. var node1 = edge.to;
  9845. var node2 = edge.via;
  9846. var node3 = edge.from;
  9847. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9848. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9849. // this implies that the edges between big clusters are longer
  9850. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9851. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9852. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9853. }
  9854. }
  9855. }
  9856. }
  9857. }
  9858. },
  9859. /**
  9860. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9861. *
  9862. * @param node1
  9863. * @param node2
  9864. * @param edgeLength
  9865. * @private
  9866. */
  9867. _calculateSpringForce: function (node1, node2, edgeLength) {
  9868. var dx, dy, fx, fy, springForce, distance;
  9869. dx = (node1.x - node2.x);
  9870. dy = (node1.y - node2.y);
  9871. distance = Math.sqrt(dx * dx + dy * dy);
  9872. if (distance == 0) {
  9873. distance = 0.01;
  9874. }
  9875. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  9876. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  9877. fx = dx * springForce;
  9878. fy = dy * springForce;
  9879. node1.fx += fx;
  9880. node1.fy += fy;
  9881. node2.fx -= fx;
  9882. node2.fy -= fy;
  9883. },
  9884. /**
  9885. * Load the HTML for the physics config and bind it
  9886. * @private
  9887. */
  9888. _loadPhysicsConfiguration: function () {
  9889. if (this.physicsConfiguration === undefined) {
  9890. this.backupConstants = {};
  9891. util.copyObject(this.constants, this.backupConstants);
  9892. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  9893. this.physicsConfiguration = document.createElement('div');
  9894. this.physicsConfiguration.className = "PhysicsConfiguration";
  9895. this.physicsConfiguration.innerHTML = '' +
  9896. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9897. '<tr>' +
  9898. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9899. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  9900. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9901. '</tr>' +
  9902. '</table>' +
  9903. '<table id="graph_BH_table" style="display:none">' +
  9904. '<tr><td><b>Barnes Hut</b></td></tr>' +
  9905. '<tr>' +
  9906. '<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>' +
  9907. '</tr>' +
  9908. '<tr>' +
  9909. '<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>' +
  9910. '</tr>' +
  9911. '<tr>' +
  9912. '<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>' +
  9913. '</tr>' +
  9914. '<tr>' +
  9915. '<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>' +
  9916. '</tr>' +
  9917. '<tr>' +
  9918. '<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>' +
  9919. '</tr>' +
  9920. '</table>' +
  9921. '<table id="graph_R_table" style="display:none">' +
  9922. '<tr><td><b>Repulsion</b></td></tr>' +
  9923. '<tr>' +
  9924. '<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>' +
  9925. '</tr>' +
  9926. '<tr>' +
  9927. '<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>' +
  9928. '</tr>' +
  9929. '<tr>' +
  9930. '<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>' +
  9931. '</tr>' +
  9932. '<tr>' +
  9933. '<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>' +
  9934. '</tr>' +
  9935. '<tr>' +
  9936. '<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>' +
  9937. '</tr>' +
  9938. '</table>' +
  9939. '<table id="graph_H_table" style="display:none">' +
  9940. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  9941. '<tr>' +
  9942. '<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>' +
  9943. '</tr>' +
  9944. '<tr>' +
  9945. '<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>' +
  9946. '</tr>' +
  9947. '<tr>' +
  9948. '<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>' +
  9949. '</tr>' +
  9950. '<tr>' +
  9951. '<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>' +
  9952. '</tr>' +
  9953. '<tr>' +
  9954. '<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>' +
  9955. '</tr>' +
  9956. '<tr>' +
  9957. '<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>' +
  9958. '</tr>' +
  9959. '<tr>' +
  9960. '<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>' +
  9961. '</tr>' +
  9962. '<tr>' +
  9963. '<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>' +
  9964. '</tr>' +
  9965. '</table>' +
  9966. '<table><tr><td><b>Options:</b></td></tr>' +
  9967. '<tr>' +
  9968. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9969. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  9970. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  9971. '</tr>' +
  9972. '</table>'
  9973. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  9974. this.optionsDiv = document.createElement("div");
  9975. this.optionsDiv.style.fontSize = "14px";
  9976. this.optionsDiv.style.fontFamily = "verdana";
  9977. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  9978. var rangeElement;
  9979. rangeElement = document.getElementById('graph_BH_gc');
  9980. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  9981. rangeElement = document.getElementById('graph_BH_cg');
  9982. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  9983. rangeElement = document.getElementById('graph_BH_sc');
  9984. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  9985. rangeElement = document.getElementById('graph_BH_sl');
  9986. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  9987. rangeElement = document.getElementById('graph_BH_damp');
  9988. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  9989. rangeElement = document.getElementById('graph_R_nd');
  9990. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  9991. rangeElement = document.getElementById('graph_R_cg');
  9992. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  9993. rangeElement = document.getElementById('graph_R_sc');
  9994. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  9995. rangeElement = document.getElementById('graph_R_sl');
  9996. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  9997. rangeElement = document.getElementById('graph_R_damp');
  9998. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  9999. rangeElement = document.getElementById('graph_H_nd');
  10000. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  10001. rangeElement = document.getElementById('graph_H_cg');
  10002. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  10003. rangeElement = document.getElementById('graph_H_sc');
  10004. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  10005. rangeElement = document.getElementById('graph_H_sl');
  10006. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  10007. rangeElement = document.getElementById('graph_H_damp');
  10008. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  10009. rangeElement = document.getElementById('graph_H_direction');
  10010. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  10011. rangeElement = document.getElementById('graph_H_levsep');
  10012. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  10013. rangeElement = document.getElementById('graph_H_nspac');
  10014. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  10015. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10016. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10017. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10018. radioButton2.checked = true;
  10019. if (this.constants.physics.barnesHut.enabled) {
  10020. radioButton1.checked = true;
  10021. }
  10022. if (this.constants.hierarchicalLayout.enabled) {
  10023. radioButton3.checked = true;
  10024. }
  10025. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10026. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10027. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10028. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10029. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10030. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10031. if (this.constants.smoothCurves == true) {
  10032. graph_toggleSmooth.style.background = "#A4FF56";
  10033. }
  10034. else {
  10035. graph_toggleSmooth.style.background = "#FF8532";
  10036. }
  10037. switchConfigurations.apply(this);
  10038. radioButton1.onchange = switchConfigurations.bind(this);
  10039. radioButton2.onchange = switchConfigurations.bind(this);
  10040. radioButton3.onchange = switchConfigurations.bind(this);
  10041. }
  10042. },
  10043. /**
  10044. * This overwrites the this.constants.
  10045. *
  10046. * @param constantsVariableName
  10047. * @param value
  10048. * @private
  10049. */
  10050. _overWriteGraphConstants: function (constantsVariableName, value) {
  10051. var nameArray = constantsVariableName.split("_");
  10052. if (nameArray.length == 1) {
  10053. this.constants[nameArray[0]] = value;
  10054. }
  10055. else if (nameArray.length == 2) {
  10056. this.constants[nameArray[0]][nameArray[1]] = value;
  10057. }
  10058. else if (nameArray.length == 3) {
  10059. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10060. }
  10061. }
  10062. };
  10063. /**
  10064. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  10065. */
  10066. function graphToggleSmoothCurves () {
  10067. this.constants.smoothCurves = !this.constants.smoothCurves;
  10068. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10069. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10070. else {graph_toggleSmooth.style.background = "#FF8532";}
  10071. this._configureSmoothCurves(false);
  10072. };
  10073. /**
  10074. * this function is used to scramble the nodes
  10075. *
  10076. */
  10077. function graphRepositionNodes () {
  10078. for (var nodeId in this.calculationNodes) {
  10079. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10080. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10081. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10082. }
  10083. }
  10084. if (this.constants.hierarchicalLayout.enabled == true) {
  10085. this._setupHierarchicalLayout();
  10086. }
  10087. else {
  10088. this.repositionNodes();
  10089. }
  10090. this.moving = true;
  10091. this.start();
  10092. };
  10093. /**
  10094. * this is used to generate an options file from the playing with physics system.
  10095. */
  10096. function graphGenerateOptions () {
  10097. var options = "No options are required, default values used.";
  10098. var optionsSpecific = [];
  10099. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10100. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10101. if (radioButton1.checked == true) {
  10102. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10103. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10104. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10105. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10106. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10107. if (optionsSpecific.length != 0) {
  10108. options = "var options = {";
  10109. options += "physics: {barnesHut: {";
  10110. for (var i = 0; i < optionsSpecific.length; i++) {
  10111. options += optionsSpecific[i];
  10112. if (i < optionsSpecific.length - 1) {
  10113. options += ", "
  10114. }
  10115. }
  10116. options += '}}'
  10117. }
  10118. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10119. if (optionsSpecific.length == 0) {options = "var options = {";}
  10120. else {options += ", "}
  10121. options += "smoothCurves: " + this.constants.smoothCurves;
  10122. }
  10123. if (options != "No options are required, default values used.") {
  10124. options += '};'
  10125. }
  10126. }
  10127. else if (radioButton2.checked == true) {
  10128. options = "var options = {";
  10129. options += "physics: {barnesHut: {enabled: false}";
  10130. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10131. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10132. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10133. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10134. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10135. if (optionsSpecific.length != 0) {
  10136. options += ", repulsion: {";
  10137. for (var i = 0; i < optionsSpecific.length; i++) {
  10138. options += optionsSpecific[i];
  10139. if (i < optionsSpecific.length - 1) {
  10140. options += ", "
  10141. }
  10142. }
  10143. options += '}}'
  10144. }
  10145. if (optionsSpecific.length == 0) {options += "}"}
  10146. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10147. options += ", smoothCurves: " + this.constants.smoothCurves;
  10148. }
  10149. options += '};'
  10150. }
  10151. else {
  10152. options = "var options = {";
  10153. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10154. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10155. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10156. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10157. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10158. if (optionsSpecific.length != 0) {
  10159. options += "physics: {hierarchicalRepulsion: {";
  10160. for (var i = 0; i < optionsSpecific.length; i++) {
  10161. options += optionsSpecific[i];
  10162. if (i < optionsSpecific.length - 1) {
  10163. options += ", ";
  10164. }
  10165. }
  10166. options += '}},';
  10167. }
  10168. options += 'hierarchicalLayout: {';
  10169. optionsSpecific = [];
  10170. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10171. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10172. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10173. if (optionsSpecific.length != 0) {
  10174. for (var i = 0; i < optionsSpecific.length; i++) {
  10175. options += optionsSpecific[i];
  10176. if (i < optionsSpecific.length - 1) {
  10177. options += ", "
  10178. }
  10179. }
  10180. options += '}'
  10181. }
  10182. else {
  10183. options += "enabled:true}";
  10184. }
  10185. options += '};'
  10186. }
  10187. this.optionsDiv.innerHTML = options;
  10188. };
  10189. /**
  10190. * this is used to switch between barnesHut, repulsion and hierarchical.
  10191. *
  10192. */
  10193. function switchConfigurations () {
  10194. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10195. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10196. var tableId = "graph_" + radioButton + "_table";
  10197. var table = document.getElementById(tableId);
  10198. table.style.display = "block";
  10199. for (var i = 0; i < ids.length; i++) {
  10200. if (ids[i] != tableId) {
  10201. table = document.getElementById(ids[i]);
  10202. table.style.display = "none";
  10203. }
  10204. }
  10205. this._restoreNodes();
  10206. if (radioButton == "R") {
  10207. this.constants.hierarchicalLayout.enabled = false;
  10208. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10209. this.constants.physics.barnesHut.enabled = false;
  10210. }
  10211. else if (radioButton == "H") {
  10212. if (this.constants.hierarchicalLayout.enabled == false) {
  10213. this.constants.hierarchicalLayout.enabled = true;
  10214. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10215. this.constants.physics.barnesHut.enabled = false;
  10216. this._setupHierarchicalLayout();
  10217. }
  10218. }
  10219. else {
  10220. this.constants.hierarchicalLayout.enabled = false;
  10221. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10222. this.constants.physics.barnesHut.enabled = true;
  10223. }
  10224. this._loadSelectedForceSolver();
  10225. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10226. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10227. else {graph_toggleSmooth.style.background = "#FF8532";}
  10228. this.moving = true;
  10229. this.start();
  10230. }
  10231. /**
  10232. * this generates the ranges depending on the iniital values.
  10233. *
  10234. * @param id
  10235. * @param map
  10236. * @param constantsVariableName
  10237. */
  10238. function showValueOfRange (id,map,constantsVariableName) {
  10239. var valueId = id + "_value";
  10240. var rangeValue = document.getElementById(id).value;
  10241. if (map instanceof Array) {
  10242. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10243. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10244. }
  10245. else {
  10246. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10247. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10248. }
  10249. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10250. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10251. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10252. this._setupHierarchicalLayout();
  10253. }
  10254. this.moving = true;
  10255. this.start();
  10256. };
  10257. /**
  10258. * Created by Alex on 2/10/14.
  10259. */
  10260. var hierarchalRepulsionMixin = {
  10261. /**
  10262. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10263. * This field is linearly approximated.
  10264. *
  10265. * @private
  10266. */
  10267. _calculateNodeForces: function () {
  10268. var dx, dy, distance, fx, fy, combinedClusterSize,
  10269. repulsingForce, node1, node2, i, j;
  10270. var nodes = this.calculationNodes;
  10271. var nodeIndices = this.calculationNodeIndices;
  10272. // approximation constants
  10273. var b = 5;
  10274. var a_base = 0.5 * -b;
  10275. // repulsing forces between nodes
  10276. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10277. var minimumDistance = nodeDistance;
  10278. // we loop from i over all but the last entree in the array
  10279. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10280. for (i = 0; i < nodeIndices.length - 1; i++) {
  10281. node1 = nodes[nodeIndices[i]];
  10282. for (j = i + 1; j < nodeIndices.length; j++) {
  10283. node2 = nodes[nodeIndices[j]];
  10284. dx = node2.x - node1.x;
  10285. dy = node2.y - node1.y;
  10286. distance = Math.sqrt(dx * dx + dy * dy);
  10287. var a = a_base / minimumDistance;
  10288. if (distance < 2 * minimumDistance) {
  10289. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10290. // normalize force with
  10291. if (distance == 0) {
  10292. distance = 0.01;
  10293. }
  10294. else {
  10295. repulsingForce = repulsingForce / distance;
  10296. }
  10297. fx = dx * repulsingForce;
  10298. fy = dy * repulsingForce;
  10299. node1.fx -= fx;
  10300. node1.fy -= fy;
  10301. node2.fx += fx;
  10302. node2.fy += fy;
  10303. }
  10304. }
  10305. }
  10306. }
  10307. };
  10308. /**
  10309. * Created by Alex on 2/10/14.
  10310. */
  10311. var barnesHutMixin = {
  10312. /**
  10313. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10314. * The Barnes Hut method is used to speed up this N-body simulation.
  10315. *
  10316. * @private
  10317. */
  10318. _calculateNodeForces : function() {
  10319. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10320. var node;
  10321. var nodes = this.calculationNodes;
  10322. var nodeIndices = this.calculationNodeIndices;
  10323. var nodeCount = nodeIndices.length;
  10324. this._formBarnesHutTree(nodes,nodeIndices);
  10325. var barnesHutTree = this.barnesHutTree;
  10326. // place the nodes one by one recursively
  10327. for (var i = 0; i < nodeCount; i++) {
  10328. node = nodes[nodeIndices[i]];
  10329. // starting with root is irrelevant, it never passes the BarnesHut condition
  10330. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10331. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10332. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10333. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10334. }
  10335. }
  10336. },
  10337. /**
  10338. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10339. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10340. *
  10341. * @param parentBranch
  10342. * @param node
  10343. * @private
  10344. */
  10345. _getForceContribution : function(parentBranch,node) {
  10346. // we get no force contribution from an empty region
  10347. if (parentBranch.childrenCount > 0) {
  10348. var dx,dy,distance;
  10349. // get the distance from the center of mass to the node.
  10350. dx = parentBranch.centerOfMass.x - node.x;
  10351. dy = parentBranch.centerOfMass.y - node.y;
  10352. distance = Math.sqrt(dx * dx + dy * dy);
  10353. // BarnesHut condition
  10354. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10355. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10356. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10357. // duplicate code to reduce function calls to speed up program
  10358. if (distance == 0) {
  10359. distance = 0.1*Math.random();
  10360. dx = distance;
  10361. }
  10362. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10363. var fx = dx * gravityForce;
  10364. var fy = dy * gravityForce;
  10365. node.fx += fx;
  10366. node.fy += fy;
  10367. }
  10368. else {
  10369. // Did not pass the condition, go into children if available
  10370. if (parentBranch.childrenCount == 4) {
  10371. this._getForceContribution(parentBranch.children.NW,node);
  10372. this._getForceContribution(parentBranch.children.NE,node);
  10373. this._getForceContribution(parentBranch.children.SW,node);
  10374. this._getForceContribution(parentBranch.children.SE,node);
  10375. }
  10376. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10377. if (parentBranch.children.data.id != node.id) { // if it is not self
  10378. // duplicate code to reduce function calls to speed up program
  10379. if (distance == 0) {
  10380. distance = 0.5*Math.random();
  10381. dx = distance;
  10382. }
  10383. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10384. var fx = dx * gravityForce;
  10385. var fy = dy * gravityForce;
  10386. node.fx += fx;
  10387. node.fy += fy;
  10388. }
  10389. }
  10390. }
  10391. }
  10392. },
  10393. /**
  10394. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10395. *
  10396. * @param nodes
  10397. * @param nodeIndices
  10398. * @private
  10399. */
  10400. _formBarnesHutTree : function(nodes,nodeIndices) {
  10401. var node;
  10402. var nodeCount = nodeIndices.length;
  10403. var minX = Number.MAX_VALUE,
  10404. minY = Number.MAX_VALUE,
  10405. maxX =-Number.MAX_VALUE,
  10406. maxY =-Number.MAX_VALUE;
  10407. // get the range of the nodes
  10408. for (var i = 0; i < nodeCount; i++) {
  10409. var x = nodes[nodeIndices[i]].x;
  10410. var y = nodes[nodeIndices[i]].y;
  10411. if (x < minX) { minX = x; }
  10412. if (x > maxX) { maxX = x; }
  10413. if (y < minY) { minY = y; }
  10414. if (y > maxY) { maxY = y; }
  10415. }
  10416. // make the range a square
  10417. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10418. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10419. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10420. var minimumTreeSize = 1e-5;
  10421. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10422. var halfRootSize = 0.5 * rootSize;
  10423. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10424. // construct the barnesHutTree
  10425. var barnesHutTree = {root:{
  10426. centerOfMass:{x:0,y:0}, // Center of Mass
  10427. mass:0,
  10428. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10429. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10430. size: rootSize,
  10431. calcSize: 1 / rootSize,
  10432. children: {data:null},
  10433. maxWidth: 0,
  10434. level: 0,
  10435. childrenCount: 4
  10436. }};
  10437. this._splitBranch(barnesHutTree.root);
  10438. // place the nodes one by one recursively
  10439. for (i = 0; i < nodeCount; i++) {
  10440. node = nodes[nodeIndices[i]];
  10441. this._placeInTree(barnesHutTree.root,node);
  10442. }
  10443. // make global
  10444. this.barnesHutTree = barnesHutTree
  10445. },
  10446. /**
  10447. * this updates the mass of a branch. this is increased by adding a node.
  10448. *
  10449. * @param parentBranch
  10450. * @param node
  10451. * @private
  10452. */
  10453. _updateBranchMass : function(parentBranch, node) {
  10454. var totalMass = parentBranch.mass + node.mass;
  10455. var totalMassInv = 1/totalMass;
  10456. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10457. parentBranch.centerOfMass.x *= totalMassInv;
  10458. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10459. parentBranch.centerOfMass.y *= totalMassInv;
  10460. parentBranch.mass = totalMass;
  10461. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10462. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10463. },
  10464. /**
  10465. * determine in which branch the node will be placed.
  10466. *
  10467. * @param parentBranch
  10468. * @param node
  10469. * @param skipMassUpdate
  10470. * @private
  10471. */
  10472. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10473. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10474. // update the mass of the branch.
  10475. this._updateBranchMass(parentBranch,node);
  10476. }
  10477. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10478. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10479. this._placeInRegion(parentBranch,node,"NW");
  10480. }
  10481. else { // in SW
  10482. this._placeInRegion(parentBranch,node,"SW");
  10483. }
  10484. }
  10485. else { // in NE or SE
  10486. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10487. this._placeInRegion(parentBranch,node,"NE");
  10488. }
  10489. else { // in SE
  10490. this._placeInRegion(parentBranch,node,"SE");
  10491. }
  10492. }
  10493. },
  10494. /**
  10495. * actually place the node in a region (or branch)
  10496. *
  10497. * @param parentBranch
  10498. * @param node
  10499. * @param region
  10500. * @private
  10501. */
  10502. _placeInRegion : function(parentBranch,node,region) {
  10503. switch (parentBranch.children[region].childrenCount) {
  10504. case 0: // place node here
  10505. parentBranch.children[region].children.data = node;
  10506. parentBranch.children[region].childrenCount = 1;
  10507. this._updateBranchMass(parentBranch.children[region],node);
  10508. break;
  10509. case 1: // convert into children
  10510. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10511. // we move one node a pixel and we do not put it in the tree.
  10512. if (parentBranch.children[region].children.data.x == node.x &&
  10513. parentBranch.children[region].children.data.y == node.y) {
  10514. node.x += Math.random();
  10515. node.y += Math.random();
  10516. }
  10517. else {
  10518. this._splitBranch(parentBranch.children[region]);
  10519. this._placeInTree(parentBranch.children[region],node);
  10520. }
  10521. break;
  10522. case 4: // place in branch
  10523. this._placeInTree(parentBranch.children[region],node);
  10524. break;
  10525. }
  10526. },
  10527. /**
  10528. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10529. * after the split is complete.
  10530. *
  10531. * @param parentBranch
  10532. * @private
  10533. */
  10534. _splitBranch : function(parentBranch) {
  10535. // if the branch is filled with a node, replace the node in the new subset.
  10536. var containedNode = null;
  10537. if (parentBranch.childrenCount == 1) {
  10538. containedNode = parentBranch.children.data;
  10539. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10540. }
  10541. parentBranch.childrenCount = 4;
  10542. parentBranch.children.data = null;
  10543. this._insertRegion(parentBranch,"NW");
  10544. this._insertRegion(parentBranch,"NE");
  10545. this._insertRegion(parentBranch,"SW");
  10546. this._insertRegion(parentBranch,"SE");
  10547. if (containedNode != null) {
  10548. this._placeInTree(parentBranch,containedNode);
  10549. }
  10550. },
  10551. /**
  10552. * This function subdivides the region into four new segments.
  10553. * Specifically, this inserts a single new segment.
  10554. * It fills the children section of the parentBranch
  10555. *
  10556. * @param parentBranch
  10557. * @param region
  10558. * @param parentRange
  10559. * @private
  10560. */
  10561. _insertRegion : function(parentBranch, region) {
  10562. var minX,maxX,minY,maxY;
  10563. var childSize = 0.5 * parentBranch.size;
  10564. switch (region) {
  10565. case "NW":
  10566. minX = parentBranch.range.minX;
  10567. maxX = parentBranch.range.minX + childSize;
  10568. minY = parentBranch.range.minY;
  10569. maxY = parentBranch.range.minY + childSize;
  10570. break;
  10571. case "NE":
  10572. minX = parentBranch.range.minX + childSize;
  10573. maxX = parentBranch.range.maxX;
  10574. minY = parentBranch.range.minY;
  10575. maxY = parentBranch.range.minY + childSize;
  10576. break;
  10577. case "SW":
  10578. minX = parentBranch.range.minX;
  10579. maxX = parentBranch.range.minX + childSize;
  10580. minY = parentBranch.range.minY + childSize;
  10581. maxY = parentBranch.range.maxY;
  10582. break;
  10583. case "SE":
  10584. minX = parentBranch.range.minX + childSize;
  10585. maxX = parentBranch.range.maxX;
  10586. minY = parentBranch.range.minY + childSize;
  10587. maxY = parentBranch.range.maxY;
  10588. break;
  10589. }
  10590. parentBranch.children[region] = {
  10591. centerOfMass:{x:0,y:0},
  10592. mass:0,
  10593. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10594. size: 0.5 * parentBranch.size,
  10595. calcSize: 2 * parentBranch.calcSize,
  10596. children: {data:null},
  10597. maxWidth: 0,
  10598. level: parentBranch.level+1,
  10599. childrenCount: 0
  10600. };
  10601. },
  10602. /**
  10603. * This function is for debugging purposed, it draws the tree.
  10604. *
  10605. * @param ctx
  10606. * @param color
  10607. * @private
  10608. */
  10609. _drawTree : function(ctx,color) {
  10610. if (this.barnesHutTree !== undefined) {
  10611. ctx.lineWidth = 1;
  10612. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10613. }
  10614. },
  10615. /**
  10616. * This function is for debugging purposes. It draws the branches recursively.
  10617. *
  10618. * @param branch
  10619. * @param ctx
  10620. * @param color
  10621. * @private
  10622. */
  10623. _drawBranch : function(branch,ctx,color) {
  10624. if (color === undefined) {
  10625. color = "#FF0000";
  10626. }
  10627. if (branch.childrenCount == 4) {
  10628. this._drawBranch(branch.children.NW,ctx);
  10629. this._drawBranch(branch.children.NE,ctx);
  10630. this._drawBranch(branch.children.SE,ctx);
  10631. this._drawBranch(branch.children.SW,ctx);
  10632. }
  10633. ctx.strokeStyle = color;
  10634. ctx.beginPath();
  10635. ctx.moveTo(branch.range.minX,branch.range.minY);
  10636. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10637. ctx.stroke();
  10638. ctx.beginPath();
  10639. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10640. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10641. ctx.stroke();
  10642. ctx.beginPath();
  10643. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10644. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10645. ctx.stroke();
  10646. ctx.beginPath();
  10647. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10648. ctx.lineTo(branch.range.minX,branch.range.minY);
  10649. ctx.stroke();
  10650. /*
  10651. if (branch.mass > 0) {
  10652. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10653. ctx.stroke();
  10654. }
  10655. */
  10656. }
  10657. };
  10658. /**
  10659. * Created by Alex on 2/10/14.
  10660. */
  10661. var repulsionMixin = {
  10662. /**
  10663. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10664. * This field is linearly approximated.
  10665. *
  10666. * @private
  10667. */
  10668. _calculateNodeForces: function () {
  10669. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10670. repulsingForce, node1, node2, i, j;
  10671. var nodes = this.calculationNodes;
  10672. var nodeIndices = this.calculationNodeIndices;
  10673. // approximation constants
  10674. var a_base = -2 / 3;
  10675. var b = 4 / 3;
  10676. // repulsing forces between nodes
  10677. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10678. var minimumDistance = nodeDistance;
  10679. // we loop from i over all but the last entree in the array
  10680. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10681. for (i = 0; i < nodeIndices.length - 1; i++) {
  10682. node1 = nodes[nodeIndices[i]];
  10683. for (j = i + 1; j < nodeIndices.length; j++) {
  10684. node2 = nodes[nodeIndices[j]];
  10685. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10686. dx = node2.x - node1.x;
  10687. dy = node2.y - node1.y;
  10688. distance = Math.sqrt(dx * dx + dy * dy);
  10689. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10690. var a = a_base / minimumDistance;
  10691. if (distance < 2 * minimumDistance) {
  10692. if (distance < 0.5 * minimumDistance) {
  10693. repulsingForce = 1.0;
  10694. }
  10695. else {
  10696. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10697. }
  10698. // amplify the repulsion for clusters.
  10699. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10700. repulsingForce = repulsingForce / distance;
  10701. fx = dx * repulsingForce;
  10702. fy = dy * repulsingForce;
  10703. node1.fx -= fx;
  10704. node1.fy -= fy;
  10705. node2.fx += fx;
  10706. node2.fy += fy;
  10707. }
  10708. }
  10709. }
  10710. }
  10711. };
  10712. var HierarchicalLayoutMixin = {
  10713. _resetLevels : function() {
  10714. for (var nodeId in this.nodes) {
  10715. if (this.nodes.hasOwnProperty(nodeId)) {
  10716. var node = this.nodes[nodeId];
  10717. if (node.preassignedLevel == false) {
  10718. node.level = -1;
  10719. }
  10720. }
  10721. }
  10722. },
  10723. /**
  10724. * This is the main function to layout the nodes in a hierarchical way.
  10725. * It checks if the node details are supplied correctly
  10726. *
  10727. * @private
  10728. */
  10729. _setupHierarchicalLayout : function() {
  10730. if (this.constants.hierarchicalLayout.enabled == true) {
  10731. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10732. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10733. }
  10734. else {
  10735. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10736. }
  10737. // get the size of the largest hubs and check if the user has defined a level for a node.
  10738. var hubsize = 0;
  10739. var node, nodeId;
  10740. var definedLevel = false;
  10741. var undefinedLevel = false;
  10742. for (nodeId in this.nodes) {
  10743. if (this.nodes.hasOwnProperty(nodeId)) {
  10744. node = this.nodes[nodeId];
  10745. if (node.level != -1) {
  10746. definedLevel = true;
  10747. }
  10748. else {
  10749. undefinedLevel = true;
  10750. }
  10751. if (hubsize < node.edges.length) {
  10752. hubsize = node.edges.length;
  10753. }
  10754. }
  10755. }
  10756. // if the user defined some levels but not all, alert and run without hierarchical layout
  10757. if (undefinedLevel == true && definedLevel == true) {
  10758. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10759. this.zoomExtent(true,this.constants.clustering.enabled);
  10760. if (!this.constants.clustering.enabled) {
  10761. this.start();
  10762. }
  10763. }
  10764. else {
  10765. // setup the system to use hierarchical method.
  10766. this._changeConstants();
  10767. // define levels if undefined by the users. Based on hubsize
  10768. if (undefinedLevel == true) {
  10769. this._determineLevels(hubsize);
  10770. }
  10771. // check the distribution of the nodes per level.
  10772. var distribution = this._getDistribution();
  10773. // place the nodes on the canvas. This also stablilizes the system.
  10774. this._placeNodesByHierarchy(distribution);
  10775. // start the simulation.
  10776. this.start();
  10777. }
  10778. }
  10779. },
  10780. /**
  10781. * This function places the nodes on the canvas based on the hierarchial distribution.
  10782. *
  10783. * @param {Object} distribution | obtained by the function this._getDistribution()
  10784. * @private
  10785. */
  10786. _placeNodesByHierarchy : function(distribution) {
  10787. var nodeId, node;
  10788. // start placing all the level 0 nodes first. Then recursively position their branches.
  10789. for (nodeId in distribution[0].nodes) {
  10790. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10791. node = distribution[0].nodes[nodeId];
  10792. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10793. if (node.xFixed) {
  10794. node.x = distribution[0].minPos;
  10795. node.xFixed = false;
  10796. distribution[0].minPos += distribution[0].nodeSpacing;
  10797. }
  10798. }
  10799. else {
  10800. if (node.yFixed) {
  10801. node.y = distribution[0].minPos;
  10802. node.yFixed = false;
  10803. distribution[0].minPos += distribution[0].nodeSpacing;
  10804. }
  10805. }
  10806. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10807. }
  10808. }
  10809. // stabilize the system after positioning. This function calls zoomExtent.
  10810. this._stabilize();
  10811. },
  10812. /**
  10813. * This function get the distribution of levels based on hubsize
  10814. *
  10815. * @returns {Object}
  10816. * @private
  10817. */
  10818. _getDistribution : function() {
  10819. var distribution = {};
  10820. var nodeId, node, level;
  10821. // 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.
  10822. // the fix of X is removed after the x value has been set.
  10823. for (nodeId in this.nodes) {
  10824. if (this.nodes.hasOwnProperty(nodeId)) {
  10825. node = this.nodes[nodeId];
  10826. node.xFixed = true;
  10827. node.yFixed = true;
  10828. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10829. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10830. }
  10831. else {
  10832. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10833. }
  10834. if (!distribution.hasOwnProperty(node.level)) {
  10835. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10836. }
  10837. distribution[node.level].amount += 1;
  10838. distribution[node.level].nodes[node.id] = node;
  10839. }
  10840. }
  10841. // determine the largest amount of nodes of all levels
  10842. var maxCount = 0;
  10843. for (level in distribution) {
  10844. if (distribution.hasOwnProperty(level)) {
  10845. if (maxCount < distribution[level].amount) {
  10846. maxCount = distribution[level].amount;
  10847. }
  10848. }
  10849. }
  10850. // set the initial position and spacing of each nodes accordingly
  10851. for (level in distribution) {
  10852. if (distribution.hasOwnProperty(level)) {
  10853. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10854. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10855. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10856. }
  10857. }
  10858. return distribution;
  10859. },
  10860. /**
  10861. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10862. *
  10863. * @param hubsize
  10864. * @private
  10865. */
  10866. _determineLevels : function(hubsize) {
  10867. var nodeId, node;
  10868. // determine hubs
  10869. for (nodeId in this.nodes) {
  10870. if (this.nodes.hasOwnProperty(nodeId)) {
  10871. node = this.nodes[nodeId];
  10872. if (node.edges.length == hubsize) {
  10873. node.level = 0;
  10874. }
  10875. }
  10876. }
  10877. // branch from hubs
  10878. for (nodeId in this.nodes) {
  10879. if (this.nodes.hasOwnProperty(nodeId)) {
  10880. node = this.nodes[nodeId];
  10881. if (node.level == 0) {
  10882. this._setLevel(1,node.edges,node.id);
  10883. }
  10884. }
  10885. }
  10886. },
  10887. /**
  10888. * Since hierarchical layout does not support:
  10889. * - smooth curves (based on the physics),
  10890. * - clustering (based on dynamic node counts)
  10891. *
  10892. * We disable both features so there will be no problems.
  10893. *
  10894. * @private
  10895. */
  10896. _changeConstants : function() {
  10897. this.constants.clustering.enabled = false;
  10898. this.constants.physics.barnesHut.enabled = false;
  10899. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10900. this._loadSelectedForceSolver();
  10901. this.constants.smoothCurves = false;
  10902. this._configureSmoothCurves();
  10903. },
  10904. /**
  10905. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10906. * on a X position that ensures there will be no overlap.
  10907. *
  10908. * @param edges
  10909. * @param parentId
  10910. * @param distribution
  10911. * @param parentLevel
  10912. * @private
  10913. */
  10914. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10915. for (var i = 0; i < edges.length; i++) {
  10916. var childNode = null;
  10917. if (edges[i].toId == parentId) {
  10918. childNode = edges[i].from;
  10919. }
  10920. else {
  10921. childNode = edges[i].to;
  10922. }
  10923. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10924. var nodeMoved = false;
  10925. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10926. if (childNode.xFixed && childNode.level > parentLevel) {
  10927. childNode.xFixed = false;
  10928. childNode.x = distribution[childNode.level].minPos;
  10929. nodeMoved = true;
  10930. }
  10931. }
  10932. else {
  10933. if (childNode.yFixed && childNode.level > parentLevel) {
  10934. childNode.yFixed = false;
  10935. childNode.y = distribution[childNode.level].minPos;
  10936. nodeMoved = true;
  10937. }
  10938. }
  10939. if (nodeMoved == true) {
  10940. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10941. if (childNode.edges.length > 1) {
  10942. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10943. }
  10944. }
  10945. }
  10946. },
  10947. /**
  10948. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10949. *
  10950. * @param level
  10951. * @param edges
  10952. * @param parentId
  10953. * @private
  10954. */
  10955. _setLevel : function(level, edges, parentId) {
  10956. for (var i = 0; i < edges.length; i++) {
  10957. var childNode = null;
  10958. if (edges[i].toId == parentId) {
  10959. childNode = edges[i].from;
  10960. }
  10961. else {
  10962. childNode = edges[i].to;
  10963. }
  10964. if (childNode.level == -1 || childNode.level > level) {
  10965. childNode.level = level;
  10966. if (edges.length > 1) {
  10967. this._setLevel(level+1, childNode.edges, childNode.id);
  10968. }
  10969. }
  10970. }
  10971. },
  10972. /**
  10973. * Unfix nodes
  10974. *
  10975. * @private
  10976. */
  10977. _restoreNodes : function() {
  10978. for (nodeId in this.nodes) {
  10979. if (this.nodes.hasOwnProperty(nodeId)) {
  10980. this.nodes[nodeId].xFixed = false;
  10981. this.nodes[nodeId].yFixed = false;
  10982. }
  10983. }
  10984. }
  10985. };
  10986. /**
  10987. * Created by Alex on 2/4/14.
  10988. */
  10989. var manipulationMixin = {
  10990. /**
  10991. * clears the toolbar div element of children
  10992. *
  10993. * @private
  10994. */
  10995. _clearManipulatorBar : function() {
  10996. while (this.manipulationDiv.hasChildNodes()) {
  10997. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10998. }
  10999. },
  11000. /**
  11001. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11002. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11003. * This function restores these functions to their original function.
  11004. *
  11005. * @private
  11006. */
  11007. _restoreOverloadedFunctions : function() {
  11008. for (var functionName in this.cachedFunctions) {
  11009. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11010. this[functionName] = this.cachedFunctions[functionName];
  11011. }
  11012. }
  11013. },
  11014. /**
  11015. * Enable or disable edit-mode.
  11016. *
  11017. * @private
  11018. */
  11019. _toggleEditMode : function() {
  11020. this.editMode = !this.editMode;
  11021. var toolbar = document.getElementById("graph-manipulationDiv");
  11022. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11023. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11024. if (this.editMode == true) {
  11025. toolbar.style.display="block";
  11026. closeDiv.style.display="block";
  11027. editModeDiv.style.display="none";
  11028. closeDiv.onclick = this._toggleEditMode.bind(this);
  11029. }
  11030. else {
  11031. toolbar.style.display="none";
  11032. closeDiv.style.display="none";
  11033. editModeDiv.style.display="block";
  11034. closeDiv.onclick = null;
  11035. }
  11036. this._createManipulatorBar()
  11037. },
  11038. /**
  11039. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11040. *
  11041. * @private
  11042. */
  11043. _createManipulatorBar : function() {
  11044. // remove bound functions
  11045. if (this.boundFunction) {
  11046. this.off('select', this.boundFunction);
  11047. }
  11048. // restore overloaded functions
  11049. this._restoreOverloadedFunctions();
  11050. // resume calculation
  11051. this.freezeSimulation = false;
  11052. // reset global variables
  11053. this.blockConnectingEdgeSelection = false;
  11054. this.forceAppendSelection = false;
  11055. if (this.editMode == true) {
  11056. while (this.manipulationDiv.hasChildNodes()) {
  11057. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11058. }
  11059. // add the icons to the manipulator div
  11060. this.manipulationDiv.innerHTML = "" +
  11061. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11062. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  11063. "<div class='graph-seperatorLine'></div>" +
  11064. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11065. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  11066. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11067. this.manipulationDiv.innerHTML += "" +
  11068. "<div class='graph-seperatorLine'></div>" +
  11069. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11070. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  11071. }
  11072. if (this._selectionIsEmpty() == false) {
  11073. this.manipulationDiv.innerHTML += "" +
  11074. "<div class='graph-seperatorLine'></div>" +
  11075. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11076. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  11077. }
  11078. // bind the icons
  11079. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11080. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11081. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11082. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11083. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11084. var editButton = document.getElementById("graph-manipulate-editNode");
  11085. editButton.onclick = this._editNode.bind(this);
  11086. }
  11087. if (this._selectionIsEmpty() == false) {
  11088. var deleteButton = document.getElementById("graph-manipulate-delete");
  11089. deleteButton.onclick = this._deleteSelected.bind(this);
  11090. }
  11091. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11092. closeDiv.onclick = this._toggleEditMode.bind(this);
  11093. this.boundFunction = this._createManipulatorBar.bind(this);
  11094. this.on('select', this.boundFunction);
  11095. }
  11096. else {
  11097. this.editModeDiv.innerHTML = "" +
  11098. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11099. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  11100. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11101. editModeButton.onclick = this._toggleEditMode.bind(this);
  11102. }
  11103. },
  11104. /**
  11105. * Create the toolbar for adding Nodes
  11106. *
  11107. * @private
  11108. */
  11109. _createAddNodeToolbar : function() {
  11110. // clear the toolbar
  11111. this._clearManipulatorBar();
  11112. if (this.boundFunction) {
  11113. this.off('select', this.boundFunction);
  11114. }
  11115. // create the toolbar contents
  11116. this.manipulationDiv.innerHTML = "" +
  11117. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11118. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11119. "<div class='graph-seperatorLine'></div>" +
  11120. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11121. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11122. // bind the icon
  11123. var backButton = document.getElementById("graph-manipulate-back");
  11124. backButton.onclick = this._createManipulatorBar.bind(this);
  11125. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11126. this.boundFunction = this._addNode.bind(this);
  11127. this.on('select', this.boundFunction);
  11128. },
  11129. /**
  11130. * create the toolbar to connect nodes
  11131. *
  11132. * @private
  11133. */
  11134. _createAddEdgeToolbar : function() {
  11135. // clear the toolbar
  11136. this._clearManipulatorBar();
  11137. this._unselectAll(true);
  11138. this.freezeSimulation = true;
  11139. if (this.boundFunction) {
  11140. this.off('select', this.boundFunction);
  11141. }
  11142. this._unselectAll();
  11143. this.forceAppendSelection = false;
  11144. this.blockConnectingEdgeSelection = true;
  11145. this.manipulationDiv.innerHTML = "" +
  11146. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11147. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11148. "<div class='graph-seperatorLine'></div>" +
  11149. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11150. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11151. // bind the icon
  11152. var backButton = document.getElementById("graph-manipulate-back");
  11153. backButton.onclick = this._createManipulatorBar.bind(this);
  11154. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11155. this.boundFunction = this._handleConnect.bind(this);
  11156. this.on('select', this.boundFunction);
  11157. // temporarily overload functions
  11158. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11159. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11160. this._handleTouch = this._handleConnect;
  11161. this._handleOnRelease = this._finishConnect;
  11162. // redraw to show the unselect
  11163. this._redraw();
  11164. },
  11165. /**
  11166. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11167. * to walk the user through the process.
  11168. *
  11169. * @private
  11170. */
  11171. _handleConnect : function(pointer) {
  11172. if (this._getSelectedNodeCount() == 0) {
  11173. var node = this._getNodeAt(pointer);
  11174. if (node != null) {
  11175. if (node.clusterSize > 1) {
  11176. alert("Cannot create edges to a cluster.")
  11177. }
  11178. else {
  11179. this._selectObject(node,false);
  11180. // create a node the temporary line can look at
  11181. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11182. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11183. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11184. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11185. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11186. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11187. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11188. // create a temporary edge
  11189. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11190. this.edges['connectionEdge'].from = node;
  11191. this.edges['connectionEdge'].connected = true;
  11192. this.edges['connectionEdge'].smooth = true;
  11193. this.edges['connectionEdge'].selected = true;
  11194. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11195. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11196. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11197. this._handleOnDrag = function(event) {
  11198. var pointer = this._getPointer(event.gesture.center);
  11199. this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x);
  11200. this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y);
  11201. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x);
  11202. this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y);
  11203. };
  11204. this.moving = true;
  11205. this.start();
  11206. }
  11207. }
  11208. }
  11209. },
  11210. _finishConnect : function(pointer) {
  11211. if (this._getSelectedNodeCount() == 1) {
  11212. // restore the drag function
  11213. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11214. delete this.cachedFunctions["_handleOnDrag"];
  11215. // remember the edge id
  11216. var connectFromId = this.edges['connectionEdge'].fromId;
  11217. // remove the temporary nodes and edge
  11218. delete this.edges['connectionEdge'];
  11219. delete this.sectors['support']['nodes']['targetNode'];
  11220. delete this.sectors['support']['nodes']['targetViaNode'];
  11221. var node = this._getNodeAt(pointer);
  11222. if (node != null) {
  11223. if (node.clusterSize > 1) {
  11224. alert("Cannot create edges to a cluster.")
  11225. }
  11226. else {
  11227. this._createEdge(connectFromId,node.id);
  11228. this._createManipulatorBar();
  11229. }
  11230. }
  11231. this._unselectAll();
  11232. }
  11233. },
  11234. /**
  11235. * Adds a node on the specified location
  11236. */
  11237. _addNode : function() {
  11238. if (this._selectionIsEmpty() && this.editMode == true) {
  11239. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11240. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11241. if (this.triggerFunctions.add) {
  11242. if (this.triggerFunctions.add.length == 2) {
  11243. var me = this;
  11244. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11245. me.nodesData.add(finalizedData);
  11246. me._createManipulatorBar();
  11247. me.moving = true;
  11248. me.start();
  11249. });
  11250. }
  11251. else {
  11252. alert(this.constants.labels['addError']);
  11253. this._createManipulatorBar();
  11254. this.moving = true;
  11255. this.start();
  11256. }
  11257. }
  11258. else {
  11259. this.nodesData.add(defaultData);
  11260. this._createManipulatorBar();
  11261. this.moving = true;
  11262. this.start();
  11263. }
  11264. }
  11265. },
  11266. /**
  11267. * connect two nodes with a new edge.
  11268. *
  11269. * @private
  11270. */
  11271. _createEdge : function(sourceNodeId,targetNodeId) {
  11272. if (this.editMode == true) {
  11273. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11274. if (this.triggerFunctions.connect) {
  11275. if (this.triggerFunctions.connect.length == 2) {
  11276. var me = this;
  11277. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11278. me.edgesData.add(finalizedData);
  11279. me.moving = true;
  11280. me.start();
  11281. });
  11282. }
  11283. else {
  11284. alert(this.constants.labels["linkError"]);
  11285. this.moving = true;
  11286. this.start();
  11287. }
  11288. }
  11289. else {
  11290. this.edgesData.add(defaultData);
  11291. this.moving = true;
  11292. this.start();
  11293. }
  11294. }
  11295. },
  11296. /**
  11297. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11298. *
  11299. * @private
  11300. */
  11301. _editNode : function() {
  11302. if (this.triggerFunctions.edit && this.editMode == true) {
  11303. var node = this._getSelectedNode();
  11304. var data = {id:node.id,
  11305. label: node.label,
  11306. group: node.group,
  11307. shape: node.shape,
  11308. color: {
  11309. background:node.color.background,
  11310. border:node.color.border,
  11311. highlight: {
  11312. background:node.color.highlight.background,
  11313. border:node.color.highlight.border
  11314. }
  11315. }};
  11316. if (this.triggerFunctions.edit.length == 2) {
  11317. var me = this;
  11318. this.triggerFunctions.edit(data, function (finalizedData) {
  11319. me.nodesData.update(finalizedData);
  11320. me._createManipulatorBar();
  11321. me.moving = true;
  11322. me.start();
  11323. });
  11324. }
  11325. else {
  11326. alert(this.constants.labels["editError"]);
  11327. }
  11328. }
  11329. else {
  11330. alert(this.constants.labels["editBoundError"]);
  11331. }
  11332. },
  11333. /**
  11334. * delete everything in the selection
  11335. *
  11336. * @private
  11337. */
  11338. _deleteSelected : function() {
  11339. if (!this._selectionIsEmpty() && this.editMode == true) {
  11340. if (!this._clusterInSelection()) {
  11341. var selectedNodes = this.getSelectedNodes();
  11342. var selectedEdges = this.getSelectedEdges();
  11343. if (this.triggerFunctions.del) {
  11344. var me = this;
  11345. var data = {nodes: selectedNodes, edges: selectedEdges};
  11346. if (this.triggerFunctions.del.length = 2) {
  11347. this.triggerFunctions.del(data, function (finalizedData) {
  11348. me.edgesData.remove(finalizedData.edges);
  11349. me.nodesData.remove(finalizedData.nodes);
  11350. me._unselectAll();
  11351. me.moving = true;
  11352. me.start();
  11353. });
  11354. }
  11355. else {
  11356. alert(this.constants.labels["deleteError"])
  11357. }
  11358. }
  11359. else {
  11360. this.edgesData.remove(selectedEdges);
  11361. this.nodesData.remove(selectedNodes);
  11362. this._unselectAll();
  11363. this.moving = true;
  11364. this.start();
  11365. }
  11366. }
  11367. else {
  11368. alert(this.constants.labels["deleteClusterError"]);
  11369. }
  11370. }
  11371. }
  11372. };
  11373. /**
  11374. * Creation of the SectorMixin var.
  11375. *
  11376. * This contains all the functions the Graph object can use to employ the sector system.
  11377. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11378. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11379. *
  11380. * Alex de Mulder
  11381. * 21-01-2013
  11382. */
  11383. var SectorMixin = {
  11384. /**
  11385. * This function is only called by the setData function of the Graph object.
  11386. * This loads the global references into the active sector. This initializes the sector.
  11387. *
  11388. * @private
  11389. */
  11390. _putDataInSector : function() {
  11391. this.sectors["active"][this._sector()].nodes = this.nodes;
  11392. this.sectors["active"][this._sector()].edges = this.edges;
  11393. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11394. },
  11395. /**
  11396. * /**
  11397. * This function sets the global references to nodes, edges and nodeIndices back to
  11398. * those of the supplied (active) sector. If a type is defined, do the specific type
  11399. *
  11400. * @param {String} sectorId
  11401. * @param {String} [sectorType] | "active" or "frozen"
  11402. * @private
  11403. */
  11404. _switchToSector : function(sectorId, sectorType) {
  11405. if (sectorType === undefined || sectorType == "active") {
  11406. this._switchToActiveSector(sectorId);
  11407. }
  11408. else {
  11409. this._switchToFrozenSector(sectorId);
  11410. }
  11411. },
  11412. /**
  11413. * This function sets the global references to nodes, edges and nodeIndices back to
  11414. * those of the supplied active sector.
  11415. *
  11416. * @param sectorId
  11417. * @private
  11418. */
  11419. _switchToActiveSector : function(sectorId) {
  11420. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11421. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11422. this.edges = this.sectors["active"][sectorId]["edges"];
  11423. },
  11424. /**
  11425. * This function sets the global references to nodes, edges and nodeIndices back to
  11426. * those of the supplied active sector.
  11427. *
  11428. * @param sectorId
  11429. * @private
  11430. */
  11431. _switchToSupportSector : function() {
  11432. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11433. this.nodes = this.sectors["support"]["nodes"];
  11434. this.edges = this.sectors["support"]["edges"];
  11435. },
  11436. /**
  11437. * This function sets the global references to nodes, edges and nodeIndices back to
  11438. * those of the supplied frozen sector.
  11439. *
  11440. * @param sectorId
  11441. * @private
  11442. */
  11443. _switchToFrozenSector : function(sectorId) {
  11444. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11445. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11446. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11447. },
  11448. /**
  11449. * This function sets the global references to nodes, edges and nodeIndices back to
  11450. * those of the currently active sector.
  11451. *
  11452. * @private
  11453. */
  11454. _loadLatestSector : function() {
  11455. this._switchToSector(this._sector());
  11456. },
  11457. /**
  11458. * This function returns the currently active sector Id
  11459. *
  11460. * @returns {String}
  11461. * @private
  11462. */
  11463. _sector : function() {
  11464. return this.activeSector[this.activeSector.length-1];
  11465. },
  11466. /**
  11467. * This function returns the previously active sector Id
  11468. *
  11469. * @returns {String}
  11470. * @private
  11471. */
  11472. _previousSector : function() {
  11473. if (this.activeSector.length > 1) {
  11474. return this.activeSector[this.activeSector.length-2];
  11475. }
  11476. else {
  11477. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11478. }
  11479. },
  11480. /**
  11481. * We add the active sector at the end of the this.activeSector array
  11482. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11483. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11484. *
  11485. * @param newId
  11486. * @private
  11487. */
  11488. _setActiveSector : function(newId) {
  11489. this.activeSector.push(newId);
  11490. },
  11491. /**
  11492. * We remove the currently active sector id from the active sector stack. This happens when
  11493. * we reactivate the previously active sector
  11494. *
  11495. * @private
  11496. */
  11497. _forgetLastSector : function() {
  11498. this.activeSector.pop();
  11499. },
  11500. /**
  11501. * This function creates a new active sector with the supplied newId. This newId
  11502. * is the expanding node id.
  11503. *
  11504. * @param {String} newId | Id of the new active sector
  11505. * @private
  11506. */
  11507. _createNewSector : function(newId) {
  11508. // create the new sector
  11509. this.sectors["active"][newId] = {"nodes":{},
  11510. "edges":{},
  11511. "nodeIndices":[],
  11512. "formationScale": this.scale,
  11513. "drawingNode": undefined};
  11514. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11515. this.sectors["active"][newId]['drawingNode'] = new Node(
  11516. {id:newId,
  11517. color: {
  11518. background: "#eaefef",
  11519. border: "495c5e"
  11520. }
  11521. },{},{},this.constants);
  11522. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11523. },
  11524. /**
  11525. * This function removes the currently active sector. This is called when we create a new
  11526. * active sector.
  11527. *
  11528. * @param {String} sectorId | Id of the active sector that will be removed
  11529. * @private
  11530. */
  11531. _deleteActiveSector : function(sectorId) {
  11532. delete this.sectors["active"][sectorId];
  11533. },
  11534. /**
  11535. * This function removes the currently active sector. This is called when we reactivate
  11536. * the previously active sector.
  11537. *
  11538. * @param {String} sectorId | Id of the active sector that will be removed
  11539. * @private
  11540. */
  11541. _deleteFrozenSector : function(sectorId) {
  11542. delete this.sectors["frozen"][sectorId];
  11543. },
  11544. /**
  11545. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11546. * We copy the references, then delete the active entree.
  11547. *
  11548. * @param sectorId
  11549. * @private
  11550. */
  11551. _freezeSector : function(sectorId) {
  11552. // we move the set references from the active to the frozen stack.
  11553. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11554. // we have moved the sector data into the frozen set, we now remove it from the active set
  11555. this._deleteActiveSector(sectorId);
  11556. },
  11557. /**
  11558. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11559. * object to the "active" object.
  11560. *
  11561. * @param sectorId
  11562. * @private
  11563. */
  11564. _activateSector : function(sectorId) {
  11565. // we move the set references from the frozen to the active stack.
  11566. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11567. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11568. this._deleteFrozenSector(sectorId);
  11569. },
  11570. /**
  11571. * This function merges the data from the currently active sector with a frozen sector. This is used
  11572. * in the process of reverting back to the previously active sector.
  11573. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11574. * upon the creation of a new active sector.
  11575. *
  11576. * @param sectorId
  11577. * @private
  11578. */
  11579. _mergeThisWithFrozen : function(sectorId) {
  11580. // copy all nodes
  11581. for (var nodeId in this.nodes) {
  11582. if (this.nodes.hasOwnProperty(nodeId)) {
  11583. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11584. }
  11585. }
  11586. // copy all edges (if not fully clustered, else there are no edges)
  11587. for (var edgeId in this.edges) {
  11588. if (this.edges.hasOwnProperty(edgeId)) {
  11589. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11590. }
  11591. }
  11592. // merge the nodeIndices
  11593. for (var i = 0; i < this.nodeIndices.length; i++) {
  11594. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11595. }
  11596. },
  11597. /**
  11598. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11599. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11600. *
  11601. * @private
  11602. */
  11603. _collapseThisToSingleCluster : function() {
  11604. this.clusterToFit(1,false);
  11605. },
  11606. /**
  11607. * We create a new active sector from the node that we want to open.
  11608. *
  11609. * @param node
  11610. * @private
  11611. */
  11612. _addSector : function(node) {
  11613. // this is the currently active sector
  11614. var sector = this._sector();
  11615. // // this should allow me to select nodes from a frozen set.
  11616. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11617. // console.log("the node is part of the active sector");
  11618. // }
  11619. // else {
  11620. // console.log("I dont know what the fuck happened!!");
  11621. // }
  11622. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11623. delete this.nodes[node.id];
  11624. var unqiueIdentifier = util.randomUUID();
  11625. // we fully freeze the currently active sector
  11626. this._freezeSector(sector);
  11627. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11628. this._createNewSector(unqiueIdentifier);
  11629. // we add the active sector to the sectors array to be able to revert these steps later on
  11630. this._setActiveSector(unqiueIdentifier);
  11631. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11632. this._switchToSector(this._sector());
  11633. // finally we add the node we removed from our previous active sector to the new active sector
  11634. this.nodes[node.id] = node;
  11635. },
  11636. /**
  11637. * We close the sector that is currently open and revert back to the one before.
  11638. * If the active sector is the "default" sector, nothing happens.
  11639. *
  11640. * @private
  11641. */
  11642. _collapseSector : function() {
  11643. // the currently active sector
  11644. var sector = this._sector();
  11645. // we cannot collapse the default sector
  11646. if (sector != "default") {
  11647. if ((this.nodeIndices.length == 1) ||
  11648. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11649. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11650. var previousSector = this._previousSector();
  11651. // we collapse the sector back to a single cluster
  11652. this._collapseThisToSingleCluster();
  11653. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11654. // This previous sector is the one we will reactivate
  11655. this._mergeThisWithFrozen(previousSector);
  11656. // the previously active (frozen) sector now has all the data from the currently active sector.
  11657. // we can now delete the active sector.
  11658. this._deleteActiveSector(sector);
  11659. // we activate the previously active (and currently frozen) sector.
  11660. this._activateSector(previousSector);
  11661. // we load the references from the newly active sector into the global references
  11662. this._switchToSector(previousSector);
  11663. // we forget the previously active sector because we reverted to the one before
  11664. this._forgetLastSector();
  11665. // finally, we update the node index list.
  11666. this._updateNodeIndexList();
  11667. // we refresh the list with calulation nodes and calculation node indices.
  11668. this._updateCalculationNodes();
  11669. }
  11670. }
  11671. },
  11672. /**
  11673. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11674. *
  11675. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11676. * | we dont pass the function itself because then the "this" is the window object
  11677. * | instead of the Graph object
  11678. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11679. * @private
  11680. */
  11681. _doInAllActiveSectors : function(runFunction,argument) {
  11682. if (argument === undefined) {
  11683. for (var sector in this.sectors["active"]) {
  11684. if (this.sectors["active"].hasOwnProperty(sector)) {
  11685. // switch the global references to those of this sector
  11686. this._switchToActiveSector(sector);
  11687. this[runFunction]();
  11688. }
  11689. }
  11690. }
  11691. else {
  11692. for (var sector in this.sectors["active"]) {
  11693. if (this.sectors["active"].hasOwnProperty(sector)) {
  11694. // switch the global references to those of this sector
  11695. this._switchToActiveSector(sector);
  11696. var args = Array.prototype.splice.call(arguments, 1);
  11697. if (args.length > 1) {
  11698. this[runFunction](args[0],args[1]);
  11699. }
  11700. else {
  11701. this[runFunction](argument);
  11702. }
  11703. }
  11704. }
  11705. }
  11706. // we revert the global references back to our active sector
  11707. this._loadLatestSector();
  11708. },
  11709. /**
  11710. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11711. *
  11712. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11713. * | we dont pass the function itself because then the "this" is the window object
  11714. * | instead of the Graph object
  11715. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11716. * @private
  11717. */
  11718. _doInSupportSector : function(runFunction,argument) {
  11719. if (argument === undefined) {
  11720. this._switchToSupportSector();
  11721. this[runFunction]();
  11722. }
  11723. else {
  11724. this._switchToSupportSector();
  11725. var args = Array.prototype.splice.call(arguments, 1);
  11726. if (args.length > 1) {
  11727. this[runFunction](args[0],args[1]);
  11728. }
  11729. else {
  11730. this[runFunction](argument);
  11731. }
  11732. }
  11733. // we revert the global references back to our active sector
  11734. this._loadLatestSector();
  11735. },
  11736. /**
  11737. * This runs a function in all frozen sectors. This is used in the _redraw().
  11738. *
  11739. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11740. * | we don't pass the function itself because then the "this" is the window object
  11741. * | instead of the Graph object
  11742. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11743. * @private
  11744. */
  11745. _doInAllFrozenSectors : function(runFunction,argument) {
  11746. if (argument === undefined) {
  11747. for (var sector in this.sectors["frozen"]) {
  11748. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11749. // switch the global references to those of this sector
  11750. this._switchToFrozenSector(sector);
  11751. this[runFunction]();
  11752. }
  11753. }
  11754. }
  11755. else {
  11756. for (var sector in this.sectors["frozen"]) {
  11757. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11758. // switch the global references to those of this sector
  11759. this._switchToFrozenSector(sector);
  11760. var args = Array.prototype.splice.call(arguments, 1);
  11761. if (args.length > 1) {
  11762. this[runFunction](args[0],args[1]);
  11763. }
  11764. else {
  11765. this[runFunction](argument);
  11766. }
  11767. }
  11768. }
  11769. }
  11770. this._loadLatestSector();
  11771. },
  11772. /**
  11773. * This runs a function in all sectors. This is used in the _redraw().
  11774. *
  11775. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11776. * | we don't pass the function itself because then the "this" is the window object
  11777. * | instead of the Graph object
  11778. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11779. * @private
  11780. */
  11781. _doInAllSectors : function(runFunction,argument) {
  11782. var args = Array.prototype.splice.call(arguments, 1);
  11783. if (argument === undefined) {
  11784. this._doInAllActiveSectors(runFunction);
  11785. this._doInAllFrozenSectors(runFunction);
  11786. }
  11787. else {
  11788. if (args.length > 1) {
  11789. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11790. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11791. }
  11792. else {
  11793. this._doInAllActiveSectors(runFunction,argument);
  11794. this._doInAllFrozenSectors(runFunction,argument);
  11795. }
  11796. }
  11797. },
  11798. /**
  11799. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11800. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11801. *
  11802. * @private
  11803. */
  11804. _clearNodeIndexList : function() {
  11805. var sector = this._sector();
  11806. this.sectors["active"][sector]["nodeIndices"] = [];
  11807. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11808. },
  11809. /**
  11810. * Draw the encompassing sector node
  11811. *
  11812. * @param ctx
  11813. * @param sectorType
  11814. * @private
  11815. */
  11816. _drawSectorNodes : function(ctx,sectorType) {
  11817. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11818. for (var sector in this.sectors[sectorType]) {
  11819. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11820. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11821. this._switchToSector(sector,sectorType);
  11822. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11823. for (var nodeId in this.nodes) {
  11824. if (this.nodes.hasOwnProperty(nodeId)) {
  11825. node = this.nodes[nodeId];
  11826. node.resize(ctx);
  11827. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11828. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11829. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11830. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11831. }
  11832. }
  11833. node = this.sectors[sectorType][sector]["drawingNode"];
  11834. node.x = 0.5 * (maxX + minX);
  11835. node.y = 0.5 * (maxY + minY);
  11836. node.width = 2 * (node.x - minX);
  11837. node.height = 2 * (node.y - minY);
  11838. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11839. node.setScale(this.scale);
  11840. node._drawCircle(ctx);
  11841. }
  11842. }
  11843. }
  11844. },
  11845. _drawAllSectorNodes : function(ctx) {
  11846. this._drawSectorNodes(ctx,"frozen");
  11847. this._drawSectorNodes(ctx,"active");
  11848. this._loadLatestSector();
  11849. }
  11850. };
  11851. /**
  11852. * Creation of the ClusterMixin var.
  11853. *
  11854. * This contains all the functions the Graph object can use to employ clustering
  11855. *
  11856. * Alex de Mulder
  11857. * 21-01-2013
  11858. */
  11859. var ClusterMixin = {
  11860. /**
  11861. * This is only called in the constructor of the graph object
  11862. *
  11863. */
  11864. startWithClustering : function() {
  11865. // cluster if the data set is big
  11866. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11867. // updates the lables after clustering
  11868. this.updateLabels();
  11869. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11870. // the setData function.
  11871. if (this.stabilize) {
  11872. this._stabilize();
  11873. }
  11874. this.start();
  11875. },
  11876. /**
  11877. * This function clusters until the initialMaxNodes has been reached
  11878. *
  11879. * @param {Number} maxNumberOfNodes
  11880. * @param {Boolean} reposition
  11881. */
  11882. clusterToFit : function(maxNumberOfNodes, reposition) {
  11883. var numberOfNodes = this.nodeIndices.length;
  11884. var maxLevels = 50;
  11885. var level = 0;
  11886. // we first cluster the hubs, then we pull in the outliers, repeat
  11887. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11888. if (level % 3 == 0) {
  11889. this.forceAggregateHubs(true);
  11890. this.normalizeClusterLevels();
  11891. }
  11892. else {
  11893. this.increaseClusterLevel(); // this also includes a cluster normalization
  11894. }
  11895. numberOfNodes = this.nodeIndices.length;
  11896. level += 1;
  11897. }
  11898. // after the clustering we reposition the nodes to reduce the initial chaos
  11899. if (level > 0 && reposition == true) {
  11900. this.repositionNodes();
  11901. }
  11902. this._updateCalculationNodes();
  11903. },
  11904. /**
  11905. * This function can be called to open up a specific cluster. It is only called by
  11906. * It will unpack the cluster back one level.
  11907. *
  11908. * @param node | Node object: cluster to open.
  11909. */
  11910. openCluster : function(node) {
  11911. var isMovingBeforeClustering = this.moving;
  11912. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11913. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11914. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11915. this._addSector(node);
  11916. var level = 0;
  11917. // we decluster until we reach a decent number of nodes
  11918. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11919. this.decreaseClusterLevel();
  11920. level += 1;
  11921. }
  11922. }
  11923. else {
  11924. this._expandClusterNode(node,false,true);
  11925. // update the index list, dynamic edges and labels
  11926. this._updateNodeIndexList();
  11927. this._updateDynamicEdges();
  11928. this._updateCalculationNodes();
  11929. this.updateLabels();
  11930. }
  11931. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11932. if (this.moving != isMovingBeforeClustering) {
  11933. this.start();
  11934. }
  11935. },
  11936. /**
  11937. * This calls the updateClustes with default arguments
  11938. */
  11939. updateClustersDefault : function() {
  11940. if (this.constants.clustering.enabled == true) {
  11941. this.updateClusters(0,false,false);
  11942. }
  11943. },
  11944. /**
  11945. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11946. * be clustered with their connected node. This can be repeated as many times as needed.
  11947. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11948. */
  11949. increaseClusterLevel : function() {
  11950. this.updateClusters(-1,false,true);
  11951. },
  11952. /**
  11953. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11954. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11955. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11956. */
  11957. decreaseClusterLevel : function() {
  11958. this.updateClusters(1,false,true);
  11959. },
  11960. /**
  11961. * This is the main clustering function. It clusters and declusters on zoom or forced
  11962. * This function clusters on zoom, it can be called with a predefined zoom direction
  11963. * If out, check if we can form clusters, if in, check if we can open clusters.
  11964. * This function is only called from _zoom()
  11965. *
  11966. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11967. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11968. * @param {Boolean} force | enabled or disable forcing
  11969. * @param {Boolean} doNotStart | if true do not call start
  11970. *
  11971. */
  11972. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11973. var isMovingBeforeClustering = this.moving;
  11974. var amountOfNodes = this.nodeIndices.length;
  11975. // on zoom out collapse the sector if the scale is at the level the sector was made
  11976. if (this.previousScale > this.scale && zoomDirection == 0) {
  11977. this._collapseSector();
  11978. }
  11979. // check if we zoom in or out
  11980. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11981. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11982. // outer nodes determines if it is being clustered
  11983. this._formClusters(force);
  11984. }
  11985. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11986. if (force == true) {
  11987. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11988. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11989. this._openClusters(recursive,force);
  11990. }
  11991. else {
  11992. // if a cluster takes up a set percentage of the active window
  11993. this._openClustersBySize();
  11994. }
  11995. }
  11996. this._updateNodeIndexList();
  11997. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11998. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11999. this._aggregateHubs(force);
  12000. this._updateNodeIndexList();
  12001. }
  12002. // we now reduce chains.
  12003. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12004. this.handleChains();
  12005. this._updateNodeIndexList();
  12006. }
  12007. this.previousScale = this.scale;
  12008. // rest of the update the index list, dynamic edges and labels
  12009. this._updateDynamicEdges();
  12010. this.updateLabels();
  12011. // if a cluster was formed, we increase the clusterSession
  12012. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12013. this.clusterSession += 1;
  12014. // if clusters have been made, we normalize the cluster level
  12015. this.normalizeClusterLevels();
  12016. }
  12017. if (doNotStart == false || doNotStart === undefined) {
  12018. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12019. if (this.moving != isMovingBeforeClustering) {
  12020. this.start();
  12021. }
  12022. }
  12023. this._updateCalculationNodes();
  12024. },
  12025. /**
  12026. * This function handles the chains. It is called on every updateClusters().
  12027. */
  12028. handleChains : function() {
  12029. // after clustering we check how many chains there are
  12030. var chainPercentage = this._getChainFraction();
  12031. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12032. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12033. }
  12034. },
  12035. /**
  12036. * this functions starts clustering by hubs
  12037. * The minimum hub threshold is set globally
  12038. *
  12039. * @private
  12040. */
  12041. _aggregateHubs : function(force) {
  12042. this._getHubSize();
  12043. this._formClustersByHub(force,false);
  12044. },
  12045. /**
  12046. * This function is fired by keypress. It forces hubs to form.
  12047. *
  12048. */
  12049. forceAggregateHubs : function(doNotStart) {
  12050. var isMovingBeforeClustering = this.moving;
  12051. var amountOfNodes = this.nodeIndices.length;
  12052. this._aggregateHubs(true);
  12053. // update the index list, dynamic edges and labels
  12054. this._updateNodeIndexList();
  12055. this._updateDynamicEdges();
  12056. this.updateLabels();
  12057. // if a cluster was formed, we increase the clusterSession
  12058. if (this.nodeIndices.length != amountOfNodes) {
  12059. this.clusterSession += 1;
  12060. }
  12061. if (doNotStart == false || doNotStart === undefined) {
  12062. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12063. if (this.moving != isMovingBeforeClustering) {
  12064. this.start();
  12065. }
  12066. }
  12067. },
  12068. /**
  12069. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12070. *
  12071. * @private
  12072. */
  12073. _openClustersBySize : function() {
  12074. for (var nodeId in this.nodes) {
  12075. if (this.nodes.hasOwnProperty(nodeId)) {
  12076. var node = this.nodes[nodeId];
  12077. if (node.inView() == true) {
  12078. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12079. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12080. this.openCluster(node);
  12081. }
  12082. }
  12083. }
  12084. }
  12085. },
  12086. /**
  12087. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12088. * has to be opened based on the current zoom level.
  12089. *
  12090. * @private
  12091. */
  12092. _openClusters : function(recursive,force) {
  12093. for (var i = 0; i < this.nodeIndices.length; i++) {
  12094. var node = this.nodes[this.nodeIndices[i]];
  12095. this._expandClusterNode(node,recursive,force);
  12096. this._updateCalculationNodes();
  12097. }
  12098. },
  12099. /**
  12100. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12101. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12102. * This recursive behaviour is optional and can be set by the recursive argument.
  12103. *
  12104. * @param {Node} parentNode | to check for cluster and expand
  12105. * @param {Boolean} recursive | enabled or disable recursive calling
  12106. * @param {Boolean} force | enabled or disable forcing
  12107. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12108. * @private
  12109. */
  12110. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12111. // first check if node is a cluster
  12112. if (parentNode.clusterSize > 1) {
  12113. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12114. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12115. openAll = true;
  12116. }
  12117. recursive = openAll ? true : recursive;
  12118. // if the last child has been added on a smaller scale than current scale decluster
  12119. if (parentNode.formationScale < this.scale || force == true) {
  12120. // we will check if any of the contained child nodes should be removed from the cluster
  12121. for (var containedNodeId in parentNode.containedNodes) {
  12122. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12123. var childNode = parentNode.containedNodes[containedNodeId];
  12124. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12125. // the largest cluster is the one that comes from outside
  12126. if (force == true) {
  12127. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12128. || openAll) {
  12129. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12130. }
  12131. }
  12132. else {
  12133. if (this._nodeInActiveArea(parentNode)) {
  12134. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12135. }
  12136. }
  12137. }
  12138. }
  12139. }
  12140. }
  12141. },
  12142. /**
  12143. * ONLY CALLED FROM _expandClusterNode
  12144. *
  12145. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12146. * the child node from the parent contained_node object and put it back into the global nodes object.
  12147. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12148. *
  12149. * @param {Node} parentNode | the parent node
  12150. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12151. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12152. * With force and recursive both true, the entire cluster is unpacked
  12153. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12154. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12155. * @private
  12156. */
  12157. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12158. var childNode = parentNode.containedNodes[containedNodeId];
  12159. // if child node has been added on smaller scale than current, kick out
  12160. if (childNode.formationScale < this.scale || force == true) {
  12161. // unselect all selected items
  12162. this._unselectAll();
  12163. // put the child node back in the global nodes object
  12164. this.nodes[containedNodeId] = childNode;
  12165. // release the contained edges from this childNode back into the global edges
  12166. this._releaseContainedEdges(parentNode,childNode);
  12167. // reconnect rerouted edges to the childNode
  12168. this._connectEdgeBackToChild(parentNode,childNode);
  12169. // validate all edges in dynamicEdges
  12170. this._validateEdges(parentNode);
  12171. // undo the changes from the clustering operation on the parent node
  12172. parentNode.mass -= childNode.mass;
  12173. parentNode.clusterSize -= childNode.clusterSize;
  12174. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12175. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12176. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12177. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12178. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12179. // remove node from the list
  12180. delete parentNode.containedNodes[containedNodeId];
  12181. // check if there are other childs with this clusterSession in the parent.
  12182. var othersPresent = false;
  12183. for (var childNodeId in parentNode.containedNodes) {
  12184. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12185. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12186. othersPresent = true;
  12187. break;
  12188. }
  12189. }
  12190. }
  12191. // if there are no others, remove the cluster session from the list
  12192. if (othersPresent == false) {
  12193. parentNode.clusterSessions.pop();
  12194. }
  12195. this._repositionBezierNodes(childNode);
  12196. // this._repositionBezierNodes(parentNode);
  12197. // remove the clusterSession from the child node
  12198. childNode.clusterSession = 0;
  12199. // recalculate the size of the node on the next time the node is rendered
  12200. parentNode.clearSizeCache();
  12201. // restart the simulation to reorganise all nodes
  12202. this.moving = true;
  12203. }
  12204. // check if a further expansion step is possible if recursivity is enabled
  12205. if (recursive == true) {
  12206. this._expandClusterNode(childNode,recursive,force,openAll);
  12207. }
  12208. },
  12209. /**
  12210. * position the bezier nodes at the center of the edges
  12211. *
  12212. * @param node
  12213. * @private
  12214. */
  12215. _repositionBezierNodes : function(node) {
  12216. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12217. node.dynamicEdges[i].positionBezierNode();
  12218. }
  12219. },
  12220. /**
  12221. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12222. * This function is called only from updateClusters()
  12223. * forceLevelCollapse ignores the length of the edge and collapses one level
  12224. * This means that a node with only one edge will be clustered with its connected node
  12225. *
  12226. * @private
  12227. * @param {Boolean} force
  12228. */
  12229. _formClusters : function(force) {
  12230. if (force == false) {
  12231. this._formClustersByZoom();
  12232. }
  12233. else {
  12234. this._forceClustersByZoom();
  12235. }
  12236. },
  12237. /**
  12238. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12239. *
  12240. * @private
  12241. */
  12242. _formClustersByZoom : function() {
  12243. var dx,dy,length,
  12244. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12245. // check if any edges are shorter than minLength and start the clustering
  12246. // the clustering favours the node with the larger mass
  12247. for (var edgeId in this.edges) {
  12248. if (this.edges.hasOwnProperty(edgeId)) {
  12249. var edge = this.edges[edgeId];
  12250. if (edge.connected) {
  12251. if (edge.toId != edge.fromId) {
  12252. dx = (edge.to.x - edge.from.x);
  12253. dy = (edge.to.y - edge.from.y);
  12254. length = Math.sqrt(dx * dx + dy * dy);
  12255. if (length < minLength) {
  12256. // first check which node is larger
  12257. var parentNode = edge.from;
  12258. var childNode = edge.to;
  12259. if (edge.to.mass > edge.from.mass) {
  12260. parentNode = edge.to;
  12261. childNode = edge.from;
  12262. }
  12263. if (childNode.dynamicEdgesLength == 1) {
  12264. this._addToCluster(parentNode,childNode,false);
  12265. }
  12266. else if (parentNode.dynamicEdgesLength == 1) {
  12267. this._addToCluster(childNode,parentNode,false);
  12268. }
  12269. }
  12270. }
  12271. }
  12272. }
  12273. }
  12274. },
  12275. /**
  12276. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12277. * connected node.
  12278. *
  12279. * @private
  12280. */
  12281. _forceClustersByZoom : function() {
  12282. for (var nodeId in this.nodes) {
  12283. // another node could have absorbed this child.
  12284. if (this.nodes.hasOwnProperty(nodeId)) {
  12285. var childNode = this.nodes[nodeId];
  12286. // the edges can be swallowed by another decrease
  12287. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12288. var edge = childNode.dynamicEdges[0];
  12289. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12290. // group to the largest node
  12291. if (childNode.id != parentNode.id) {
  12292. if (parentNode.mass > childNode.mass) {
  12293. this._addToCluster(parentNode,childNode,true);
  12294. }
  12295. else {
  12296. this._addToCluster(childNode,parentNode,true);
  12297. }
  12298. }
  12299. }
  12300. }
  12301. }
  12302. },
  12303. /**
  12304. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12305. * This function clusters a node to its smallest connected neighbour.
  12306. *
  12307. * @param node
  12308. * @private
  12309. */
  12310. _clusterToSmallestNeighbour : function(node) {
  12311. var smallestNeighbour = -1;
  12312. var smallestNeighbourNode = null;
  12313. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12314. if (node.dynamicEdges[i] !== undefined) {
  12315. var neighbour = null;
  12316. if (node.dynamicEdges[i].fromId != node.id) {
  12317. neighbour = node.dynamicEdges[i].from;
  12318. }
  12319. else if (node.dynamicEdges[i].toId != node.id) {
  12320. neighbour = node.dynamicEdges[i].to;
  12321. }
  12322. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12323. smallestNeighbour = neighbour.clusterSessions.length;
  12324. smallestNeighbourNode = neighbour;
  12325. }
  12326. }
  12327. }
  12328. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12329. this._addToCluster(neighbour, node, true);
  12330. }
  12331. },
  12332. /**
  12333. * This function forms clusters from hubs, it loops over all nodes
  12334. *
  12335. * @param {Boolean} force | Disregard zoom level
  12336. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12337. * @private
  12338. */
  12339. _formClustersByHub : function(force, onlyEqual) {
  12340. // we loop over all nodes in the list
  12341. for (var nodeId in this.nodes) {
  12342. // we check if it is still available since it can be used by the clustering in this loop
  12343. if (this.nodes.hasOwnProperty(nodeId)) {
  12344. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12345. }
  12346. }
  12347. },
  12348. /**
  12349. * This function forms a cluster from a specific preselected hub node
  12350. *
  12351. * @param {Node} hubNode | the node we will cluster as a hub
  12352. * @param {Boolean} force | Disregard zoom level
  12353. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12354. * @param {Number} [absorptionSizeOffset] |
  12355. * @private
  12356. */
  12357. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12358. if (absorptionSizeOffset === undefined) {
  12359. absorptionSizeOffset = 0;
  12360. }
  12361. // we decide if the node is a hub
  12362. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12363. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12364. // initialize variables
  12365. var dx,dy,length;
  12366. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12367. var allowCluster = false;
  12368. // we create a list of edges because the dynamicEdges change over the course of this loop
  12369. var edgesIdarray = [];
  12370. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12371. for (var j = 0; j < amountOfInitialEdges; j++) {
  12372. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12373. }
  12374. // if the hub clustering is not forces, we check if one of the edges connected
  12375. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12376. if (force == false) {
  12377. allowCluster = false;
  12378. for (j = 0; j < amountOfInitialEdges; j++) {
  12379. var edge = this.edges[edgesIdarray[j]];
  12380. if (edge !== undefined) {
  12381. if (edge.connected) {
  12382. if (edge.toId != edge.fromId) {
  12383. dx = (edge.to.x - edge.from.x);
  12384. dy = (edge.to.y - edge.from.y);
  12385. length = Math.sqrt(dx * dx + dy * dy);
  12386. if (length < minLength) {
  12387. allowCluster = true;
  12388. break;
  12389. }
  12390. }
  12391. }
  12392. }
  12393. }
  12394. }
  12395. // start the clustering if allowed
  12396. if ((!force && allowCluster) || force) {
  12397. // we loop over all edges INITIALLY connected to this hub
  12398. for (j = 0; j < amountOfInitialEdges; j++) {
  12399. edge = this.edges[edgesIdarray[j]];
  12400. // the edge can be clustered by this function in a previous loop
  12401. if (edge !== undefined) {
  12402. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12403. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12404. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12405. (childNode.id != hubNode.id)) {
  12406. this._addToCluster(hubNode,childNode,force);
  12407. }
  12408. }
  12409. }
  12410. }
  12411. }
  12412. },
  12413. /**
  12414. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12415. *
  12416. * @param {Node} parentNode | this is the node that will house the child node
  12417. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12418. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12419. * @private
  12420. */
  12421. _addToCluster : function(parentNode, childNode, force) {
  12422. // join child node in the parent node
  12423. parentNode.containedNodes[childNode.id] = childNode;
  12424. // manage all the edges connected to the child and parent nodes
  12425. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12426. var edge = childNode.dynamicEdges[i];
  12427. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12428. this._addToContainedEdges(parentNode,childNode,edge);
  12429. }
  12430. else {
  12431. this._connectEdgeToCluster(parentNode,childNode,edge);
  12432. }
  12433. }
  12434. // a contained node has no dynamic edges.
  12435. childNode.dynamicEdges = [];
  12436. // remove circular edges from clusters
  12437. this._containCircularEdgesFromNode(parentNode,childNode);
  12438. // remove the childNode from the global nodes object
  12439. delete this.nodes[childNode.id];
  12440. // update the properties of the child and parent
  12441. var massBefore = parentNode.mass;
  12442. childNode.clusterSession = this.clusterSession;
  12443. parentNode.mass += childNode.mass;
  12444. parentNode.clusterSize += childNode.clusterSize;
  12445. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12446. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12447. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12448. parentNode.clusterSessions.push(this.clusterSession);
  12449. }
  12450. // forced clusters only open from screen size and double tap
  12451. if (force == true) {
  12452. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12453. parentNode.formationScale = 0;
  12454. }
  12455. else {
  12456. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12457. }
  12458. // recalculate the size of the node on the next time the node is rendered
  12459. parentNode.clearSizeCache();
  12460. // set the pop-out scale for the childnode
  12461. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12462. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12463. childNode.clearVelocity();
  12464. // the mass has altered, preservation of energy dictates the velocity to be updated
  12465. parentNode.updateVelocity(massBefore);
  12466. // restart the simulation to reorganise all nodes
  12467. this.moving = true;
  12468. },
  12469. /**
  12470. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12471. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12472. * It has to be called if a level is collapsed. It is called by _formClusters().
  12473. * @private
  12474. */
  12475. _updateDynamicEdges : function() {
  12476. for (var i = 0; i < this.nodeIndices.length; i++) {
  12477. var node = this.nodes[this.nodeIndices[i]];
  12478. node.dynamicEdgesLength = node.dynamicEdges.length;
  12479. // this corrects for multiple edges pointing at the same other node
  12480. var correction = 0;
  12481. if (node.dynamicEdgesLength > 1) {
  12482. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12483. var edgeToId = node.dynamicEdges[j].toId;
  12484. var edgeFromId = node.dynamicEdges[j].fromId;
  12485. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12486. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12487. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12488. correction += 1;
  12489. }
  12490. }
  12491. }
  12492. }
  12493. node.dynamicEdgesLength -= correction;
  12494. }
  12495. },
  12496. /**
  12497. * This adds an edge from the childNode to the contained edges of the parent node
  12498. *
  12499. * @param parentNode | Node object
  12500. * @param childNode | Node object
  12501. * @param edge | Edge object
  12502. * @private
  12503. */
  12504. _addToContainedEdges : function(parentNode, childNode, edge) {
  12505. // create an array object if it does not yet exist for this childNode
  12506. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12507. parentNode.containedEdges[childNode.id] = []
  12508. }
  12509. // add this edge to the list
  12510. parentNode.containedEdges[childNode.id].push(edge);
  12511. // remove the edge from the global edges object
  12512. delete this.edges[edge.id];
  12513. // remove the edge from the parent object
  12514. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12515. if (parentNode.dynamicEdges[i].id == edge.id) {
  12516. parentNode.dynamicEdges.splice(i,1);
  12517. break;
  12518. }
  12519. }
  12520. },
  12521. /**
  12522. * This function connects an edge that was connected to a child node to the parent node.
  12523. * It keeps track of which nodes it has been connected to with the originalId array.
  12524. *
  12525. * @param {Node} parentNode | Node object
  12526. * @param {Node} childNode | Node object
  12527. * @param {Edge} edge | Edge object
  12528. * @private
  12529. */
  12530. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12531. // handle circular edges
  12532. if (edge.toId == edge.fromId) {
  12533. this._addToContainedEdges(parentNode, childNode, edge);
  12534. }
  12535. else {
  12536. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12537. edge.originalToId.push(childNode.id);
  12538. edge.to = parentNode;
  12539. edge.toId = parentNode.id;
  12540. }
  12541. else { // edge connected to other node with the "from" side
  12542. edge.originalFromId.push(childNode.id);
  12543. edge.from = parentNode;
  12544. edge.fromId = parentNode.id;
  12545. }
  12546. this._addToReroutedEdges(parentNode,childNode,edge);
  12547. }
  12548. },
  12549. /**
  12550. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12551. * these edges inside of the cluster.
  12552. *
  12553. * @param parentNode
  12554. * @param childNode
  12555. * @private
  12556. */
  12557. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12558. // manage all the edges connected to the child and parent nodes
  12559. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12560. var edge = parentNode.dynamicEdges[i];
  12561. // handle circular edges
  12562. if (edge.toId == edge.fromId) {
  12563. this._addToContainedEdges(parentNode, childNode, edge);
  12564. }
  12565. }
  12566. },
  12567. /**
  12568. * This adds an edge from the childNode to the rerouted edges of the parent node
  12569. *
  12570. * @param parentNode | Node object
  12571. * @param childNode | Node object
  12572. * @param edge | Edge object
  12573. * @private
  12574. */
  12575. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12576. // create an array object if it does not yet exist for this childNode
  12577. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12578. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12579. parentNode.reroutedEdges[childNode.id] = [];
  12580. }
  12581. parentNode.reroutedEdges[childNode.id].push(edge);
  12582. // this edge becomes part of the dynamicEdges of the cluster node
  12583. parentNode.dynamicEdges.push(edge);
  12584. },
  12585. /**
  12586. * This function connects an edge that was connected to a cluster node back to the child node.
  12587. *
  12588. * @param parentNode | Node object
  12589. * @param childNode | Node object
  12590. * @private
  12591. */
  12592. _connectEdgeBackToChild : function(parentNode, childNode) {
  12593. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12594. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12595. var edge = parentNode.reroutedEdges[childNode.id][i];
  12596. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12597. edge.originalFromId.pop();
  12598. edge.fromId = childNode.id;
  12599. edge.from = childNode;
  12600. }
  12601. else {
  12602. edge.originalToId.pop();
  12603. edge.toId = childNode.id;
  12604. edge.to = childNode;
  12605. }
  12606. // append this edge to the list of edges connecting to the childnode
  12607. childNode.dynamicEdges.push(edge);
  12608. // remove the edge from the parent object
  12609. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12610. if (parentNode.dynamicEdges[j].id == edge.id) {
  12611. parentNode.dynamicEdges.splice(j,1);
  12612. break;
  12613. }
  12614. }
  12615. }
  12616. // remove the entry from the rerouted edges
  12617. delete parentNode.reroutedEdges[childNode.id];
  12618. }
  12619. },
  12620. /**
  12621. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12622. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12623. * parentNode
  12624. *
  12625. * @param parentNode | Node object
  12626. * @private
  12627. */
  12628. _validateEdges : function(parentNode) {
  12629. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12630. var edge = parentNode.dynamicEdges[i];
  12631. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12632. parentNode.dynamicEdges.splice(i,1);
  12633. }
  12634. }
  12635. },
  12636. /**
  12637. * This function released the contained edges back into the global domain and puts them back into the
  12638. * dynamic edges of both parent and child.
  12639. *
  12640. * @param {Node} parentNode |
  12641. * @param {Node} childNode |
  12642. * @private
  12643. */
  12644. _releaseContainedEdges : function(parentNode, childNode) {
  12645. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12646. var edge = parentNode.containedEdges[childNode.id][i];
  12647. // put the edge back in the global edges object
  12648. this.edges[edge.id] = edge;
  12649. // put the edge back in the dynamic edges of the child and parent
  12650. childNode.dynamicEdges.push(edge);
  12651. parentNode.dynamicEdges.push(edge);
  12652. }
  12653. // remove the entry from the contained edges
  12654. delete parentNode.containedEdges[childNode.id];
  12655. },
  12656. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12657. /**
  12658. * This updates the node labels for all nodes (for debugging purposes)
  12659. */
  12660. updateLabels : function() {
  12661. var nodeId;
  12662. // update node labels
  12663. for (nodeId in this.nodes) {
  12664. if (this.nodes.hasOwnProperty(nodeId)) {
  12665. var node = this.nodes[nodeId];
  12666. if (node.clusterSize > 1) {
  12667. node.label = "[".concat(String(node.clusterSize),"]");
  12668. }
  12669. }
  12670. }
  12671. // update node labels
  12672. for (nodeId in this.nodes) {
  12673. if (this.nodes.hasOwnProperty(nodeId)) {
  12674. node = this.nodes[nodeId];
  12675. if (node.clusterSize == 1) {
  12676. if (node.originalLabel !== undefined) {
  12677. node.label = node.originalLabel;
  12678. }
  12679. else {
  12680. node.label = String(node.id);
  12681. }
  12682. }
  12683. }
  12684. }
  12685. // /* Debug Override */
  12686. // for (nodeId in this.nodes) {
  12687. // if (this.nodes.hasOwnProperty(nodeId)) {
  12688. // node = this.nodes[nodeId];
  12689. // node.label = String(node.level);
  12690. // }
  12691. // }
  12692. },
  12693. /**
  12694. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12695. * if the rest of the nodes are already a few cluster levels in.
  12696. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12697. * clustered enough to the clusterToSmallestNeighbours function.
  12698. */
  12699. normalizeClusterLevels : function() {
  12700. var maxLevel = 0;
  12701. var minLevel = 1e9;
  12702. var clusterLevel = 0;
  12703. var nodeId;
  12704. // we loop over all nodes in the list
  12705. for (nodeId in this.nodes) {
  12706. if (this.nodes.hasOwnProperty(nodeId)) {
  12707. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12708. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12709. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12710. }
  12711. }
  12712. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12713. var amountOfNodes = this.nodeIndices.length;
  12714. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12715. // we loop over all nodes in the list
  12716. for (nodeId in this.nodes) {
  12717. if (this.nodes.hasOwnProperty(nodeId)) {
  12718. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12719. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12720. }
  12721. }
  12722. }
  12723. this._updateNodeIndexList();
  12724. this._updateDynamicEdges();
  12725. // if a cluster was formed, we increase the clusterSession
  12726. if (this.nodeIndices.length != amountOfNodes) {
  12727. this.clusterSession += 1;
  12728. }
  12729. }
  12730. },
  12731. /**
  12732. * This function determines if the cluster we want to decluster is in the active area
  12733. * this means around the zoom center
  12734. *
  12735. * @param {Node} node
  12736. * @returns {boolean}
  12737. * @private
  12738. */
  12739. _nodeInActiveArea : function(node) {
  12740. return (
  12741. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12742. &&
  12743. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12744. )
  12745. },
  12746. /**
  12747. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12748. * It puts large clusters away from the center and randomizes the order.
  12749. *
  12750. */
  12751. repositionNodes : function() {
  12752. for (var i = 0; i < this.nodeIndices.length; i++) {
  12753. var node = this.nodes[this.nodeIndices[i]];
  12754. if ((node.xFixed == false || node.yFixed == false)) {
  12755. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12756. var angle = 2 * Math.PI * Math.random();
  12757. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12758. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12759. this._repositionBezierNodes(node);
  12760. }
  12761. }
  12762. },
  12763. /**
  12764. * We determine how many connections denote an important hub.
  12765. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12766. *
  12767. * @private
  12768. */
  12769. _getHubSize : function() {
  12770. var average = 0;
  12771. var averageSquared = 0;
  12772. var hubCounter = 0;
  12773. var largestHub = 0;
  12774. for (var i = 0; i < this.nodeIndices.length; i++) {
  12775. var node = this.nodes[this.nodeIndices[i]];
  12776. if (node.dynamicEdgesLength > largestHub) {
  12777. largestHub = node.dynamicEdgesLength;
  12778. }
  12779. average += node.dynamicEdgesLength;
  12780. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12781. hubCounter += 1;
  12782. }
  12783. average = average / hubCounter;
  12784. averageSquared = averageSquared / hubCounter;
  12785. var variance = averageSquared - Math.pow(average,2);
  12786. var standardDeviation = Math.sqrt(variance);
  12787. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12788. // always have at least one to cluster
  12789. if (this.hubThreshold > largestHub) {
  12790. this.hubThreshold = largestHub;
  12791. }
  12792. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12793. // console.log("hubThreshold:",this.hubThreshold);
  12794. },
  12795. /**
  12796. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12797. * with this amount we can cluster specifically on these chains.
  12798. *
  12799. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12800. * @private
  12801. */
  12802. _reduceAmountOfChains : function(fraction) {
  12803. this.hubThreshold = 2;
  12804. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12805. for (var nodeId in this.nodes) {
  12806. if (this.nodes.hasOwnProperty(nodeId)) {
  12807. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12808. if (reduceAmount > 0) {
  12809. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12810. reduceAmount -= 1;
  12811. }
  12812. }
  12813. }
  12814. }
  12815. },
  12816. /**
  12817. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12818. * with this amount we can cluster specifically on these chains.
  12819. *
  12820. * @private
  12821. */
  12822. _getChainFraction : function() {
  12823. var chains = 0;
  12824. var total = 0;
  12825. for (var nodeId in this.nodes) {
  12826. if (this.nodes.hasOwnProperty(nodeId)) {
  12827. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12828. chains += 1;
  12829. }
  12830. total += 1;
  12831. }
  12832. }
  12833. return chains/total;
  12834. }
  12835. };
  12836. var SelectionMixin = {
  12837. /**
  12838. * This function can be called from the _doInAllSectors function
  12839. *
  12840. * @param object
  12841. * @param overlappingNodes
  12842. * @private
  12843. */
  12844. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12845. var nodes = this.nodes;
  12846. for (var nodeId in nodes) {
  12847. if (nodes.hasOwnProperty(nodeId)) {
  12848. if (nodes[nodeId].isOverlappingWith(object)) {
  12849. overlappingNodes.push(nodeId);
  12850. }
  12851. }
  12852. }
  12853. },
  12854. /**
  12855. * retrieve all nodes overlapping with given object
  12856. * @param {Object} object An object with parameters left, top, right, bottom
  12857. * @return {Number[]} An array with id's of the overlapping nodes
  12858. * @private
  12859. */
  12860. _getAllNodesOverlappingWith : function (object) {
  12861. var overlappingNodes = [];
  12862. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12863. return overlappingNodes;
  12864. },
  12865. /**
  12866. * Return a position object in canvasspace from a single point in screenspace
  12867. *
  12868. * @param pointer
  12869. * @returns {{left: number, top: number, right: number, bottom: number}}
  12870. * @private
  12871. */
  12872. _pointerToPositionObject : function(pointer) {
  12873. var x = this._XconvertDOMtoCanvas(pointer.x);
  12874. var y = this._YconvertDOMtoCanvas(pointer.y);
  12875. return {left: x,
  12876. top: y,
  12877. right: x,
  12878. bottom: y};
  12879. },
  12880. /**
  12881. * Get the top node at the a specific point (like a click)
  12882. *
  12883. * @param {{x: Number, y: Number}} pointer
  12884. * @return {Node | null} node
  12885. * @private
  12886. */
  12887. _getNodeAt : function (pointer) {
  12888. // we first check if this is an navigation controls element
  12889. var positionObject = this._pointerToPositionObject(pointer);
  12890. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12891. // if there are overlapping nodes, select the last one, this is the
  12892. // one which is drawn on top of the others
  12893. if (overlappingNodes.length > 0) {
  12894. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12895. }
  12896. else {
  12897. return null;
  12898. }
  12899. },
  12900. /**
  12901. * retrieve all edges overlapping with given object, selector is around center
  12902. * @param {Object} object An object with parameters left, top, right, bottom
  12903. * @return {Number[]} An array with id's of the overlapping nodes
  12904. * @private
  12905. */
  12906. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12907. var edges = this.edges;
  12908. for (var edgeId in edges) {
  12909. if (edges.hasOwnProperty(edgeId)) {
  12910. if (edges[edgeId].isOverlappingWith(object)) {
  12911. overlappingEdges.push(edgeId);
  12912. }
  12913. }
  12914. }
  12915. },
  12916. /**
  12917. * retrieve all nodes overlapping with given object
  12918. * @param {Object} object An object with parameters left, top, right, bottom
  12919. * @return {Number[]} An array with id's of the overlapping nodes
  12920. * @private
  12921. */
  12922. _getAllEdgesOverlappingWith : function (object) {
  12923. var overlappingEdges = [];
  12924. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12925. return overlappingEdges;
  12926. },
  12927. /**
  12928. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12929. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12930. *
  12931. * @param pointer
  12932. * @returns {null}
  12933. * @private
  12934. */
  12935. _getEdgeAt : function(pointer) {
  12936. var positionObject = this._pointerToPositionObject(pointer);
  12937. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12938. if (overlappingEdges.length > 0) {
  12939. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12940. }
  12941. else {
  12942. return null;
  12943. }
  12944. },
  12945. /**
  12946. * Add object to the selection array.
  12947. *
  12948. * @param obj
  12949. * @private
  12950. */
  12951. _addToSelection : function(obj) {
  12952. if (obj instanceof Node) {
  12953. this.selectionObj.nodes[obj.id] = obj;
  12954. }
  12955. else {
  12956. this.selectionObj.edges[obj.id] = obj;
  12957. }
  12958. },
  12959. /**
  12960. * Remove a single option from selection.
  12961. *
  12962. * @param {Object} obj
  12963. * @private
  12964. */
  12965. _removeFromSelection : function(obj) {
  12966. if (obj instanceof Node) {
  12967. delete this.selectionObj.nodes[obj.id];
  12968. }
  12969. else {
  12970. delete this.selectionObj.edges[obj.id];
  12971. }
  12972. },
  12973. /**
  12974. * Unselect all. The selectionObj is useful for this.
  12975. *
  12976. * @param {Boolean} [doNotTrigger] | ignore trigger
  12977. * @private
  12978. */
  12979. _unselectAll : function(doNotTrigger) {
  12980. if (doNotTrigger === undefined) {
  12981. doNotTrigger = false;
  12982. }
  12983. for(var nodeId in this.selectionObj.nodes) {
  12984. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12985. this.selectionObj.nodes[nodeId].unselect();
  12986. }
  12987. }
  12988. for(var edgeId in this.selectionObj.edges) {
  12989. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12990. this.selectionObj.edges[edgeId].unselect();
  12991. }
  12992. }
  12993. this.selectionObj = {nodes:{},edges:{}};
  12994. if (doNotTrigger == false) {
  12995. this.emit('select', this.getSelection());
  12996. }
  12997. },
  12998. /**
  12999. * Unselect all clusters. The selectionObj is useful for this.
  13000. *
  13001. * @param {Boolean} [doNotTrigger] | ignore trigger
  13002. * @private
  13003. */
  13004. _unselectClusters : function(doNotTrigger) {
  13005. if (doNotTrigger === undefined) {
  13006. doNotTrigger = false;
  13007. }
  13008. for (var nodeId in this.selectionObj.nodes) {
  13009. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13010. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13011. this.selectionObj.nodes[nodeId].unselect();
  13012. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13013. }
  13014. }
  13015. }
  13016. if (doNotTrigger == false) {
  13017. this.emit('select', this.getSelection());
  13018. }
  13019. },
  13020. /**
  13021. * return the number of selected nodes
  13022. *
  13023. * @returns {number}
  13024. * @private
  13025. */
  13026. _getSelectedNodeCount : function() {
  13027. var count = 0;
  13028. for (var nodeId in this.selectionObj.nodes) {
  13029. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13030. count += 1;
  13031. }
  13032. }
  13033. return count;
  13034. },
  13035. /**
  13036. * return the number of selected nodes
  13037. *
  13038. * @returns {number}
  13039. * @private
  13040. */
  13041. _getSelectedNode : function() {
  13042. for (var nodeId in this.selectionObj.nodes) {
  13043. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13044. return this.selectionObj.nodes[nodeId];
  13045. }
  13046. }
  13047. return null;
  13048. },
  13049. /**
  13050. * return the number of selected edges
  13051. *
  13052. * @returns {number}
  13053. * @private
  13054. */
  13055. _getSelectedEdgeCount : function() {
  13056. var count = 0;
  13057. for (var edgeId in this.selectionObj.edges) {
  13058. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13059. count += 1;
  13060. }
  13061. }
  13062. return count;
  13063. },
  13064. /**
  13065. * return the number of selected objects.
  13066. *
  13067. * @returns {number}
  13068. * @private
  13069. */
  13070. _getSelectedObjectCount : function() {
  13071. var count = 0;
  13072. for(var nodeId in this.selectionObj.nodes) {
  13073. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13074. count += 1;
  13075. }
  13076. }
  13077. for(var edgeId in this.selectionObj.edges) {
  13078. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13079. count += 1;
  13080. }
  13081. }
  13082. return count;
  13083. },
  13084. /**
  13085. * Check if anything is selected
  13086. *
  13087. * @returns {boolean}
  13088. * @private
  13089. */
  13090. _selectionIsEmpty : function() {
  13091. for(var nodeId in this.selectionObj.nodes) {
  13092. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13093. return false;
  13094. }
  13095. }
  13096. for(var edgeId in this.selectionObj.edges) {
  13097. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13098. return false;
  13099. }
  13100. }
  13101. return true;
  13102. },
  13103. /**
  13104. * check if one of the selected nodes is a cluster.
  13105. *
  13106. * @returns {boolean}
  13107. * @private
  13108. */
  13109. _clusterInSelection : function() {
  13110. for(var nodeId in this.selectionObj.nodes) {
  13111. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13112. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13113. return true;
  13114. }
  13115. }
  13116. }
  13117. return false;
  13118. },
  13119. /**
  13120. * select the edges connected to the node that is being selected
  13121. *
  13122. * @param {Node} node
  13123. * @private
  13124. */
  13125. _selectConnectedEdges : function(node) {
  13126. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13127. var edge = node.dynamicEdges[i];
  13128. edge.select();
  13129. this._addToSelection(edge);
  13130. }
  13131. },
  13132. /**
  13133. * unselect the edges connected to the node that is being selected
  13134. *
  13135. * @param {Node} node
  13136. * @private
  13137. */
  13138. _unselectConnectedEdges : function(node) {
  13139. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13140. var edge = node.dynamicEdges[i];
  13141. edge.unselect();
  13142. this._removeFromSelection(edge);
  13143. }
  13144. },
  13145. /**
  13146. * This is called when someone clicks on a node. either select or deselect it.
  13147. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13148. *
  13149. * @param {Node || Edge} object
  13150. * @param {Boolean} append
  13151. * @param {Boolean} [doNotTrigger] | ignore trigger
  13152. * @private
  13153. */
  13154. _selectObject : function(object, append, doNotTrigger) {
  13155. if (doNotTrigger === undefined) {
  13156. doNotTrigger = false;
  13157. }
  13158. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13159. this._unselectAll(true);
  13160. }
  13161. if (object.selected == false) {
  13162. object.select();
  13163. this._addToSelection(object);
  13164. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13165. this._selectConnectedEdges(object);
  13166. }
  13167. }
  13168. else {
  13169. object.unselect();
  13170. this._removeFromSelection(object);
  13171. }
  13172. if (doNotTrigger == false) {
  13173. this.emit('select', this.getSelection());
  13174. }
  13175. },
  13176. /**
  13177. * handles the selection part of the touch, only for navigation controls elements;
  13178. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13179. * This is the most responsive solution
  13180. *
  13181. * @param {Object} pointer
  13182. * @private
  13183. */
  13184. _handleTouch : function(pointer) {
  13185. },
  13186. /**
  13187. * handles the selection part of the tap;
  13188. *
  13189. * @param {Object} pointer
  13190. * @private
  13191. */
  13192. _handleTap : function(pointer) {
  13193. var node = this._getNodeAt(pointer);
  13194. if (node != null) {
  13195. this._selectObject(node,false);
  13196. }
  13197. else {
  13198. var edge = this._getEdgeAt(pointer);
  13199. if (edge != null) {
  13200. this._selectObject(edge,false);
  13201. }
  13202. else {
  13203. this._unselectAll();
  13204. }
  13205. }
  13206. this.emit("click", this.getSelection());
  13207. this._redraw();
  13208. },
  13209. /**
  13210. * handles the selection part of the double tap and opens a cluster if needed
  13211. *
  13212. * @param {Object} pointer
  13213. * @private
  13214. */
  13215. _handleDoubleTap : function(pointer) {
  13216. var node = this._getNodeAt(pointer);
  13217. if (node != null && node !== undefined) {
  13218. // we reset the areaCenter here so the opening of the node will occur
  13219. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  13220. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  13221. this.openCluster(node);
  13222. }
  13223. this.emit("doubleClick", this.getSelection());
  13224. },
  13225. /**
  13226. * Handle the onHold selection part
  13227. *
  13228. * @param pointer
  13229. * @private
  13230. */
  13231. _handleOnHold : function(pointer) {
  13232. var node = this._getNodeAt(pointer);
  13233. if (node != null) {
  13234. this._selectObject(node,true);
  13235. }
  13236. else {
  13237. var edge = this._getEdgeAt(pointer);
  13238. if (edge != null) {
  13239. this._selectObject(edge,true);
  13240. }
  13241. }
  13242. this._redraw();
  13243. },
  13244. /**
  13245. * handle the onRelease event. These functions are here for the navigation controls module.
  13246. *
  13247. * @private
  13248. */
  13249. _handleOnRelease : function(pointer) {
  13250. },
  13251. /**
  13252. *
  13253. * retrieve the currently selected objects
  13254. * @return {Number[] | String[]} selection An array with the ids of the
  13255. * selected nodes.
  13256. */
  13257. getSelection : function() {
  13258. var nodeIds = this.getSelectedNodes();
  13259. var edgeIds = this.getSelectedEdges();
  13260. return {nodes:nodeIds, edges:edgeIds};
  13261. },
  13262. /**
  13263. *
  13264. * retrieve the currently selected nodes
  13265. * @return {String} selection An array with the ids of the
  13266. * selected nodes.
  13267. */
  13268. getSelectedNodes : function() {
  13269. var idArray = [];
  13270. for(var nodeId in this.selectionObj.nodes) {
  13271. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13272. idArray.push(nodeId);
  13273. }
  13274. }
  13275. return idArray
  13276. },
  13277. /**
  13278. *
  13279. * retrieve the currently selected edges
  13280. * @return {Array} selection An array with the ids of the
  13281. * selected nodes.
  13282. */
  13283. getSelectedEdges : function() {
  13284. var idArray = [];
  13285. for(var edgeId in this.selectionObj.edges) {
  13286. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13287. idArray.push(edgeId);
  13288. }
  13289. }
  13290. return idArray;
  13291. },
  13292. /**
  13293. * select zero or more nodes
  13294. * @param {Number[] | String[]} selection An array with the ids of the
  13295. * selected nodes.
  13296. */
  13297. setSelection : function(selection) {
  13298. var i, iMax, id;
  13299. if (!selection || (selection.length == undefined))
  13300. throw 'Selection must be an array with ids';
  13301. // first unselect any selected node
  13302. this._unselectAll(true);
  13303. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13304. id = selection[i];
  13305. var node = this.nodes[id];
  13306. if (!node) {
  13307. throw new RangeError('Node with id "' + id + '" not found');
  13308. }
  13309. this._selectObject(node,true,true);
  13310. }
  13311. this.redraw();
  13312. },
  13313. /**
  13314. * Validate the selection: remove ids of nodes which no longer exist
  13315. * @private
  13316. */
  13317. _updateSelection : function () {
  13318. for(var nodeId in this.selectionObj.nodes) {
  13319. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13320. if (!this.nodes.hasOwnProperty(nodeId)) {
  13321. delete this.selectionObj.nodes[nodeId];
  13322. }
  13323. }
  13324. }
  13325. for(var edgeId in this.selectionObj.edges) {
  13326. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13327. if (!this.edges.hasOwnProperty(edgeId)) {
  13328. delete this.selectionObj.edges[edgeId];
  13329. }
  13330. }
  13331. }
  13332. }
  13333. };
  13334. /**
  13335. * Created by Alex on 1/22/14.
  13336. */
  13337. var NavigationMixin = {
  13338. _cleanNavigation : function() {
  13339. // clean up previosu navigation items
  13340. var wrapper = document.getElementById('graph-navigation_wrapper');
  13341. if (wrapper != null) {
  13342. this.containerElement.removeChild(wrapper);
  13343. }
  13344. document.onmouseup = null;
  13345. },
  13346. /**
  13347. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13348. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13349. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13350. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13351. *
  13352. * @private
  13353. */
  13354. _loadNavigationElements : function() {
  13355. this._cleanNavigation();
  13356. this.navigationDivs = {};
  13357. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13358. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13359. this.navigationDivs['wrapper'] = document.createElement('div');
  13360. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13361. this.navigationDivs['wrapper'].style.position = "absolute";
  13362. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13363. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13364. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13365. for (var i = 0; i < navigationDivs.length; i++) {
  13366. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13367. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13368. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13369. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13370. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13371. }
  13372. document.onmouseup = this._stopMovement.bind(this);
  13373. },
  13374. /**
  13375. * this stops all movement induced by the navigation buttons
  13376. *
  13377. * @private
  13378. */
  13379. _stopMovement : function() {
  13380. this._xStopMoving();
  13381. this._yStopMoving();
  13382. this._stopZoom();
  13383. },
  13384. /**
  13385. * stops the actions performed by page up and down etc.
  13386. *
  13387. * @param event
  13388. * @private
  13389. */
  13390. _preventDefault : function(event) {
  13391. if (event !== undefined) {
  13392. if (event.preventDefault) {
  13393. event.preventDefault();
  13394. } else {
  13395. event.returnValue = false;
  13396. }
  13397. }
  13398. },
  13399. /**
  13400. * move the screen up
  13401. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13402. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13403. * To avoid this behaviour, we do the translation in the start loop.
  13404. *
  13405. * @private
  13406. */
  13407. _moveUp : function(event) {
  13408. this.yIncrement = this.constants.keyboard.speed.y;
  13409. this.start(); // if there is no node movement, the calculation wont be done
  13410. this._preventDefault(event);
  13411. if (this.navigationDivs) {
  13412. this.navigationDivs['up'].className += " active";
  13413. }
  13414. },
  13415. /**
  13416. * move the screen down
  13417. * @private
  13418. */
  13419. _moveDown : function(event) {
  13420. this.yIncrement = -this.constants.keyboard.speed.y;
  13421. this.start(); // if there is no node movement, the calculation wont be done
  13422. this._preventDefault(event);
  13423. if (this.navigationDivs) {
  13424. this.navigationDivs['down'].className += " active";
  13425. }
  13426. },
  13427. /**
  13428. * move the screen left
  13429. * @private
  13430. */
  13431. _moveLeft : function(event) {
  13432. this.xIncrement = this.constants.keyboard.speed.x;
  13433. this.start(); // if there is no node movement, the calculation wont be done
  13434. this._preventDefault(event);
  13435. if (this.navigationDivs) {
  13436. this.navigationDivs['left'].className += " active";
  13437. }
  13438. },
  13439. /**
  13440. * move the screen right
  13441. * @private
  13442. */
  13443. _moveRight : function(event) {
  13444. this.xIncrement = -this.constants.keyboard.speed.y;
  13445. this.start(); // if there is no node movement, the calculation wont be done
  13446. this._preventDefault(event);
  13447. if (this.navigationDivs) {
  13448. this.navigationDivs['right'].className += " active";
  13449. }
  13450. },
  13451. /**
  13452. * Zoom in, using the same method as the movement.
  13453. * @private
  13454. */
  13455. _zoomIn : function(event) {
  13456. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13457. this.start(); // if there is no node movement, the calculation wont be done
  13458. this._preventDefault(event);
  13459. if (this.navigationDivs) {
  13460. this.navigationDivs['zoomIn'].className += " active";
  13461. }
  13462. },
  13463. /**
  13464. * Zoom out
  13465. * @private
  13466. */
  13467. _zoomOut : function() {
  13468. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13469. this.start(); // if there is no node movement, the calculation wont be done
  13470. this._preventDefault(event);
  13471. if (this.navigationDivs) {
  13472. this.navigationDivs['zoomOut'].className += " active";
  13473. }
  13474. },
  13475. /**
  13476. * Stop zooming and unhighlight the zoom controls
  13477. * @private
  13478. */
  13479. _stopZoom : function() {
  13480. this.zoomIncrement = 0;
  13481. if (this.navigationDivs) {
  13482. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13483. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13484. }
  13485. },
  13486. /**
  13487. * Stop moving in the Y direction and unHighlight the up and down
  13488. * @private
  13489. */
  13490. _yStopMoving : function() {
  13491. this.yIncrement = 0;
  13492. if (this.navigationDivs) {
  13493. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13494. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13495. }
  13496. },
  13497. /**
  13498. * Stop moving in the X direction and unHighlight left and right.
  13499. * @private
  13500. */
  13501. _xStopMoving : function() {
  13502. this.xIncrement = 0;
  13503. if (this.navigationDivs) {
  13504. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13505. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13506. }
  13507. }
  13508. };
  13509. /**
  13510. * Created by Alex on 2/10/14.
  13511. */
  13512. var graphMixinLoaders = {
  13513. /**
  13514. * Load a mixin into the graph object
  13515. *
  13516. * @param {Object} sourceVariable | this object has to contain functions.
  13517. * @private
  13518. */
  13519. _loadMixin: function (sourceVariable) {
  13520. for (var mixinFunction in sourceVariable) {
  13521. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13522. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13523. }
  13524. }
  13525. },
  13526. /**
  13527. * removes a mixin from the graph object.
  13528. *
  13529. * @param {Object} sourceVariable | this object has to contain functions.
  13530. * @private
  13531. */
  13532. _clearMixin: function (sourceVariable) {
  13533. for (var mixinFunction in sourceVariable) {
  13534. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13535. Graph.prototype[mixinFunction] = undefined;
  13536. }
  13537. }
  13538. },
  13539. /**
  13540. * Mixin the physics system and initialize the parameters required.
  13541. *
  13542. * @private
  13543. */
  13544. _loadPhysicsSystem: function () {
  13545. this._loadMixin(physicsMixin);
  13546. this._loadSelectedForceSolver();
  13547. if (this.constants.configurePhysics == true) {
  13548. this._loadPhysicsConfiguration();
  13549. }
  13550. },
  13551. /**
  13552. * Mixin the cluster system and initialize the parameters required.
  13553. *
  13554. * @private
  13555. */
  13556. _loadClusterSystem: function () {
  13557. this.clusterSession = 0;
  13558. this.hubThreshold = 5;
  13559. this._loadMixin(ClusterMixin);
  13560. },
  13561. /**
  13562. * Mixin the sector system and initialize the parameters required
  13563. *
  13564. * @private
  13565. */
  13566. _loadSectorSystem: function () {
  13567. this.sectors = {};
  13568. this.activeSector = ["default"];
  13569. this.sectors["active"] = {};
  13570. this.sectors["active"]["default"] = {"nodes": {},
  13571. "edges": {},
  13572. "nodeIndices": [],
  13573. "formationScale": 1.0,
  13574. "drawingNode": undefined };
  13575. this.sectors["frozen"] = {};
  13576. this.sectors["support"] = {"nodes": {},
  13577. "edges": {},
  13578. "nodeIndices": [],
  13579. "formationScale": 1.0,
  13580. "drawingNode": undefined };
  13581. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13582. this._loadMixin(SectorMixin);
  13583. },
  13584. /**
  13585. * Mixin the selection system and initialize the parameters required
  13586. *
  13587. * @private
  13588. */
  13589. _loadSelectionSystem: function () {
  13590. this.selectionObj = {nodes: {}, edges: {}};
  13591. this._loadMixin(SelectionMixin);
  13592. },
  13593. /**
  13594. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13595. *
  13596. * @private
  13597. */
  13598. _loadManipulationSystem: function () {
  13599. // reset global variables -- these are used by the selection of nodes and edges.
  13600. this.blockConnectingEdgeSelection = false;
  13601. this.forceAppendSelection = false;
  13602. if (this.constants.dataManipulation.enabled == true) {
  13603. // load the manipulator HTML elements. All styling done in css.
  13604. if (this.manipulationDiv === undefined) {
  13605. this.manipulationDiv = document.createElement('div');
  13606. this.manipulationDiv.className = 'graph-manipulationDiv';
  13607. this.manipulationDiv.id = 'graph-manipulationDiv';
  13608. if (this.editMode == true) {
  13609. this.manipulationDiv.style.display = "block";
  13610. }
  13611. else {
  13612. this.manipulationDiv.style.display = "none";
  13613. }
  13614. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13615. }
  13616. if (this.editModeDiv === undefined) {
  13617. this.editModeDiv = document.createElement('div');
  13618. this.editModeDiv.className = 'graph-manipulation-editMode';
  13619. this.editModeDiv.id = 'graph-manipulation-editMode';
  13620. if (this.editMode == true) {
  13621. this.editModeDiv.style.display = "none";
  13622. }
  13623. else {
  13624. this.editModeDiv.style.display = "block";
  13625. }
  13626. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13627. }
  13628. if (this.closeDiv === undefined) {
  13629. this.closeDiv = document.createElement('div');
  13630. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13631. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13632. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13633. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13634. }
  13635. // load the manipulation functions
  13636. this._loadMixin(manipulationMixin);
  13637. // create the manipulator toolbar
  13638. this._createManipulatorBar();
  13639. }
  13640. else {
  13641. if (this.manipulationDiv !== undefined) {
  13642. // removes all the bindings and overloads
  13643. this._createManipulatorBar();
  13644. // remove the manipulation divs
  13645. this.containerElement.removeChild(this.manipulationDiv);
  13646. this.containerElement.removeChild(this.editModeDiv);
  13647. this.containerElement.removeChild(this.closeDiv);
  13648. this.manipulationDiv = undefined;
  13649. this.editModeDiv = undefined;
  13650. this.closeDiv = undefined;
  13651. // remove the mixin functions
  13652. this._clearMixin(manipulationMixin);
  13653. }
  13654. }
  13655. },
  13656. /**
  13657. * Mixin the navigation (User Interface) system and initialize the parameters required
  13658. *
  13659. * @private
  13660. */
  13661. _loadNavigationControls: function () {
  13662. this._loadMixin(NavigationMixin);
  13663. // the clean function removes the button divs, this is done to remove the bindings.
  13664. this._cleanNavigation();
  13665. if (this.constants.navigation.enabled == true) {
  13666. this._loadNavigationElements();
  13667. }
  13668. },
  13669. /**
  13670. * Mixin the hierarchical layout system.
  13671. *
  13672. * @private
  13673. */
  13674. _loadHierarchySystem: function () {
  13675. this._loadMixin(HierarchicalLayoutMixin);
  13676. }
  13677. };
  13678. /**
  13679. * @constructor Graph
  13680. * Create a graph visualization, displaying nodes and edges.
  13681. *
  13682. * @param {Element} container The DOM element in which the Graph will
  13683. * be created. Normally a div element.
  13684. * @param {Object} data An object containing parameters
  13685. * {Array} nodes
  13686. * {Array} edges
  13687. * @param {Object} options Options
  13688. */
  13689. function Graph (container, data, options) {
  13690. this._initializeMixinLoaders();
  13691. // create variables and set default values
  13692. this.containerElement = container;
  13693. this.width = '100%';
  13694. this.height = '100%';
  13695. // render and calculation settings
  13696. this.renderRefreshRate = 60; // hz (fps)
  13697. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13698. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13699. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13700. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13701. this.stabilize = true; // stabilize before displaying the graph
  13702. this.selectable = true;
  13703. this.initializing = true;
  13704. // these functions are triggered when the dataset is edited
  13705. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13706. // set constant values
  13707. this.constants = {
  13708. nodes: {
  13709. radiusMin: 5,
  13710. radiusMax: 20,
  13711. radius: 5,
  13712. shape: 'ellipse',
  13713. image: undefined,
  13714. widthMin: 16, // px
  13715. widthMax: 64, // px
  13716. fixed: false,
  13717. fontColor: 'black',
  13718. fontSize: 14, // px
  13719. fontFace: 'verdana',
  13720. level: -1,
  13721. color: {
  13722. border: '#2B7CE9',
  13723. background: '#97C2FC',
  13724. highlight: {
  13725. border: '#2B7CE9',
  13726. background: '#D2E5FF'
  13727. }
  13728. },
  13729. borderColor: '#2B7CE9',
  13730. backgroundColor: '#97C2FC',
  13731. highlightColor: '#D2E5FF',
  13732. group: undefined
  13733. },
  13734. edges: {
  13735. widthMin: 1,
  13736. widthMax: 15,
  13737. width: 1,
  13738. style: 'line',
  13739. color: {
  13740. color:'#848484',
  13741. highlight:'#848484'
  13742. },
  13743. fontColor: '#343434',
  13744. fontSize: 14, // px
  13745. fontFace: 'arial',
  13746. fontFill: 'white',
  13747. arrowScaleFactor: 1,
  13748. dash: {
  13749. length: 10,
  13750. gap: 5,
  13751. altLength: undefined
  13752. }
  13753. },
  13754. configurePhysics:false,
  13755. physics: {
  13756. barnesHut: {
  13757. enabled: true,
  13758. theta: 1 / 0.6, // inverted to save time during calculation
  13759. gravitationalConstant: -2000,
  13760. centralGravity: 0.3,
  13761. springLength: 95,
  13762. springConstant: 0.04,
  13763. damping: 0.09
  13764. },
  13765. repulsion: {
  13766. centralGravity: 0.1,
  13767. springLength: 200,
  13768. springConstant: 0.05,
  13769. nodeDistance: 100,
  13770. damping: 0.09
  13771. },
  13772. hierarchicalRepulsion: {
  13773. enabled: false,
  13774. centralGravity: 0.0,
  13775. springLength: 100,
  13776. springConstant: 0.01,
  13777. nodeDistance: 60,
  13778. damping: 0.09
  13779. },
  13780. damping: null,
  13781. centralGravity: null,
  13782. springLength: null,
  13783. springConstant: null
  13784. },
  13785. clustering: { // Per Node in Cluster = PNiC
  13786. enabled: false, // (Boolean) | global on/off switch for clustering.
  13787. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13788. 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
  13789. 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
  13790. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13791. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13792. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13793. 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.
  13794. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13795. maxFontSize: 1000,
  13796. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13797. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13798. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13799. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13800. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13801. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13802. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13803. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13804. clusterLevelDifference: 2
  13805. },
  13806. navigation: {
  13807. enabled: false
  13808. },
  13809. keyboard: {
  13810. enabled: false,
  13811. speed: {x: 10, y: 10, zoom: 0.02}
  13812. },
  13813. dataManipulation: {
  13814. enabled: false,
  13815. initiallyVisible: false
  13816. },
  13817. hierarchicalLayout: {
  13818. enabled:false,
  13819. levelSeparation: 150,
  13820. nodeSpacing: 100,
  13821. direction: "UD" // UD, DU, LR, RL
  13822. },
  13823. freezeForStabilization: false,
  13824. smoothCurves: true,
  13825. maxVelocity: 10,
  13826. minVelocity: 0.1, // px/s
  13827. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13828. labels:{
  13829. add:"Add Node",
  13830. edit:"Edit",
  13831. link:"Add Link",
  13832. del:"Delete selected",
  13833. editNode:"Edit Node",
  13834. back:"Back",
  13835. addDescription:"Click in an empty space to place a new node.",
  13836. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13837. addError:"The function for add does not support two arguments (data,callback).",
  13838. linkError:"The function for connect does not support two arguments (data,callback).",
  13839. editError:"The function for edit does not support two arguments (data, callback).",
  13840. editBoundError:"No edit function has been bound to this button.",
  13841. deleteError:"The function for delete does not support two arguments (data, callback).",
  13842. deleteClusterError:"Clusters cannot be deleted."
  13843. },
  13844. tooltip: {
  13845. delay: 300,
  13846. fontColor: 'black',
  13847. fontSize: 14, // px
  13848. fontFace: 'verdana',
  13849. color: {
  13850. border: '#666',
  13851. background: '#FFFFC6'
  13852. }
  13853. },
  13854. moveable: true,
  13855. zoomable: true
  13856. };
  13857. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13858. // Node variables
  13859. var graph = this;
  13860. this.groups = new Groups(); // object with groups
  13861. this.images = new Images(); // object with images
  13862. this.images.setOnloadCallback(function () {
  13863. graph._redraw();
  13864. });
  13865. // keyboard navigation variables
  13866. this.xIncrement = 0;
  13867. this.yIncrement = 0;
  13868. this.zoomIncrement = 0;
  13869. // loading all the mixins:
  13870. // load the force calculation functions, grouped under the physics system.
  13871. this._loadPhysicsSystem();
  13872. // create a frame and canvas
  13873. this._create();
  13874. // load the sector system. (mandatory, fully integrated with Graph)
  13875. this._loadSectorSystem();
  13876. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13877. this._loadClusterSystem();
  13878. // load the selection system. (mandatory, required by Graph)
  13879. this._loadSelectionSystem();
  13880. // load the selection system. (mandatory, required by Graph)
  13881. this._loadHierarchySystem();
  13882. // apply options
  13883. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  13884. this._setScale(1);
  13885. this.setOptions(options);
  13886. // other vars
  13887. this.freezeSimulation = false;// freeze the simulation
  13888. this.cachedFunctions = {};
  13889. // containers for nodes and edges
  13890. this.calculationNodes = {};
  13891. this.calculationNodeIndices = [];
  13892. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13893. this.nodes = {}; // object with Node objects
  13894. this.edges = {}; // object with Edge objects
  13895. // position and scale variables and objects
  13896. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13897. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13898. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13899. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13900. this.scale = 1; // defining the global scale variable in the constructor
  13901. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13902. // datasets or dataviews
  13903. this.nodesData = null; // A DataSet or DataView
  13904. this.edgesData = null; // A DataSet or DataView
  13905. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13906. this.nodesListeners = {
  13907. 'add': function (event, params) {
  13908. graph._addNodes(params.items);
  13909. graph.start();
  13910. },
  13911. 'update': function (event, params) {
  13912. graph._updateNodes(params.items);
  13913. graph.start();
  13914. },
  13915. 'remove': function (event, params) {
  13916. graph._removeNodes(params.items);
  13917. graph.start();
  13918. }
  13919. };
  13920. this.edgesListeners = {
  13921. 'add': function (event, params) {
  13922. graph._addEdges(params.items);
  13923. graph.start();
  13924. },
  13925. 'update': function (event, params) {
  13926. graph._updateEdges(params.items);
  13927. graph.start();
  13928. },
  13929. 'remove': function (event, params) {
  13930. graph._removeEdges(params.items);
  13931. graph.start();
  13932. }
  13933. };
  13934. // properties for the animation
  13935. this.moving = true;
  13936. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13937. // load data (the disable start variable will be the same as the enabled clustering)
  13938. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13939. // hierarchical layout
  13940. this.initializing = false;
  13941. if (this.constants.hierarchicalLayout.enabled == true) {
  13942. this._setupHierarchicalLayout();
  13943. }
  13944. else {
  13945. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13946. if (this.stabilize == false) {
  13947. this.zoomExtent(true,this.constants.clustering.enabled);
  13948. }
  13949. }
  13950. // if clustering is disabled, the simulation will have started in the setData function
  13951. if (this.constants.clustering.enabled) {
  13952. this.startWithClustering();
  13953. }
  13954. }
  13955. // Extend Graph with an Emitter mixin
  13956. Emitter(Graph.prototype);
  13957. /**
  13958. * Get the script path where the vis.js library is located
  13959. *
  13960. * @returns {string | null} path Path or null when not found. Path does not
  13961. * end with a slash.
  13962. * @private
  13963. */
  13964. Graph.prototype._getScriptPath = function() {
  13965. var scripts = document.getElementsByTagName( 'script' );
  13966. // find script named vis.js or vis.min.js
  13967. for (var i = 0; i < scripts.length; i++) {
  13968. var src = scripts[i].src;
  13969. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13970. if (match) {
  13971. // return path without the script name
  13972. return src.substring(0, src.length - match[0].length);
  13973. }
  13974. }
  13975. return null;
  13976. };
  13977. /**
  13978. * Find the center position of the graph
  13979. * @private
  13980. */
  13981. Graph.prototype._getRange = function() {
  13982. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13983. for (var nodeId in this.nodes) {
  13984. if (this.nodes.hasOwnProperty(nodeId)) {
  13985. node = this.nodes[nodeId];
  13986. if (minX > (node.x)) {minX = node.x;}
  13987. if (maxX < (node.x)) {maxX = node.x;}
  13988. if (minY > (node.y)) {minY = node.y;}
  13989. if (maxY < (node.y)) {maxY = node.y;}
  13990. }
  13991. }
  13992. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13993. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13994. }
  13995. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13996. };
  13997. /**
  13998. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13999. * @returns {{x: number, y: number}}
  14000. * @private
  14001. */
  14002. Graph.prototype._findCenter = function(range) {
  14003. return {x: (0.5 * (range.maxX + range.minX)),
  14004. y: (0.5 * (range.maxY + range.minY))};
  14005. };
  14006. /**
  14007. * center the graph
  14008. *
  14009. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14010. */
  14011. Graph.prototype._centerGraph = function(range) {
  14012. var center = this._findCenter(range);
  14013. center.x *= this.scale;
  14014. center.y *= this.scale;
  14015. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14016. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14017. this._setTranslation(-center.x,-center.y); // set at 0,0
  14018. };
  14019. /**
  14020. * This function zooms out to fit all data on screen based on amount of nodes
  14021. *
  14022. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14023. * @param {Boolean} [disableStart] | If true, start is not called.
  14024. */
  14025. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14026. if (initialZoom === undefined) {
  14027. initialZoom = false;
  14028. }
  14029. if (disableStart === undefined) {
  14030. disableStart = false;
  14031. }
  14032. var range = this._getRange();
  14033. var zoomLevel;
  14034. if (initialZoom == true) {
  14035. var numberOfNodes = this.nodeIndices.length;
  14036. if (this.constants.smoothCurves == true) {
  14037. if (this.constants.clustering.enabled == true &&
  14038. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14039. 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.
  14040. }
  14041. else {
  14042. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14043. }
  14044. }
  14045. else {
  14046. if (this.constants.clustering.enabled == true &&
  14047. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14048. 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.
  14049. }
  14050. else {
  14051. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14052. }
  14053. }
  14054. // correct for larger canvasses.
  14055. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14056. zoomLevel *= factor;
  14057. }
  14058. else {
  14059. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14060. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14061. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14062. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14063. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14064. }
  14065. if (zoomLevel > 1.0) {
  14066. zoomLevel = 1.0;
  14067. }
  14068. this._setScale(zoomLevel);
  14069. this._centerGraph(range);
  14070. if (disableStart == false) {
  14071. this.moving = true;
  14072. this.start();
  14073. }
  14074. };
  14075. /**
  14076. * Update the this.nodeIndices with the most recent node index list
  14077. * @private
  14078. */
  14079. Graph.prototype._updateNodeIndexList = function() {
  14080. this._clearNodeIndexList();
  14081. for (var idx in this.nodes) {
  14082. if (this.nodes.hasOwnProperty(idx)) {
  14083. this.nodeIndices.push(idx);
  14084. }
  14085. }
  14086. };
  14087. /**
  14088. * Set nodes and edges, and optionally options as well.
  14089. *
  14090. * @param {Object} data Object containing parameters:
  14091. * {Array | DataSet | DataView} [nodes] Array with nodes
  14092. * {Array | DataSet | DataView} [edges] Array with edges
  14093. * {String} [dot] String containing data in DOT format
  14094. * {Options} [options] Object with options
  14095. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14096. */
  14097. Graph.prototype.setData = function(data, disableStart) {
  14098. if (disableStart === undefined) {
  14099. disableStart = false;
  14100. }
  14101. if (data && data.dot && (data.nodes || data.edges)) {
  14102. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14103. ' parameter pair "nodes" and "edges", but not both.');
  14104. }
  14105. // set options
  14106. this.setOptions(data && data.options);
  14107. // set all data
  14108. if (data && data.dot) {
  14109. // parse DOT file
  14110. if(data && data.dot) {
  14111. var dotData = vis.util.DOTToGraph(data.dot);
  14112. this.setData(dotData);
  14113. return;
  14114. }
  14115. }
  14116. else {
  14117. this._setNodes(data && data.nodes);
  14118. this._setEdges(data && data.edges);
  14119. }
  14120. this._putDataInSector();
  14121. if (!disableStart) {
  14122. // find a stable position or start animating to a stable position
  14123. if (this.stabilize) {
  14124. var me = this;
  14125. setTimeout(function() {me._stabilize(); me.start();},0)
  14126. }
  14127. else {
  14128. this.start();
  14129. }
  14130. }
  14131. };
  14132. /**
  14133. * Set options
  14134. * @param {Object} options
  14135. * @param {Boolean} [initializeView] | set zoom and translation to default.
  14136. */
  14137. Graph.prototype.setOptions = function (options) {
  14138. if (options) {
  14139. var prop;
  14140. // retrieve parameter values
  14141. if (options.width !== undefined) {this.width = options.width;}
  14142. if (options.height !== undefined) {this.height = options.height;}
  14143. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14144. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14145. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14146. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14147. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14148. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14149. if (options.moveable !== undefined) {this.constants.moveable = options.moveable;}
  14150. if (options.zoomable !== undefined) {this.constants.zoomable = options.zoomable;}
  14151. if (options.labels !== undefined) {
  14152. for (prop in options.labels) {
  14153. if (options.labels.hasOwnProperty(prop)) {
  14154. this.constants.labels[prop] = options.labels[prop];
  14155. }
  14156. }
  14157. }
  14158. if (options.onAdd) {
  14159. this.triggerFunctions.add = options.onAdd;
  14160. }
  14161. if (options.onEdit) {
  14162. this.triggerFunctions.edit = options.onEdit;
  14163. }
  14164. if (options.onConnect) {
  14165. this.triggerFunctions.connect = options.onConnect;
  14166. }
  14167. if (options.onDelete) {
  14168. this.triggerFunctions.del = options.onDelete;
  14169. }
  14170. if (options.physics) {
  14171. if (options.physics.barnesHut) {
  14172. this.constants.physics.barnesHut.enabled = true;
  14173. for (prop in options.physics.barnesHut) {
  14174. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14175. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14176. }
  14177. }
  14178. }
  14179. if (options.physics.repulsion) {
  14180. this.constants.physics.barnesHut.enabled = false;
  14181. for (prop in options.physics.repulsion) {
  14182. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14183. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14184. }
  14185. }
  14186. }
  14187. if (options.physics.hierarchicalRepulsion) {
  14188. this.constants.hierarchicalLayout.enabled = true;
  14189. this.constants.physics.hierarchicalRepulsion.enabled = true;
  14190. this.constants.physics.barnesHut.enabled = false;
  14191. for (prop in options.physics.hierarchicalRepulsion) {
  14192. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  14193. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  14194. }
  14195. }
  14196. }
  14197. }
  14198. if (options.hierarchicalLayout) {
  14199. this.constants.hierarchicalLayout.enabled = true;
  14200. for (prop in options.hierarchicalLayout) {
  14201. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14202. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14203. }
  14204. }
  14205. }
  14206. else if (options.hierarchicalLayout !== undefined) {
  14207. this.constants.hierarchicalLayout.enabled = false;
  14208. }
  14209. if (options.clustering) {
  14210. this.constants.clustering.enabled = true;
  14211. for (prop in options.clustering) {
  14212. if (options.clustering.hasOwnProperty(prop)) {
  14213. this.constants.clustering[prop] = options.clustering[prop];
  14214. }
  14215. }
  14216. }
  14217. else if (options.clustering !== undefined) {
  14218. this.constants.clustering.enabled = false;
  14219. }
  14220. if (options.navigation) {
  14221. this.constants.navigation.enabled = true;
  14222. for (prop in options.navigation) {
  14223. if (options.navigation.hasOwnProperty(prop)) {
  14224. this.constants.navigation[prop] = options.navigation[prop];
  14225. }
  14226. }
  14227. }
  14228. else if (options.navigation !== undefined) {
  14229. this.constants.navigation.enabled = false;
  14230. }
  14231. if (options.keyboard) {
  14232. this.constants.keyboard.enabled = true;
  14233. for (prop in options.keyboard) {
  14234. if (options.keyboard.hasOwnProperty(prop)) {
  14235. this.constants.keyboard[prop] = options.keyboard[prop];
  14236. }
  14237. }
  14238. }
  14239. else if (options.keyboard !== undefined) {
  14240. this.constants.keyboard.enabled = false;
  14241. }
  14242. if (options.dataManipulation) {
  14243. this.constants.dataManipulation.enabled = true;
  14244. for (prop in options.dataManipulation) {
  14245. if (options.dataManipulation.hasOwnProperty(prop)) {
  14246. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14247. }
  14248. }
  14249. }
  14250. else if (options.dataManipulation !== undefined) {
  14251. this.constants.dataManipulation.enabled = false;
  14252. }
  14253. // TODO: work out these options and document them
  14254. if (options.edges) {
  14255. for (prop in options.edges) {
  14256. if (options.edges.hasOwnProperty(prop)) {
  14257. if (typeof options.edges[prop] != "object") {
  14258. this.constants.edges[prop] = options.edges[prop];
  14259. }
  14260. }
  14261. }
  14262. if (options.edges.color !== undefined) {
  14263. if (util.isString(options.edges.color)) {
  14264. this.constants.edges.color = {};
  14265. this.constants.edges.color.color = options.edges.color;
  14266. this.constants.edges.color.highlight = options.edges.color;
  14267. }
  14268. else {
  14269. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14270. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14271. }
  14272. }
  14273. if (!options.edges.fontColor) {
  14274. if (options.edges.color !== undefined) {
  14275. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14276. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14277. }
  14278. }
  14279. // Added to support dashed lines
  14280. // David Jordan
  14281. // 2012-08-08
  14282. if (options.edges.dash) {
  14283. if (options.edges.dash.length !== undefined) {
  14284. this.constants.edges.dash.length = options.edges.dash.length;
  14285. }
  14286. if (options.edges.dash.gap !== undefined) {
  14287. this.constants.edges.dash.gap = options.edges.dash.gap;
  14288. }
  14289. if (options.edges.dash.altLength !== undefined) {
  14290. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14291. }
  14292. }
  14293. }
  14294. if (options.nodes) {
  14295. for (prop in options.nodes) {
  14296. if (options.nodes.hasOwnProperty(prop)) {
  14297. this.constants.nodes[prop] = options.nodes[prop];
  14298. }
  14299. }
  14300. if (options.nodes.color) {
  14301. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14302. }
  14303. /*
  14304. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14305. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14306. */
  14307. }
  14308. if (options.groups) {
  14309. for (var groupname in options.groups) {
  14310. if (options.groups.hasOwnProperty(groupname)) {
  14311. var group = options.groups[groupname];
  14312. this.groups.add(groupname, group);
  14313. }
  14314. }
  14315. }
  14316. if (options.tooltip) {
  14317. for (prop in options.tooltip) {
  14318. if (options.tooltip.hasOwnProperty(prop)) {
  14319. this.constants.tooltip[prop] = options.tooltip[prop];
  14320. }
  14321. }
  14322. if (options.tooltip.color) {
  14323. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14324. }
  14325. }
  14326. }
  14327. // (Re)loading the mixins that can be enabled or disabled in the options.
  14328. // load the force calculation functions, grouped under the physics system.
  14329. this._loadPhysicsSystem();
  14330. // load the navigation system.
  14331. this._loadNavigationControls();
  14332. // load the data manipulation system
  14333. this._loadManipulationSystem();
  14334. // configure the smooth curves
  14335. this._configureSmoothCurves();
  14336. // bind keys. If disabled, this will not do anything;
  14337. this._createKeyBinds();
  14338. this.setSize(this.width, this.height);
  14339. this.moving = true;
  14340. this.start();
  14341. };
  14342. /**
  14343. * Create the main frame for the Graph.
  14344. * This function is executed once when a Graph object is created. The frame
  14345. * contains a canvas, and this canvas contains all objects like the axis and
  14346. * nodes.
  14347. * @private
  14348. */
  14349. Graph.prototype._create = function () {
  14350. // remove all elements from the container element.
  14351. while (this.containerElement.hasChildNodes()) {
  14352. this.containerElement.removeChild(this.containerElement.firstChild);
  14353. }
  14354. this.frame = document.createElement('div');
  14355. this.frame.className = 'graph-frame';
  14356. this.frame.style.position = 'relative';
  14357. this.frame.style.overflow = 'hidden';
  14358. // create the graph canvas (HTML canvas element)
  14359. this.frame.canvas = document.createElement( 'canvas' );
  14360. this.frame.canvas.style.position = 'relative';
  14361. this.frame.appendChild(this.frame.canvas);
  14362. if (!this.frame.canvas.getContext) {
  14363. var noCanvas = document.createElement( 'DIV' );
  14364. noCanvas.style.color = 'red';
  14365. noCanvas.style.fontWeight = 'bold' ;
  14366. noCanvas.style.padding = '10px';
  14367. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14368. this.frame.canvas.appendChild(noCanvas);
  14369. }
  14370. var me = this;
  14371. this.drag = {};
  14372. this.pinch = {};
  14373. this.hammer = Hammer(this.frame.canvas, {
  14374. prevent_default: true
  14375. });
  14376. this.hammer.on('tap', me._onTap.bind(me) );
  14377. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14378. this.hammer.on('hold', me._onHold.bind(me) );
  14379. this.hammer.on('pinch', me._onPinch.bind(me) );
  14380. this.hammer.on('touch', me._onTouch.bind(me) );
  14381. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14382. this.hammer.on('drag', me._onDrag.bind(me) );
  14383. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14384. this.hammer.on('release', me._onRelease.bind(me) );
  14385. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14386. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14387. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14388. // add the frame to the container element
  14389. this.containerElement.appendChild(this.frame);
  14390. };
  14391. /**
  14392. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14393. * @private
  14394. */
  14395. Graph.prototype._createKeyBinds = function() {
  14396. var me = this;
  14397. this.mousetrap = mousetrap;
  14398. this.mousetrap.reset();
  14399. if (this.constants.keyboard.enabled == true) {
  14400. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14401. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14402. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14403. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14404. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14405. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14406. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14407. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14408. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14409. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14410. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14411. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14412. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14413. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14414. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14415. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14416. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14417. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14418. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14419. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14420. }
  14421. if (this.constants.dataManipulation.enabled == true) {
  14422. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14423. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14424. }
  14425. };
  14426. /**
  14427. * Get the pointer location from a touch location
  14428. * @param {{pageX: Number, pageY: Number}} touch
  14429. * @return {{x: Number, y: Number}} pointer
  14430. * @private
  14431. */
  14432. Graph.prototype._getPointer = function (touch) {
  14433. return {
  14434. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14435. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14436. };
  14437. };
  14438. /**
  14439. * On start of a touch gesture, store the pointer
  14440. * @param event
  14441. * @private
  14442. */
  14443. Graph.prototype._onTouch = function (event) {
  14444. this.drag.pointer = this._getPointer(event.gesture.center);
  14445. this.drag.pinched = false;
  14446. this.pinch.scale = this._getScale();
  14447. this._handleTouch(this.drag.pointer);
  14448. };
  14449. /**
  14450. * handle drag start event
  14451. * @private
  14452. */
  14453. Graph.prototype._onDragStart = function () {
  14454. this._handleDragStart();
  14455. };
  14456. /**
  14457. * This function is called by _onDragStart.
  14458. * It is separated out because we can then overload it for the datamanipulation system.
  14459. *
  14460. * @private
  14461. */
  14462. Graph.prototype._handleDragStart = function() {
  14463. var drag = this.drag;
  14464. var node = this._getNodeAt(drag.pointer);
  14465. // note: drag.pointer is set in _onTouch to get the initial touch location
  14466. drag.dragging = true;
  14467. drag.selection = [];
  14468. drag.translation = this._getTranslation();
  14469. drag.nodeId = null;
  14470. if (node != null) {
  14471. drag.nodeId = node.id;
  14472. // select the clicked node if not yet selected
  14473. if (!node.isSelected()) {
  14474. this._selectObject(node,false);
  14475. }
  14476. // create an array with the selected nodes and their original location and status
  14477. for (var objectId in this.selectionObj.nodes) {
  14478. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14479. var object = this.selectionObj.nodes[objectId];
  14480. var s = {
  14481. id: object.id,
  14482. node: object,
  14483. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14484. x: object.x,
  14485. y: object.y,
  14486. xFixed: object.xFixed,
  14487. yFixed: object.yFixed
  14488. };
  14489. object.xFixed = true;
  14490. object.yFixed = true;
  14491. drag.selection.push(s);
  14492. }
  14493. }
  14494. }
  14495. };
  14496. /**
  14497. * handle drag event
  14498. * @private
  14499. */
  14500. Graph.prototype._onDrag = function (event) {
  14501. this._handleOnDrag(event)
  14502. };
  14503. /**
  14504. * This function is called by _onDrag.
  14505. * It is separated out because we can then overload it for the datamanipulation system.
  14506. *
  14507. * @private
  14508. */
  14509. Graph.prototype._handleOnDrag = function(event) {
  14510. if (this.drag.pinched) {
  14511. return;
  14512. }
  14513. var pointer = this._getPointer(event.gesture.center);
  14514. var me = this,
  14515. drag = this.drag,
  14516. selection = drag.selection;
  14517. if (selection && selection.length) {
  14518. // calculate delta's and new location
  14519. var deltaX = pointer.x - drag.pointer.x,
  14520. deltaY = pointer.y - drag.pointer.y;
  14521. // update position of all selected nodes
  14522. selection.forEach(function (s) {
  14523. var node = s.node;
  14524. if (!s.xFixed) {
  14525. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  14526. }
  14527. if (!s.yFixed) {
  14528. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  14529. }
  14530. });
  14531. // start _animationStep if not yet running
  14532. if (!this.moving) {
  14533. this.moving = true;
  14534. this.start();
  14535. }
  14536. }
  14537. else {
  14538. if (this.constants.moveable == true) {
  14539. // move the graph
  14540. var diffX = pointer.x - this.drag.pointer.x;
  14541. var diffY = pointer.y - this.drag.pointer.y;
  14542. this._setTranslation(
  14543. this.drag.translation.x + diffX,
  14544. this.drag.translation.y + diffY);
  14545. this._redraw();
  14546. this.moving = true;
  14547. this.start();
  14548. }
  14549. }
  14550. };
  14551. /**
  14552. * handle drag start event
  14553. * @private
  14554. */
  14555. Graph.prototype._onDragEnd = function () {
  14556. this.drag.dragging = false;
  14557. var selection = this.drag.selection;
  14558. if (selection) {
  14559. selection.forEach(function (s) {
  14560. // restore original xFixed and yFixed
  14561. s.node.xFixed = s.xFixed;
  14562. s.node.yFixed = s.yFixed;
  14563. });
  14564. }
  14565. };
  14566. /**
  14567. * handle tap/click event: select/unselect a node
  14568. * @private
  14569. */
  14570. Graph.prototype._onTap = function (event) {
  14571. var pointer = this._getPointer(event.gesture.center);
  14572. this.pointerPosition = pointer;
  14573. this._handleTap(pointer);
  14574. };
  14575. /**
  14576. * handle doubletap event
  14577. * @private
  14578. */
  14579. Graph.prototype._onDoubleTap = function (event) {
  14580. var pointer = this._getPointer(event.gesture.center);
  14581. this._handleDoubleTap(pointer);
  14582. };
  14583. /**
  14584. * handle long tap event: multi select nodes
  14585. * @private
  14586. */
  14587. Graph.prototype._onHold = function (event) {
  14588. var pointer = this._getPointer(event.gesture.center);
  14589. this.pointerPosition = pointer;
  14590. this._handleOnHold(pointer);
  14591. };
  14592. /**
  14593. * handle the release of the screen
  14594. *
  14595. * @private
  14596. */
  14597. Graph.prototype._onRelease = function (event) {
  14598. var pointer = this._getPointer(event.gesture.center);
  14599. this._handleOnRelease(pointer);
  14600. };
  14601. /**
  14602. * Handle pinch event
  14603. * @param event
  14604. * @private
  14605. */
  14606. Graph.prototype._onPinch = function (event) {
  14607. var pointer = this._getPointer(event.gesture.center);
  14608. this.drag.pinched = true;
  14609. if (!('scale' in this.pinch)) {
  14610. this.pinch.scale = 1;
  14611. }
  14612. // TODO: enabled moving while pinching?
  14613. var scale = this.pinch.scale * event.gesture.scale;
  14614. this._zoom(scale, pointer)
  14615. };
  14616. /**
  14617. * Zoom the graph in or out
  14618. * @param {Number} scale a number around 1, and between 0.01 and 10
  14619. * @param {{x: Number, y: Number}} pointer Position on screen
  14620. * @return {Number} appliedScale scale is limited within the boundaries
  14621. * @private
  14622. */
  14623. Graph.prototype._zoom = function(scale, pointer) {
  14624. if (this.constants.zoomable == true) {
  14625. var scaleOld = this._getScale();
  14626. if (scale < 0.00001) {
  14627. scale = 0.00001;
  14628. }
  14629. if (scale > 10) {
  14630. scale = 10;
  14631. }
  14632. // + this.frame.canvas.clientHeight / 2
  14633. var translation = this._getTranslation();
  14634. var scaleFrac = scale / scaleOld;
  14635. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14636. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14637. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  14638. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  14639. this._setScale(scale);
  14640. this._setTranslation(tx, ty);
  14641. this.updateClustersDefault();
  14642. this._redraw();
  14643. if (scaleOld < scale) {
  14644. this.emit("zoom", {direction:"+"});
  14645. }
  14646. else {
  14647. this.emit("zoom", {direction:"-"});
  14648. }
  14649. return scale;
  14650. }
  14651. };
  14652. /**
  14653. * Event handler for mouse wheel event, used to zoom the timeline
  14654. * See http://adomas.org/javascript-mouse-wheel/
  14655. * https://github.com/EightMedia/hammer.js/issues/256
  14656. * @param {MouseEvent} event
  14657. * @private
  14658. */
  14659. Graph.prototype._onMouseWheel = function(event) {
  14660. // retrieve delta
  14661. var delta = 0;
  14662. if (event.wheelDelta) { /* IE/Opera. */
  14663. delta = event.wheelDelta/120;
  14664. } else if (event.detail) { /* Mozilla case. */
  14665. // In Mozilla, sign of delta is different than in IE.
  14666. // Also, delta is multiple of 3.
  14667. delta = -event.detail/3;
  14668. }
  14669. // If delta is nonzero, handle it.
  14670. // Basically, delta is now positive if wheel was scrolled up,
  14671. // and negative, if wheel was scrolled down.
  14672. if (delta) {
  14673. // calculate the new scale
  14674. var scale = this._getScale();
  14675. var zoom = delta / 10;
  14676. if (delta < 0) {
  14677. zoom = zoom / (1 - zoom);
  14678. }
  14679. scale *= (1 + zoom);
  14680. // calculate the pointer location
  14681. var gesture = util.fakeGesture(this, event);
  14682. var pointer = this._getPointer(gesture.center);
  14683. // apply the new scale
  14684. this._zoom(scale, pointer);
  14685. }
  14686. // Prevent default actions caused by mouse wheel.
  14687. event.preventDefault();
  14688. };
  14689. /**
  14690. * Mouse move handler for checking whether the title moves over a node with a title.
  14691. * @param {Event} event
  14692. * @private
  14693. */
  14694. Graph.prototype._onMouseMoveTitle = function (event) {
  14695. var gesture = util.fakeGesture(this, event);
  14696. var pointer = this._getPointer(gesture.center);
  14697. // check if the previously selected node is still selected
  14698. if (this.popupNode) {
  14699. this._checkHidePopup(pointer);
  14700. }
  14701. // start a timeout that will check if the mouse is positioned above
  14702. // an element
  14703. var me = this;
  14704. var checkShow = function() {
  14705. me._checkShowPopup(pointer);
  14706. };
  14707. if (this.popupTimer) {
  14708. clearInterval(this.popupTimer); // stop any running calculationTimer
  14709. }
  14710. if (!this.drag.dragging) {
  14711. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14712. }
  14713. };
  14714. /**
  14715. * Check if there is an element on the given position in the graph
  14716. * (a node or edge). If so, and if this element has a title,
  14717. * show a popup window with its title.
  14718. *
  14719. * @param {{x:Number, y:Number}} pointer
  14720. * @private
  14721. */
  14722. Graph.prototype._checkShowPopup = function (pointer) {
  14723. var obj = {
  14724. left: this._XconvertDOMtoCanvas(pointer.x),
  14725. top: this._YconvertDOMtoCanvas(pointer.y),
  14726. right: this._XconvertDOMtoCanvas(pointer.x),
  14727. bottom: this._YconvertDOMtoCanvas(pointer.y)
  14728. };
  14729. var id;
  14730. var lastPopupNode = this.popupNode;
  14731. if (this.popupNode == undefined) {
  14732. // search the nodes for overlap, select the top one in case of multiple nodes
  14733. var nodes = this.nodes;
  14734. for (id in nodes) {
  14735. if (nodes.hasOwnProperty(id)) {
  14736. var node = nodes[id];
  14737. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14738. this.popupNode = node;
  14739. break;
  14740. }
  14741. }
  14742. }
  14743. }
  14744. if (this.popupNode === undefined) {
  14745. // search the edges for overlap
  14746. var edges = this.edges;
  14747. for (id in edges) {
  14748. if (edges.hasOwnProperty(id)) {
  14749. var edge = edges[id];
  14750. if (edge.connected && (edge.getTitle() !== undefined) &&
  14751. edge.isOverlappingWith(obj)) {
  14752. this.popupNode = edge;
  14753. break;
  14754. }
  14755. }
  14756. }
  14757. }
  14758. if (this.popupNode) {
  14759. // show popup message window
  14760. if (this.popupNode != lastPopupNode) {
  14761. var me = this;
  14762. if (!me.popup) {
  14763. me.popup = new Popup(me.frame, me.constants.tooltip);
  14764. }
  14765. // adjust a small offset such that the mouse cursor is located in the
  14766. // bottom left location of the popup, and you can easily move over the
  14767. // popup area
  14768. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14769. me.popup.setText(me.popupNode.getTitle());
  14770. me.popup.show();
  14771. }
  14772. }
  14773. else {
  14774. if (this.popup) {
  14775. this.popup.hide();
  14776. }
  14777. }
  14778. };
  14779. /**
  14780. * Check if the popup must be hided, which is the case when the mouse is no
  14781. * longer hovering on the object
  14782. * @param {{x:Number, y:Number}} pointer
  14783. * @private
  14784. */
  14785. Graph.prototype._checkHidePopup = function (pointer) {
  14786. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14787. this.popupNode = undefined;
  14788. if (this.popup) {
  14789. this.popup.hide();
  14790. }
  14791. }
  14792. };
  14793. /**
  14794. * Set a new size for the graph
  14795. * @param {string} width Width in pixels or percentage (for example '800px'
  14796. * or '50%')
  14797. * @param {string} height Height in pixels or percentage (for example '400px'
  14798. * or '30%')
  14799. */
  14800. Graph.prototype.setSize = function(width, height) {
  14801. this.frame.style.width = width;
  14802. this.frame.style.height = height;
  14803. this.frame.canvas.style.width = '100%';
  14804. this.frame.canvas.style.height = '100%';
  14805. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14806. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14807. if (this.manipulationDiv !== undefined) {
  14808. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14809. }
  14810. if (this.navigationDivs !== undefined) {
  14811. if (this.navigationDivs['wrapper'] !== undefined) {
  14812. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14813. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14814. }
  14815. }
  14816. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14817. };
  14818. /**
  14819. * Set a data set with nodes for the graph
  14820. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14821. * @private
  14822. */
  14823. Graph.prototype._setNodes = function(nodes) {
  14824. var oldNodesData = this.nodesData;
  14825. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14826. this.nodesData = nodes;
  14827. }
  14828. else if (nodes instanceof Array) {
  14829. this.nodesData = new DataSet();
  14830. this.nodesData.add(nodes);
  14831. }
  14832. else if (!nodes) {
  14833. this.nodesData = new DataSet();
  14834. }
  14835. else {
  14836. throw new TypeError('Array or DataSet expected');
  14837. }
  14838. if (oldNodesData) {
  14839. // unsubscribe from old dataset
  14840. util.forEach(this.nodesListeners, function (callback, event) {
  14841. oldNodesData.off(event, callback);
  14842. });
  14843. }
  14844. // remove drawn nodes
  14845. this.nodes = {};
  14846. if (this.nodesData) {
  14847. // subscribe to new dataset
  14848. var me = this;
  14849. util.forEach(this.nodesListeners, function (callback, event) {
  14850. me.nodesData.on(event, callback);
  14851. });
  14852. // draw all new nodes
  14853. var ids = this.nodesData.getIds();
  14854. this._addNodes(ids);
  14855. }
  14856. this._updateSelection();
  14857. };
  14858. /**
  14859. * Add nodes
  14860. * @param {Number[] | String[]} ids
  14861. * @private
  14862. */
  14863. Graph.prototype._addNodes = function(ids) {
  14864. var id;
  14865. for (var i = 0, len = ids.length; i < len; i++) {
  14866. id = ids[i];
  14867. var data = this.nodesData.get(id);
  14868. var node = new Node(data, this.images, this.groups, this.constants);
  14869. this.nodes[id] = node; // note: this may replace an existing node
  14870. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14871. var radius = 10 * 0.1*ids.length;
  14872. var angle = 2 * Math.PI * Math.random();
  14873. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14874. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14875. }
  14876. this.moving = true;
  14877. }
  14878. this._updateNodeIndexList();
  14879. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14880. this._resetLevels();
  14881. this._setupHierarchicalLayout();
  14882. }
  14883. this._updateCalculationNodes();
  14884. this._reconnectEdges();
  14885. this._updateValueRange(this.nodes);
  14886. this.updateLabels();
  14887. };
  14888. /**
  14889. * Update existing nodes, or create them when not yet existing
  14890. * @param {Number[] | String[]} ids
  14891. * @private
  14892. */
  14893. Graph.prototype._updateNodes = function(ids) {
  14894. var nodes = this.nodes,
  14895. nodesData = this.nodesData;
  14896. for (var i = 0, len = ids.length; i < len; i++) {
  14897. var id = ids[i];
  14898. var node = nodes[id];
  14899. var data = nodesData.get(id);
  14900. if (node) {
  14901. // update node
  14902. node.setProperties(data, this.constants);
  14903. }
  14904. else {
  14905. // create node
  14906. node = new Node(properties, this.images, this.groups, this.constants);
  14907. nodes[id] = node;
  14908. }
  14909. }
  14910. this.moving = true;
  14911. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14912. this._resetLevels();
  14913. this._setupHierarchicalLayout();
  14914. }
  14915. this._updateNodeIndexList();
  14916. this._reconnectEdges();
  14917. this._updateValueRange(nodes);
  14918. };
  14919. /**
  14920. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14921. * @param {Number[] | String[]} ids
  14922. * @private
  14923. */
  14924. Graph.prototype._removeNodes = function(ids) {
  14925. var nodes = this.nodes;
  14926. for (var i = 0, len = ids.length; i < len; i++) {
  14927. var id = ids[i];
  14928. delete nodes[id];
  14929. }
  14930. this._updateNodeIndexList();
  14931. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14932. this._resetLevels();
  14933. this._setupHierarchicalLayout();
  14934. }
  14935. this._updateCalculationNodes();
  14936. this._reconnectEdges();
  14937. this._updateSelection();
  14938. this._updateValueRange(nodes);
  14939. };
  14940. /**
  14941. * Load edges by reading the data table
  14942. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14943. * @private
  14944. * @private
  14945. */
  14946. Graph.prototype._setEdges = function(edges) {
  14947. var oldEdgesData = this.edgesData;
  14948. if (edges instanceof DataSet || edges instanceof DataView) {
  14949. this.edgesData = edges;
  14950. }
  14951. else if (edges instanceof Array) {
  14952. this.edgesData = new DataSet();
  14953. this.edgesData.add(edges);
  14954. }
  14955. else if (!edges) {
  14956. this.edgesData = new DataSet();
  14957. }
  14958. else {
  14959. throw new TypeError('Array or DataSet expected');
  14960. }
  14961. if (oldEdgesData) {
  14962. // unsubscribe from old dataset
  14963. util.forEach(this.edgesListeners, function (callback, event) {
  14964. oldEdgesData.off(event, callback);
  14965. });
  14966. }
  14967. // remove drawn edges
  14968. this.edges = {};
  14969. if (this.edgesData) {
  14970. // subscribe to new dataset
  14971. var me = this;
  14972. util.forEach(this.edgesListeners, function (callback, event) {
  14973. me.edgesData.on(event, callback);
  14974. });
  14975. // draw all new nodes
  14976. var ids = this.edgesData.getIds();
  14977. this._addEdges(ids);
  14978. }
  14979. this._reconnectEdges();
  14980. };
  14981. /**
  14982. * Add edges
  14983. * @param {Number[] | String[]} ids
  14984. * @private
  14985. */
  14986. Graph.prototype._addEdges = function (ids) {
  14987. var edges = this.edges,
  14988. edgesData = this.edgesData;
  14989. for (var i = 0, len = ids.length; i < len; i++) {
  14990. var id = ids[i];
  14991. var oldEdge = edges[id];
  14992. if (oldEdge) {
  14993. oldEdge.disconnect();
  14994. }
  14995. var data = edgesData.get(id, {"showInternalIds" : true});
  14996. edges[id] = new Edge(data, this, this.constants);
  14997. }
  14998. this.moving = true;
  14999. this._updateValueRange(edges);
  15000. this._createBezierNodes();
  15001. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15002. this._resetLevels();
  15003. this._setupHierarchicalLayout();
  15004. }
  15005. this._updateCalculationNodes();
  15006. };
  15007. /**
  15008. * Update existing edges, or create them when not yet existing
  15009. * @param {Number[] | String[]} ids
  15010. * @private
  15011. */
  15012. Graph.prototype._updateEdges = function (ids) {
  15013. var edges = this.edges,
  15014. edgesData = this.edgesData;
  15015. for (var i = 0, len = ids.length; i < len; i++) {
  15016. var id = ids[i];
  15017. var data = edgesData.get(id);
  15018. var edge = edges[id];
  15019. if (edge) {
  15020. // update edge
  15021. edge.disconnect();
  15022. edge.setProperties(data, this.constants);
  15023. edge.connect();
  15024. }
  15025. else {
  15026. // create edge
  15027. edge = new Edge(data, this, this.constants);
  15028. this.edges[id] = edge;
  15029. }
  15030. }
  15031. this._createBezierNodes();
  15032. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15033. this._resetLevels();
  15034. this._setupHierarchicalLayout();
  15035. }
  15036. this.moving = true;
  15037. this._updateValueRange(edges);
  15038. };
  15039. /**
  15040. * Remove existing edges. Non existing ids will be ignored
  15041. * @param {Number[] | String[]} ids
  15042. * @private
  15043. */
  15044. Graph.prototype._removeEdges = function (ids) {
  15045. var edges = this.edges;
  15046. for (var i = 0, len = ids.length; i < len; i++) {
  15047. var id = ids[i];
  15048. var edge = edges[id];
  15049. if (edge) {
  15050. if (edge.via != null) {
  15051. delete this.sectors['support']['nodes'][edge.via.id];
  15052. }
  15053. edge.disconnect();
  15054. delete edges[id];
  15055. }
  15056. }
  15057. this.moving = true;
  15058. this._updateValueRange(edges);
  15059. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15060. this._resetLevels();
  15061. this._setupHierarchicalLayout();
  15062. }
  15063. this._updateCalculationNodes();
  15064. };
  15065. /**
  15066. * Reconnect all edges
  15067. * @private
  15068. */
  15069. Graph.prototype._reconnectEdges = function() {
  15070. var id,
  15071. nodes = this.nodes,
  15072. edges = this.edges;
  15073. for (id in nodes) {
  15074. if (nodes.hasOwnProperty(id)) {
  15075. nodes[id].edges = [];
  15076. }
  15077. }
  15078. for (id in edges) {
  15079. if (edges.hasOwnProperty(id)) {
  15080. var edge = edges[id];
  15081. edge.from = null;
  15082. edge.to = null;
  15083. edge.connect();
  15084. }
  15085. }
  15086. };
  15087. /**
  15088. * Update the values of all object in the given array according to the current
  15089. * value range of the objects in the array.
  15090. * @param {Object} obj An object containing a set of Edges or Nodes
  15091. * The objects must have a method getValue() and
  15092. * setValueRange(min, max).
  15093. * @private
  15094. */
  15095. Graph.prototype._updateValueRange = function(obj) {
  15096. var id;
  15097. // determine the range of the objects
  15098. var valueMin = undefined;
  15099. var valueMax = undefined;
  15100. for (id in obj) {
  15101. if (obj.hasOwnProperty(id)) {
  15102. var value = obj[id].getValue();
  15103. if (value !== undefined) {
  15104. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15105. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15106. }
  15107. }
  15108. }
  15109. // adjust the range of all objects
  15110. if (valueMin !== undefined && valueMax !== undefined) {
  15111. for (id in obj) {
  15112. if (obj.hasOwnProperty(id)) {
  15113. obj[id].setValueRange(valueMin, valueMax);
  15114. }
  15115. }
  15116. }
  15117. };
  15118. /**
  15119. * Redraw the graph with the current data
  15120. * chart will be resized too.
  15121. */
  15122. Graph.prototype.redraw = function() {
  15123. this.setSize(this.width, this.height);
  15124. this._redraw();
  15125. };
  15126. /**
  15127. * Redraw the graph with the current data
  15128. * @private
  15129. */
  15130. Graph.prototype._redraw = function() {
  15131. var ctx = this.frame.canvas.getContext('2d');
  15132. // clear the canvas
  15133. var w = this.frame.canvas.width;
  15134. var h = this.frame.canvas.height;
  15135. ctx.clearRect(0, 0, w, h);
  15136. // set scaling and translation
  15137. ctx.save();
  15138. ctx.translate(this.translation.x, this.translation.y);
  15139. ctx.scale(this.scale, this.scale);
  15140. this.canvasTopLeft = {
  15141. "x": this._XconvertDOMtoCanvas(0),
  15142. "y": this._YconvertDOMtoCanvas(0)
  15143. };
  15144. this.canvasBottomRight = {
  15145. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  15146. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  15147. };
  15148. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15149. this._doInAllSectors("_drawEdges",ctx);
  15150. this._doInAllSectors("_drawNodes",ctx,false);
  15151. // this._doInSupportSector("_drawNodes",ctx,true);
  15152. // this._drawTree(ctx,"#F00F0F");
  15153. // restore original scaling and translation
  15154. ctx.restore();
  15155. };
  15156. /**
  15157. * Set the translation of the graph
  15158. * @param {Number} offsetX Horizontal offset
  15159. * @param {Number} offsetY Vertical offset
  15160. * @private
  15161. */
  15162. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15163. if (this.translation === undefined) {
  15164. this.translation = {
  15165. x: 0,
  15166. y: 0
  15167. };
  15168. }
  15169. if (offsetX !== undefined) {
  15170. this.translation.x = offsetX;
  15171. }
  15172. if (offsetY !== undefined) {
  15173. this.translation.y = offsetY;
  15174. }
  15175. this.emit('viewChanged');
  15176. };
  15177. /**
  15178. * Get the translation of the graph
  15179. * @return {Object} translation An object with parameters x and y, both a number
  15180. * @private
  15181. */
  15182. Graph.prototype._getTranslation = function() {
  15183. return {
  15184. x: this.translation.x,
  15185. y: this.translation.y
  15186. };
  15187. };
  15188. /**
  15189. * Scale the graph
  15190. * @param {Number} scale Scaling factor 1.0 is unscaled
  15191. * @private
  15192. */
  15193. Graph.prototype._setScale = function(scale) {
  15194. this.scale = scale;
  15195. };
  15196. /**
  15197. * Get the current scale of the graph
  15198. * @return {Number} scale Scaling factor 1.0 is unscaled
  15199. * @private
  15200. */
  15201. Graph.prototype._getScale = function() {
  15202. return this.scale;
  15203. };
  15204. /**
  15205. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15206. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15207. * @param {number} x
  15208. * @returns {number}
  15209. * @private
  15210. */
  15211. Graph.prototype._XconvertDOMtoCanvas = function(x) {
  15212. return (x - this.translation.x) / this.scale;
  15213. };
  15214. /**
  15215. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15216. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  15217. * @param {number} x
  15218. * @returns {number}
  15219. * @private
  15220. */
  15221. Graph.prototype._XconvertCanvasToDOM = function(x) {
  15222. return x * this.scale + this.translation.x;
  15223. };
  15224. /**
  15225. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15226. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15227. * @param {number} y
  15228. * @returns {number}
  15229. * @private
  15230. */
  15231. Graph.prototype._YconvertDOMtoCanvas = function(y) {
  15232. return (y - this.translation.y) / this.scale;
  15233. };
  15234. /**
  15235. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15236. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  15237. * @param {number} y
  15238. * @returns {number}
  15239. * @private
  15240. */
  15241. Graph.prototype._YconvertCanvasToDOM = function(y) {
  15242. return y * this.scale + this.translation.y ;
  15243. };
  15244. /**
  15245. *
  15246. * @param {object} pos = {x: number, y: number}
  15247. * @returns {{x: number, y: number}}
  15248. * @constructor
  15249. */
  15250. Graph.prototype.canvasToDOM = function(pos) {
  15251. return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)};
  15252. }
  15253. /**
  15254. *
  15255. * @param {object} pos = {x: number, y: number}
  15256. * @returns {{x: number, y: number}}
  15257. * @constructor
  15258. */
  15259. Graph.prototype.DOMtoCanvas = function(pos) {
  15260. return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)};
  15261. }
  15262. /**
  15263. * Redraw all nodes
  15264. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15265. * @param {CanvasRenderingContext2D} ctx
  15266. * @param {Boolean} [alwaysShow]
  15267. * @private
  15268. */
  15269. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15270. if (alwaysShow === undefined) {
  15271. alwaysShow = false;
  15272. }
  15273. // first draw the unselected nodes
  15274. var nodes = this.nodes;
  15275. var selected = [];
  15276. for (var id in nodes) {
  15277. if (nodes.hasOwnProperty(id)) {
  15278. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15279. if (nodes[id].isSelected()) {
  15280. selected.push(id);
  15281. }
  15282. else {
  15283. if (nodes[id].inArea() || alwaysShow) {
  15284. nodes[id].draw(ctx);
  15285. }
  15286. }
  15287. }
  15288. }
  15289. // draw the selected nodes on top
  15290. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15291. if (nodes[selected[s]].inArea() || alwaysShow) {
  15292. nodes[selected[s]].draw(ctx);
  15293. }
  15294. }
  15295. };
  15296. /**
  15297. * Redraw all edges
  15298. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15299. * @param {CanvasRenderingContext2D} ctx
  15300. * @private
  15301. */
  15302. Graph.prototype._drawEdges = function(ctx) {
  15303. var edges = this.edges;
  15304. for (var id in edges) {
  15305. if (edges.hasOwnProperty(id)) {
  15306. var edge = edges[id];
  15307. edge.setScale(this.scale);
  15308. if (edge.connected) {
  15309. edges[id].draw(ctx);
  15310. }
  15311. }
  15312. }
  15313. };
  15314. /**
  15315. * Find a stable position for all nodes
  15316. * @private
  15317. */
  15318. Graph.prototype._stabilize = function() {
  15319. if (this.constants.freezeForStabilization == true) {
  15320. this._freezeDefinedNodes();
  15321. }
  15322. // find stable position
  15323. var count = 0;
  15324. while (this.moving && count < this.constants.stabilizationIterations) {
  15325. this._physicsTick();
  15326. count++;
  15327. }
  15328. this.zoomExtent(false,true);
  15329. if (this.constants.freezeForStabilization == true) {
  15330. this._restoreFrozenNodes();
  15331. }
  15332. this.emit("stabilized",{iterations:count});
  15333. };
  15334. /**
  15335. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15336. * because only the supportnodes for the smoothCurves have to settle.
  15337. *
  15338. * @private
  15339. */
  15340. Graph.prototype._freezeDefinedNodes = function() {
  15341. var nodes = this.nodes;
  15342. for (var id in nodes) {
  15343. if (nodes.hasOwnProperty(id)) {
  15344. if (nodes[id].x != null && nodes[id].y != null) {
  15345. nodes[id].fixedData.x = nodes[id].xFixed;
  15346. nodes[id].fixedData.y = nodes[id].yFixed;
  15347. nodes[id].xFixed = true;
  15348. nodes[id].yFixed = true;
  15349. }
  15350. }
  15351. }
  15352. };
  15353. /**
  15354. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15355. *
  15356. * @private
  15357. */
  15358. Graph.prototype._restoreFrozenNodes = function() {
  15359. var nodes = this.nodes;
  15360. for (var id in nodes) {
  15361. if (nodes.hasOwnProperty(id)) {
  15362. if (nodes[id].fixedData.x != null) {
  15363. nodes[id].xFixed = nodes[id].fixedData.x;
  15364. nodes[id].yFixed = nodes[id].fixedData.y;
  15365. }
  15366. }
  15367. }
  15368. };
  15369. /**
  15370. * Check if any of the nodes is still moving
  15371. * @param {number} vmin the minimum velocity considered as 'moving'
  15372. * @return {boolean} true if moving, false if non of the nodes is moving
  15373. * @private
  15374. */
  15375. Graph.prototype._isMoving = function(vmin) {
  15376. var nodes = this.nodes;
  15377. for (var id in nodes) {
  15378. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15379. return true;
  15380. }
  15381. }
  15382. return false;
  15383. };
  15384. /**
  15385. * /**
  15386. * Perform one discrete step for all nodes
  15387. *
  15388. * @private
  15389. */
  15390. Graph.prototype._discreteStepNodes = function() {
  15391. var interval = this.physicsDiscreteStepsize;
  15392. var nodes = this.nodes;
  15393. var nodeId;
  15394. var nodesPresent = false;
  15395. if (this.constants.maxVelocity > 0) {
  15396. for (nodeId in nodes) {
  15397. if (nodes.hasOwnProperty(nodeId)) {
  15398. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15399. nodesPresent = true;
  15400. }
  15401. }
  15402. }
  15403. else {
  15404. for (nodeId in nodes) {
  15405. if (nodes.hasOwnProperty(nodeId)) {
  15406. nodes[nodeId].discreteStep(interval);
  15407. nodesPresent = true;
  15408. }
  15409. }
  15410. }
  15411. if (nodesPresent == true) {
  15412. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15413. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15414. this.moving = true;
  15415. }
  15416. else {
  15417. this.moving = this._isMoving(vminCorrected);
  15418. }
  15419. }
  15420. };
  15421. /**
  15422. * A single simulation step (or "tick") in the physics simulation
  15423. *
  15424. * @private
  15425. */
  15426. Graph.prototype._physicsTick = function() {
  15427. if (!this.freezeSimulation) {
  15428. if (this.moving) {
  15429. this._doInAllActiveSectors("_initializeForceCalculation");
  15430. this._doInAllActiveSectors("_discreteStepNodes");
  15431. if (this.constants.smoothCurves) {
  15432. this._doInSupportSector("_discreteStepNodes");
  15433. }
  15434. this._findCenter(this._getRange())
  15435. }
  15436. }
  15437. };
  15438. /**
  15439. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15440. * It reschedules itself at the beginning of the function
  15441. *
  15442. * @private
  15443. */
  15444. Graph.prototype._animationStep = function() {
  15445. // reset the timer so a new scheduled animation step can be set
  15446. this.timer = undefined;
  15447. // handle the keyboad movement
  15448. this._handleNavigation();
  15449. // this schedules a new animation step
  15450. this.start();
  15451. // start the physics simulation
  15452. var calculationTime = Date.now();
  15453. var maxSteps = 1;
  15454. this._physicsTick();
  15455. var timeRequired = Date.now() - calculationTime;
  15456. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15457. this._physicsTick();
  15458. timeRequired = Date.now() - calculationTime;
  15459. maxSteps++;
  15460. }
  15461. // start the rendering process
  15462. var renderTime = Date.now();
  15463. this._redraw();
  15464. this.renderTime = Date.now() - renderTime;
  15465. };
  15466. if (typeof window !== 'undefined') {
  15467. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15468. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15469. }
  15470. /**
  15471. * Schedule a animation step with the refreshrate interval.
  15472. */
  15473. Graph.prototype.start = function() {
  15474. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15475. if (!this.timer) {
  15476. var ua = navigator.userAgent.toLowerCase();
  15477. var requiresTimeout = false;
  15478. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15479. requiresTimeout = true;
  15480. }
  15481. else if (ua.indexOf('safari') != -1) { // safari
  15482. if (ua.indexOf('chrome') <= -1) {
  15483. requiresTimeout = true;
  15484. }
  15485. }
  15486. if (requiresTimeout == true) {
  15487. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15488. }
  15489. else{
  15490. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15491. }
  15492. }
  15493. }
  15494. else {
  15495. this._redraw();
  15496. }
  15497. };
  15498. /**
  15499. * Move the graph according to the keyboard presses.
  15500. *
  15501. * @private
  15502. */
  15503. Graph.prototype._handleNavigation = function() {
  15504. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15505. var translation = this._getTranslation();
  15506. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15507. }
  15508. if (this.zoomIncrement != 0) {
  15509. var center = {
  15510. x: this.frame.canvas.clientWidth / 2,
  15511. y: this.frame.canvas.clientHeight / 2
  15512. };
  15513. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15514. }
  15515. };
  15516. /**
  15517. * Freeze the _animationStep
  15518. */
  15519. Graph.prototype.toggleFreeze = function() {
  15520. if (this.freezeSimulation == false) {
  15521. this.freezeSimulation = true;
  15522. }
  15523. else {
  15524. this.freezeSimulation = false;
  15525. this.start();
  15526. }
  15527. };
  15528. /**
  15529. * This function cleans the support nodes if they are not needed and adds them when they are.
  15530. *
  15531. * @param {boolean} [disableStart]
  15532. * @private
  15533. */
  15534. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15535. if (disableStart === undefined) {
  15536. disableStart = true;
  15537. }
  15538. if (this.constants.smoothCurves == true) {
  15539. this._createBezierNodes();
  15540. }
  15541. else {
  15542. // delete the support nodes
  15543. this.sectors['support']['nodes'] = {};
  15544. for (var edgeId in this.edges) {
  15545. if (this.edges.hasOwnProperty(edgeId)) {
  15546. this.edges[edgeId].smooth = false;
  15547. this.edges[edgeId].via = null;
  15548. }
  15549. }
  15550. }
  15551. this._updateCalculationNodes();
  15552. if (!disableStart) {
  15553. this.moving = true;
  15554. this.start();
  15555. }
  15556. };
  15557. /**
  15558. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  15559. * are used for the force calculation.
  15560. *
  15561. * @private
  15562. */
  15563. Graph.prototype._createBezierNodes = function() {
  15564. if (this.constants.smoothCurves == true) {
  15565. for (var edgeId in this.edges) {
  15566. if (this.edges.hasOwnProperty(edgeId)) {
  15567. var edge = this.edges[edgeId];
  15568. if (edge.via == null) {
  15569. edge.smooth = true;
  15570. var nodeId = "edgeId:".concat(edge.id);
  15571. this.sectors['support']['nodes'][nodeId] = new Node(
  15572. {id:nodeId,
  15573. mass:1,
  15574. shape:'circle',
  15575. image:"",
  15576. internalMultiplier:1
  15577. },{},{},this.constants);
  15578. edge.via = this.sectors['support']['nodes'][nodeId];
  15579. edge.via.parentEdgeId = edge.id;
  15580. edge.positionBezierNode();
  15581. }
  15582. }
  15583. }
  15584. }
  15585. };
  15586. /**
  15587. * load the functions that load the mixins into the prototype.
  15588. *
  15589. * @private
  15590. */
  15591. Graph.prototype._initializeMixinLoaders = function () {
  15592. for (var mixinFunction in graphMixinLoaders) {
  15593. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15594. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15595. }
  15596. }
  15597. };
  15598. /**
  15599. * Load the XY positions of the nodes into the dataset.
  15600. */
  15601. Graph.prototype.storePosition = function() {
  15602. var dataArray = [];
  15603. for (var nodeId in this.nodes) {
  15604. if (this.nodes.hasOwnProperty(nodeId)) {
  15605. var node = this.nodes[nodeId];
  15606. var allowedToMoveX = !this.nodes.xFixed;
  15607. var allowedToMoveY = !this.nodes.yFixed;
  15608. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15609. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15610. }
  15611. }
  15612. }
  15613. this.nodesData.update(dataArray);
  15614. };
  15615. /**
  15616. * vis.js module exports
  15617. */
  15618. var vis = {
  15619. util: util,
  15620. moment: moment,
  15621. DataSet: DataSet,
  15622. DataView: DataView,
  15623. Range: Range,
  15624. stack: stack,
  15625. TimeStep: TimeStep,
  15626. components: {
  15627. items: {
  15628. Item: Item,
  15629. ItemBox: ItemBox,
  15630. ItemPoint: ItemPoint,
  15631. ItemRange: ItemRange
  15632. },
  15633. Component: Component,
  15634. Panel: Panel,
  15635. RootPanel: RootPanel,
  15636. ItemSet: ItemSet,
  15637. TimeAxis: TimeAxis
  15638. },
  15639. graph: {
  15640. Node: Node,
  15641. Edge: Edge,
  15642. Popup: Popup,
  15643. Groups: Groups,
  15644. Images: Images
  15645. },
  15646. Timeline: Timeline,
  15647. Graph: Graph
  15648. };
  15649. /**
  15650. * CommonJS module exports
  15651. */
  15652. if (typeof exports !== 'undefined') {
  15653. exports = vis;
  15654. }
  15655. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15656. module.exports = vis;
  15657. }
  15658. /**
  15659. * AMD module exports
  15660. */
  15661. if (typeof(define) === 'function') {
  15662. define(function () {
  15663. return vis;
  15664. });
  15665. }
  15666. /**
  15667. * Window exports
  15668. */
  15669. if (typeof window !== 'undefined') {
  15670. // attach the module to the window, load as a regular javascript file
  15671. window['vis'] = vis;
  15672. }
  15673. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15674. /**
  15675. * Expose `Emitter`.
  15676. */
  15677. module.exports = Emitter;
  15678. /**
  15679. * Initialize a new `Emitter`.
  15680. *
  15681. * @api public
  15682. */
  15683. function Emitter(obj) {
  15684. if (obj) return mixin(obj);
  15685. };
  15686. /**
  15687. * Mixin the emitter properties.
  15688. *
  15689. * @param {Object} obj
  15690. * @return {Object}
  15691. * @api private
  15692. */
  15693. function mixin(obj) {
  15694. for (var key in Emitter.prototype) {
  15695. obj[key] = Emitter.prototype[key];
  15696. }
  15697. return obj;
  15698. }
  15699. /**
  15700. * Listen on the given `event` with `fn`.
  15701. *
  15702. * @param {String} event
  15703. * @param {Function} fn
  15704. * @return {Emitter}
  15705. * @api public
  15706. */
  15707. Emitter.prototype.on =
  15708. Emitter.prototype.addEventListener = function(event, fn){
  15709. this._callbacks = this._callbacks || {};
  15710. (this._callbacks[event] = this._callbacks[event] || [])
  15711. .push(fn);
  15712. return this;
  15713. };
  15714. /**
  15715. * Adds an `event` listener that will be invoked a single
  15716. * time then automatically removed.
  15717. *
  15718. * @param {String} event
  15719. * @param {Function} fn
  15720. * @return {Emitter}
  15721. * @api public
  15722. */
  15723. Emitter.prototype.once = function(event, fn){
  15724. var self = this;
  15725. this._callbacks = this._callbacks || {};
  15726. function on() {
  15727. self.off(event, on);
  15728. fn.apply(this, arguments);
  15729. }
  15730. on.fn = fn;
  15731. this.on(event, on);
  15732. return this;
  15733. };
  15734. /**
  15735. * Remove the given callback for `event` or all
  15736. * registered callbacks.
  15737. *
  15738. * @param {String} event
  15739. * @param {Function} fn
  15740. * @return {Emitter}
  15741. * @api public
  15742. */
  15743. Emitter.prototype.off =
  15744. Emitter.prototype.removeListener =
  15745. Emitter.prototype.removeAllListeners =
  15746. Emitter.prototype.removeEventListener = function(event, fn){
  15747. this._callbacks = this._callbacks || {};
  15748. // all
  15749. if (0 == arguments.length) {
  15750. this._callbacks = {};
  15751. return this;
  15752. }
  15753. // specific event
  15754. var callbacks = this._callbacks[event];
  15755. if (!callbacks) return this;
  15756. // remove all handlers
  15757. if (1 == arguments.length) {
  15758. delete this._callbacks[event];
  15759. return this;
  15760. }
  15761. // remove specific handler
  15762. var cb;
  15763. for (var i = 0; i < callbacks.length; i++) {
  15764. cb = callbacks[i];
  15765. if (cb === fn || cb.fn === fn) {
  15766. callbacks.splice(i, 1);
  15767. break;
  15768. }
  15769. }
  15770. return this;
  15771. };
  15772. /**
  15773. * Emit `event` with the given args.
  15774. *
  15775. * @param {String} event
  15776. * @param {Mixed} ...
  15777. * @return {Emitter}
  15778. */
  15779. Emitter.prototype.emit = function(event){
  15780. this._callbacks = this._callbacks || {};
  15781. var args = [].slice.call(arguments, 1)
  15782. , callbacks = this._callbacks[event];
  15783. if (callbacks) {
  15784. callbacks = callbacks.slice(0);
  15785. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15786. callbacks[i].apply(this, args);
  15787. }
  15788. }
  15789. return this;
  15790. };
  15791. /**
  15792. * Return array of callbacks for `event`.
  15793. *
  15794. * @param {String} event
  15795. * @return {Array}
  15796. * @api public
  15797. */
  15798. Emitter.prototype.listeners = function(event){
  15799. this._callbacks = this._callbacks || {};
  15800. return this._callbacks[event] || [];
  15801. };
  15802. /**
  15803. * Check if this emitter has `event` handlers.
  15804. *
  15805. * @param {String} event
  15806. * @return {Boolean}
  15807. * @api public
  15808. */
  15809. Emitter.prototype.hasListeners = function(event){
  15810. return !! this.listeners(event).length;
  15811. };
  15812. },{}],3:[function(require,module,exports){
  15813. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15814. * http://eightmedia.github.com/hammer.js
  15815. *
  15816. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15817. * Licensed under the MIT license */
  15818. (function(window, undefined) {
  15819. 'use strict';
  15820. /**
  15821. * Hammer
  15822. * use this to create instances
  15823. * @param {HTMLElement} element
  15824. * @param {Object} options
  15825. * @returns {Hammer.Instance}
  15826. * @constructor
  15827. */
  15828. var Hammer = function(element, options) {
  15829. return new Hammer.Instance(element, options || {});
  15830. };
  15831. // default settings
  15832. Hammer.defaults = {
  15833. // add styles and attributes to the element to prevent the browser from doing
  15834. // its native behavior. this doesnt prevent the scrolling, but cancels
  15835. // the contextmenu, tap highlighting etc
  15836. // set to false to disable this
  15837. stop_browser_behavior: {
  15838. // this also triggers onselectstart=false for IE
  15839. userSelect: 'none',
  15840. // this makes the element blocking in IE10 >, you could experiment with the value
  15841. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15842. touchAction: 'none',
  15843. touchCallout: 'none',
  15844. contentZooming: 'none',
  15845. userDrag: 'none',
  15846. tapHighlightColor: 'rgba(0,0,0,0)'
  15847. }
  15848. // more settings are defined per gesture at gestures.js
  15849. };
  15850. // detect touchevents
  15851. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15852. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15853. // dont use mouseevents on mobile devices
  15854. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15855. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15856. // eventtypes per touchevent (start, move, end)
  15857. // are filled by Hammer.event.determineEventTypes on setup
  15858. Hammer.EVENT_TYPES = {};
  15859. // direction defines
  15860. Hammer.DIRECTION_DOWN = 'down';
  15861. Hammer.DIRECTION_LEFT = 'left';
  15862. Hammer.DIRECTION_UP = 'up';
  15863. Hammer.DIRECTION_RIGHT = 'right';
  15864. // pointer type
  15865. Hammer.POINTER_MOUSE = 'mouse';
  15866. Hammer.POINTER_TOUCH = 'touch';
  15867. Hammer.POINTER_PEN = 'pen';
  15868. // touch event defines
  15869. Hammer.EVENT_START = 'start';
  15870. Hammer.EVENT_MOVE = 'move';
  15871. Hammer.EVENT_END = 'end';
  15872. // hammer document where the base events are added at
  15873. Hammer.DOCUMENT = document;
  15874. // plugins namespace
  15875. Hammer.plugins = {};
  15876. // if the window events are set...
  15877. Hammer.READY = false;
  15878. /**
  15879. * setup events to detect gestures on the document
  15880. */
  15881. function setup() {
  15882. if(Hammer.READY) {
  15883. return;
  15884. }
  15885. // find what eventtypes we add listeners to
  15886. Hammer.event.determineEventTypes();
  15887. // Register all gestures inside Hammer.gestures
  15888. for(var name in Hammer.gestures) {
  15889. if(Hammer.gestures.hasOwnProperty(name)) {
  15890. Hammer.detection.register(Hammer.gestures[name]);
  15891. }
  15892. }
  15893. // Add touch events on the document
  15894. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15895. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15896. // Hammer is ready...!
  15897. Hammer.READY = true;
  15898. }
  15899. /**
  15900. * create new hammer instance
  15901. * all methods should return the instance itself, so it is chainable.
  15902. * @param {HTMLElement} element
  15903. * @param {Object} [options={}]
  15904. * @returns {Hammer.Instance}
  15905. * @constructor
  15906. */
  15907. Hammer.Instance = function(element, options) {
  15908. var self = this;
  15909. // setup HammerJS window events and register all gestures
  15910. // this also sets up the default options
  15911. setup();
  15912. this.element = element;
  15913. // start/stop detection option
  15914. this.enabled = true;
  15915. // merge options
  15916. this.options = Hammer.utils.extend(
  15917. Hammer.utils.extend({}, Hammer.defaults),
  15918. options || {});
  15919. // add some css to the element to prevent the browser from doing its native behavoir
  15920. if(this.options.stop_browser_behavior) {
  15921. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15922. }
  15923. // start detection on touchstart
  15924. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15925. if(self.enabled) {
  15926. Hammer.detection.startDetect(self, ev);
  15927. }
  15928. });
  15929. // return instance
  15930. return this;
  15931. };
  15932. Hammer.Instance.prototype = {
  15933. /**
  15934. * bind events to the instance
  15935. * @param {String} gesture
  15936. * @param {Function} handler
  15937. * @returns {Hammer.Instance}
  15938. */
  15939. on: function onEvent(gesture, handler){
  15940. var gestures = gesture.split(' ');
  15941. for(var t=0; t<gestures.length; t++) {
  15942. this.element.addEventListener(gestures[t], handler, false);
  15943. }
  15944. return this;
  15945. },
  15946. /**
  15947. * unbind events to the instance
  15948. * @param {String} gesture
  15949. * @param {Function} handler
  15950. * @returns {Hammer.Instance}
  15951. */
  15952. off: function offEvent(gesture, handler){
  15953. var gestures = gesture.split(' ');
  15954. for(var t=0; t<gestures.length; t++) {
  15955. this.element.removeEventListener(gestures[t], handler, false);
  15956. }
  15957. return this;
  15958. },
  15959. /**
  15960. * trigger gesture event
  15961. * @param {String} gesture
  15962. * @param {Object} eventData
  15963. * @returns {Hammer.Instance}
  15964. */
  15965. trigger: function triggerEvent(gesture, eventData){
  15966. // create DOM event
  15967. var event = Hammer.DOCUMENT.createEvent('Event');
  15968. event.initEvent(gesture, true, true);
  15969. event.gesture = eventData;
  15970. // trigger on the target if it is in the instance element,
  15971. // this is for event delegation tricks
  15972. var element = this.element;
  15973. if(Hammer.utils.hasParent(eventData.target, element)) {
  15974. element = eventData.target;
  15975. }
  15976. element.dispatchEvent(event);
  15977. return this;
  15978. },
  15979. /**
  15980. * enable of disable hammer.js detection
  15981. * @param {Boolean} state
  15982. * @returns {Hammer.Instance}
  15983. */
  15984. enable: function enable(state) {
  15985. this.enabled = state;
  15986. return this;
  15987. }
  15988. };
  15989. /**
  15990. * this holds the last move event,
  15991. * used to fix empty touchend issue
  15992. * see the onTouch event for an explanation
  15993. * @type {Object}
  15994. */
  15995. var last_move_event = null;
  15996. /**
  15997. * when the mouse is hold down, this is true
  15998. * @type {Boolean}
  15999. */
  16000. var enable_detect = false;
  16001. /**
  16002. * when touch events have been fired, this is true
  16003. * @type {Boolean}
  16004. */
  16005. var touch_triggered = false;
  16006. Hammer.event = {
  16007. /**
  16008. * simple addEventListener
  16009. * @param {HTMLElement} element
  16010. * @param {String} type
  16011. * @param {Function} handler
  16012. */
  16013. bindDom: function(element, type, handler) {
  16014. var types = type.split(' ');
  16015. for(var t=0; t<types.length; t++) {
  16016. element.addEventListener(types[t], handler, false);
  16017. }
  16018. },
  16019. /**
  16020. * touch events with mouse fallback
  16021. * @param {HTMLElement} element
  16022. * @param {String} eventType like Hammer.EVENT_MOVE
  16023. * @param {Function} handler
  16024. */
  16025. onTouch: function onTouch(element, eventType, handler) {
  16026. var self = this;
  16027. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16028. var sourceEventType = ev.type.toLowerCase();
  16029. // onmouseup, but when touchend has been fired we do nothing.
  16030. // this is for touchdevices which also fire a mouseup on touchend
  16031. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16032. return;
  16033. }
  16034. // mousebutton must be down or a touch event
  16035. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16036. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16037. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16038. ){
  16039. enable_detect = true;
  16040. }
  16041. // we are in a touch event, set the touch triggered bool to true,
  16042. // this for the conflicts that may occur on ios and android
  16043. if(sourceEventType.match(/touch|pointer/)) {
  16044. touch_triggered = true;
  16045. }
  16046. // count the total touches on the screen
  16047. var count_touches = 0;
  16048. // when touch has been triggered in this detection session
  16049. // and we are now handling a mouse event, we stop that to prevent conflicts
  16050. if(enable_detect) {
  16051. // update pointerevent
  16052. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16053. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16054. }
  16055. // touch
  16056. else if(sourceEventType.match(/touch/)) {
  16057. count_touches = ev.touches.length;
  16058. }
  16059. // mouse
  16060. else if(!touch_triggered) {
  16061. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16062. }
  16063. // if we are in a end event, but when we remove one touch and
  16064. // we still have enough, set eventType to move
  16065. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16066. eventType = Hammer.EVENT_MOVE;
  16067. }
  16068. // no touches, force the end event
  16069. else if(!count_touches) {
  16070. eventType = Hammer.EVENT_END;
  16071. }
  16072. // because touchend has no touches, and we often want to use these in our gestures,
  16073. // we send the last move event as our eventData in touchend
  16074. if(!count_touches && last_move_event !== null) {
  16075. ev = last_move_event;
  16076. }
  16077. // store the last move event
  16078. else {
  16079. last_move_event = ev;
  16080. }
  16081. // trigger the handler
  16082. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16083. // remove pointerevent from list
  16084. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16085. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16086. }
  16087. }
  16088. //debug(sourceEventType +" "+ eventType);
  16089. // on the end we reset everything
  16090. if(!count_touches) {
  16091. last_move_event = null;
  16092. enable_detect = false;
  16093. touch_triggered = false;
  16094. Hammer.PointerEvent.reset();
  16095. }
  16096. });
  16097. },
  16098. /**
  16099. * we have different events for each device/browser
  16100. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16101. */
  16102. determineEventTypes: function determineEventTypes() {
  16103. // determine the eventtype we want to set
  16104. var types;
  16105. // pointerEvents magic
  16106. if(Hammer.HAS_POINTEREVENTS) {
  16107. types = Hammer.PointerEvent.getEvents();
  16108. }
  16109. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16110. else if(Hammer.NO_MOUSEEVENTS) {
  16111. types = [
  16112. 'touchstart',
  16113. 'touchmove',
  16114. 'touchend touchcancel'];
  16115. }
  16116. // for non pointer events browsers and mixed browsers,
  16117. // like chrome on windows8 touch laptop
  16118. else {
  16119. types = [
  16120. 'touchstart mousedown',
  16121. 'touchmove mousemove',
  16122. 'touchend touchcancel mouseup'];
  16123. }
  16124. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16125. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16126. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16127. },
  16128. /**
  16129. * create touchlist depending on the event
  16130. * @param {Object} ev
  16131. * @param {String} eventType used by the fakemultitouch plugin
  16132. */
  16133. getTouchList: function getTouchList(ev/*, eventType*/) {
  16134. // get the fake pointerEvent touchlist
  16135. if(Hammer.HAS_POINTEREVENTS) {
  16136. return Hammer.PointerEvent.getTouchList();
  16137. }
  16138. // get the touchlist
  16139. else if(ev.touches) {
  16140. return ev.touches;
  16141. }
  16142. // make fake touchlist from mouse position
  16143. else {
  16144. return [{
  16145. identifier: 1,
  16146. pageX: ev.pageX,
  16147. pageY: ev.pageY,
  16148. target: ev.target
  16149. }];
  16150. }
  16151. },
  16152. /**
  16153. * collect event data for Hammer js
  16154. * @param {HTMLElement} element
  16155. * @param {String} eventType like Hammer.EVENT_MOVE
  16156. * @param {Object} eventData
  16157. */
  16158. collectEventData: function collectEventData(element, eventType, ev) {
  16159. var touches = this.getTouchList(ev, eventType);
  16160. // find out pointerType
  16161. var pointerType = Hammer.POINTER_TOUCH;
  16162. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16163. pointerType = Hammer.POINTER_MOUSE;
  16164. }
  16165. return {
  16166. center : Hammer.utils.getCenter(touches),
  16167. timeStamp : new Date().getTime(),
  16168. target : ev.target,
  16169. touches : touches,
  16170. eventType : eventType,
  16171. pointerType : pointerType,
  16172. srcEvent : ev,
  16173. /**
  16174. * prevent the browser default actions
  16175. * mostly used to disable scrolling of the browser
  16176. */
  16177. preventDefault: function() {
  16178. if(this.srcEvent.preventManipulation) {
  16179. this.srcEvent.preventManipulation();
  16180. }
  16181. if(this.srcEvent.preventDefault) {
  16182. this.srcEvent.preventDefault();
  16183. }
  16184. },
  16185. /**
  16186. * stop bubbling the event up to its parents
  16187. */
  16188. stopPropagation: function() {
  16189. this.srcEvent.stopPropagation();
  16190. },
  16191. /**
  16192. * immediately stop gesture detection
  16193. * might be useful after a swipe was detected
  16194. * @return {*}
  16195. */
  16196. stopDetect: function() {
  16197. return Hammer.detection.stopDetect();
  16198. }
  16199. };
  16200. }
  16201. };
  16202. Hammer.PointerEvent = {
  16203. /**
  16204. * holds all pointers
  16205. * @type {Object}
  16206. */
  16207. pointers: {},
  16208. /**
  16209. * get a list of pointers
  16210. * @returns {Array} touchlist
  16211. */
  16212. getTouchList: function() {
  16213. var self = this;
  16214. var touchlist = [];
  16215. // we can use forEach since pointerEvents only is in IE10
  16216. Object.keys(self.pointers).sort().forEach(function(id) {
  16217. touchlist.push(self.pointers[id]);
  16218. });
  16219. return touchlist;
  16220. },
  16221. /**
  16222. * update the position of a pointer
  16223. * @param {String} type Hammer.EVENT_END
  16224. * @param {Object} pointerEvent
  16225. */
  16226. updatePointer: function(type, pointerEvent) {
  16227. if(type == Hammer.EVENT_END) {
  16228. this.pointers = {};
  16229. }
  16230. else {
  16231. pointerEvent.identifier = pointerEvent.pointerId;
  16232. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16233. }
  16234. return Object.keys(this.pointers).length;
  16235. },
  16236. /**
  16237. * check if ev matches pointertype
  16238. * @param {String} pointerType Hammer.POINTER_MOUSE
  16239. * @param {PointerEvent} ev
  16240. */
  16241. matchType: function(pointerType, ev) {
  16242. if(!ev.pointerType) {
  16243. return false;
  16244. }
  16245. var types = {};
  16246. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16247. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16248. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16249. return types[pointerType];
  16250. },
  16251. /**
  16252. * get events
  16253. */
  16254. getEvents: function() {
  16255. return [
  16256. 'pointerdown MSPointerDown',
  16257. 'pointermove MSPointerMove',
  16258. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16259. ];
  16260. },
  16261. /**
  16262. * reset the list
  16263. */
  16264. reset: function() {
  16265. this.pointers = {};
  16266. }
  16267. };
  16268. Hammer.utils = {
  16269. /**
  16270. * extend method,
  16271. * also used for cloning when dest is an empty object
  16272. * @param {Object} dest
  16273. * @param {Object} src
  16274. * @parm {Boolean} merge do a merge
  16275. * @returns {Object} dest
  16276. */
  16277. extend: function extend(dest, src, merge) {
  16278. for (var key in src) {
  16279. if(dest[key] !== undefined && merge) {
  16280. continue;
  16281. }
  16282. dest[key] = src[key];
  16283. }
  16284. return dest;
  16285. },
  16286. /**
  16287. * find if a node is in the given parent
  16288. * used for event delegation tricks
  16289. * @param {HTMLElement} node
  16290. * @param {HTMLElement} parent
  16291. * @returns {boolean} has_parent
  16292. */
  16293. hasParent: function(node, parent) {
  16294. while(node){
  16295. if(node == parent) {
  16296. return true;
  16297. }
  16298. node = node.parentNode;
  16299. }
  16300. return false;
  16301. },
  16302. /**
  16303. * get the center of all the touches
  16304. * @param {Array} touches
  16305. * @returns {Object} center
  16306. */
  16307. getCenter: function getCenter(touches) {
  16308. var valuesX = [], valuesY = [];
  16309. for(var t= 0,len=touches.length; t<len; t++) {
  16310. valuesX.push(touches[t].pageX);
  16311. valuesY.push(touches[t].pageY);
  16312. }
  16313. return {
  16314. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16315. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16316. };
  16317. },
  16318. /**
  16319. * calculate the velocity between two points
  16320. * @param {Number} delta_time
  16321. * @param {Number} delta_x
  16322. * @param {Number} delta_y
  16323. * @returns {Object} velocity
  16324. */
  16325. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16326. return {
  16327. x: Math.abs(delta_x / delta_time) || 0,
  16328. y: Math.abs(delta_y / delta_time) || 0
  16329. };
  16330. },
  16331. /**
  16332. * calculate the angle between two coordinates
  16333. * @param {Touch} touch1
  16334. * @param {Touch} touch2
  16335. * @returns {Number} angle
  16336. */
  16337. getAngle: function getAngle(touch1, touch2) {
  16338. var y = touch2.pageY - touch1.pageY,
  16339. x = touch2.pageX - touch1.pageX;
  16340. return Math.atan2(y, x) * 180 / Math.PI;
  16341. },
  16342. /**
  16343. * angle to direction define
  16344. * @param {Touch} touch1
  16345. * @param {Touch} touch2
  16346. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16347. */
  16348. getDirection: function getDirection(touch1, touch2) {
  16349. var x = Math.abs(touch1.pageX - touch2.pageX),
  16350. y = Math.abs(touch1.pageY - touch2.pageY);
  16351. if(x >= y) {
  16352. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16353. }
  16354. else {
  16355. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16356. }
  16357. },
  16358. /**
  16359. * calculate the distance between two touches
  16360. * @param {Touch} touch1
  16361. * @param {Touch} touch2
  16362. * @returns {Number} distance
  16363. */
  16364. getDistance: function getDistance(touch1, touch2) {
  16365. var x = touch2.pageX - touch1.pageX,
  16366. y = touch2.pageY - touch1.pageY;
  16367. return Math.sqrt((x*x) + (y*y));
  16368. },
  16369. /**
  16370. * calculate the scale factor between two touchLists (fingers)
  16371. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16372. * @param {Array} start
  16373. * @param {Array} end
  16374. * @returns {Number} scale
  16375. */
  16376. getScale: function getScale(start, end) {
  16377. // need two fingers...
  16378. if(start.length >= 2 && end.length >= 2) {
  16379. return this.getDistance(end[0], end[1]) /
  16380. this.getDistance(start[0], start[1]);
  16381. }
  16382. return 1;
  16383. },
  16384. /**
  16385. * calculate the rotation degrees between two touchLists (fingers)
  16386. * @param {Array} start
  16387. * @param {Array} end
  16388. * @returns {Number} rotation
  16389. */
  16390. getRotation: function getRotation(start, end) {
  16391. // need two fingers
  16392. if(start.length >= 2 && end.length >= 2) {
  16393. return this.getAngle(end[1], end[0]) -
  16394. this.getAngle(start[1], start[0]);
  16395. }
  16396. return 0;
  16397. },
  16398. /**
  16399. * boolean if the direction is vertical
  16400. * @param {String} direction
  16401. * @returns {Boolean} is_vertical
  16402. */
  16403. isVertical: function isVertical(direction) {
  16404. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16405. },
  16406. /**
  16407. * stop browser default behavior with css props
  16408. * @param {HtmlElement} element
  16409. * @param {Object} css_props
  16410. */
  16411. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16412. var prop,
  16413. vendors = ['webkit','khtml','moz','ms','o',''];
  16414. if(!css_props || !element.style) {
  16415. return;
  16416. }
  16417. // with css properties for modern browsers
  16418. for(var i = 0; i < vendors.length; i++) {
  16419. for(var p in css_props) {
  16420. if(css_props.hasOwnProperty(p)) {
  16421. prop = p;
  16422. // vender prefix at the property
  16423. if(vendors[i]) {
  16424. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16425. }
  16426. // set the style
  16427. element.style[prop] = css_props[p];
  16428. }
  16429. }
  16430. }
  16431. // also the disable onselectstart
  16432. if(css_props.userSelect == 'none') {
  16433. element.onselectstart = function() {
  16434. return false;
  16435. };
  16436. }
  16437. }
  16438. };
  16439. Hammer.detection = {
  16440. // contains all registred Hammer.gestures in the correct order
  16441. gestures: [],
  16442. // data of the current Hammer.gesture detection session
  16443. current: null,
  16444. // the previous Hammer.gesture session data
  16445. // is a full clone of the previous gesture.current object
  16446. previous: null,
  16447. // when this becomes true, no gestures are fired
  16448. stopped: false,
  16449. /**
  16450. * start Hammer.gesture detection
  16451. * @param {Hammer.Instance} inst
  16452. * @param {Object} eventData
  16453. */
  16454. startDetect: function startDetect(inst, eventData) {
  16455. // already busy with a Hammer.gesture detection on an element
  16456. if(this.current) {
  16457. return;
  16458. }
  16459. this.stopped = false;
  16460. this.current = {
  16461. inst : inst, // reference to HammerInstance we're working for
  16462. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16463. lastEvent : false, // last eventData
  16464. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16465. };
  16466. this.detect(eventData);
  16467. },
  16468. /**
  16469. * Hammer.gesture detection
  16470. * @param {Object} eventData
  16471. * @param {Object} eventData
  16472. */
  16473. detect: function detect(eventData) {
  16474. if(!this.current || this.stopped) {
  16475. return;
  16476. }
  16477. // extend event data with calculations about scale, distance etc
  16478. eventData = this.extendEventData(eventData);
  16479. // instance options
  16480. var inst_options = this.current.inst.options;
  16481. // call Hammer.gesture handlers
  16482. for(var g=0,len=this.gestures.length; g<len; g++) {
  16483. var gesture = this.gestures[g];
  16484. // only when the instance options have enabled this gesture
  16485. if(!this.stopped && inst_options[gesture.name] !== false) {
  16486. // if a handler returns false, we stop with the detection
  16487. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16488. this.stopDetect();
  16489. break;
  16490. }
  16491. }
  16492. }
  16493. // store as previous event event
  16494. if(this.current) {
  16495. this.current.lastEvent = eventData;
  16496. }
  16497. // endevent, but not the last touch, so dont stop
  16498. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16499. this.stopDetect();
  16500. }
  16501. return eventData;
  16502. },
  16503. /**
  16504. * clear the Hammer.gesture vars
  16505. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16506. * to stop other Hammer.gestures from being fired
  16507. */
  16508. stopDetect: function stopDetect() {
  16509. // clone current data to the store as the previous gesture
  16510. // used for the double tap gesture, since this is an other gesture detect session
  16511. this.previous = Hammer.utils.extend({}, this.current);
  16512. // reset the current
  16513. this.current = null;
  16514. // stopped!
  16515. this.stopped = true;
  16516. },
  16517. /**
  16518. * extend eventData for Hammer.gestures
  16519. * @param {Object} ev
  16520. * @returns {Object} ev
  16521. */
  16522. extendEventData: function extendEventData(ev) {
  16523. var startEv = this.current.startEvent;
  16524. // if the touches change, set the new touches over the startEvent touches
  16525. // this because touchevents don't have all the touches on touchstart, or the
  16526. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16527. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16528. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16529. // extend 1 level deep to get the touchlist with the touch objects
  16530. startEv.touches = [];
  16531. for(var i=0,len=ev.touches.length; i<len; i++) {
  16532. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16533. }
  16534. }
  16535. var delta_time = ev.timeStamp - startEv.timeStamp,
  16536. delta_x = ev.center.pageX - startEv.center.pageX,
  16537. delta_y = ev.center.pageY - startEv.center.pageY,
  16538. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16539. Hammer.utils.extend(ev, {
  16540. deltaTime : delta_time,
  16541. deltaX : delta_x,
  16542. deltaY : delta_y,
  16543. velocityX : velocity.x,
  16544. velocityY : velocity.y,
  16545. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16546. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16547. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16548. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16549. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16550. startEvent : startEv
  16551. });
  16552. return ev;
  16553. },
  16554. /**
  16555. * register new gesture
  16556. * @param {Object} gesture object, see gestures.js for documentation
  16557. * @returns {Array} gestures
  16558. */
  16559. register: function register(gesture) {
  16560. // add an enable gesture options if there is no given
  16561. var options = gesture.defaults || {};
  16562. if(options[gesture.name] === undefined) {
  16563. options[gesture.name] = true;
  16564. }
  16565. // extend Hammer default options with the Hammer.gesture options
  16566. Hammer.utils.extend(Hammer.defaults, options, true);
  16567. // set its index
  16568. gesture.index = gesture.index || 1000;
  16569. // add Hammer.gesture to the list
  16570. this.gestures.push(gesture);
  16571. // sort the list by index
  16572. this.gestures.sort(function(a, b) {
  16573. if (a.index < b.index) {
  16574. return -1;
  16575. }
  16576. if (a.index > b.index) {
  16577. return 1;
  16578. }
  16579. return 0;
  16580. });
  16581. return this.gestures;
  16582. }
  16583. };
  16584. Hammer.gestures = Hammer.gestures || {};
  16585. /**
  16586. * Custom gestures
  16587. * ==============================
  16588. *
  16589. * Gesture object
  16590. * --------------------
  16591. * The object structure of a gesture:
  16592. *
  16593. * { name: 'mygesture',
  16594. * index: 1337,
  16595. * defaults: {
  16596. * mygesture_option: true
  16597. * }
  16598. * handler: function(type, ev, inst) {
  16599. * // trigger gesture event
  16600. * inst.trigger(this.name, ev);
  16601. * }
  16602. * }
  16603. * @param {String} name
  16604. * this should be the name of the gesture, lowercase
  16605. * it is also being used to disable/enable the gesture per instance config.
  16606. *
  16607. * @param {Number} [index=1000]
  16608. * the index of the gesture, where it is going to be in the stack of gestures detection
  16609. * like when you build an gesture that depends on the drag gesture, it is a good
  16610. * idea to place it after the index of the drag gesture.
  16611. *
  16612. * @param {Object} [defaults={}]
  16613. * the default settings of the gesture. these are added to the instance settings,
  16614. * and can be overruled per instance. you can also add the name of the gesture,
  16615. * but this is also added by default (and set to true).
  16616. *
  16617. * @param {Function} handler
  16618. * this handles the gesture detection of your custom gesture and receives the
  16619. * following arguments:
  16620. *
  16621. * @param {Object} eventData
  16622. * event data containing the following properties:
  16623. * timeStamp {Number} time the event occurred
  16624. * target {HTMLElement} target element
  16625. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16626. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16627. * center {Object} center position of the touches. contains pageX and pageY
  16628. * deltaTime {Number} the total time of the touches in the screen
  16629. * deltaX {Number} the delta on x axis we haved moved
  16630. * deltaY {Number} the delta on y axis we haved moved
  16631. * velocityX {Number} the velocity on the x
  16632. * velocityY {Number} the velocity on y
  16633. * angle {Number} the angle we are moving
  16634. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16635. * distance {Number} the distance we haved moved
  16636. * scale {Number} scaling of the touches, needs 2 touches
  16637. * rotation {Number} rotation of the touches, needs 2 touches *
  16638. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16639. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16640. * startEvent {Object} contains the same properties as above,
  16641. * but from the first touch. this is used to calculate
  16642. * distances, deltaTime, scaling etc
  16643. *
  16644. * @param {Hammer.Instance} inst
  16645. * the instance we are doing the detection for. you can get the options from
  16646. * the inst.options object and trigger the gesture event by calling inst.trigger
  16647. *
  16648. *
  16649. * Handle gestures
  16650. * --------------------
  16651. * inside the handler you can get/set Hammer.detection.current. This is the current
  16652. * detection session. It has the following properties
  16653. * @param {String} name
  16654. * contains the name of the gesture we have detected. it has not a real function,
  16655. * only to check in other gestures if something is detected.
  16656. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16657. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16658. *
  16659. * @readonly
  16660. * @param {Hammer.Instance} inst
  16661. * the instance we do the detection for
  16662. *
  16663. * @readonly
  16664. * @param {Object} startEvent
  16665. * contains the properties of the first gesture detection in this session.
  16666. * Used for calculations about timing, distance, etc.
  16667. *
  16668. * @readonly
  16669. * @param {Object} lastEvent
  16670. * contains all the properties of the last gesture detect in this session.
  16671. *
  16672. * after the gesture detection session has been completed (user has released the screen)
  16673. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16674. * this is usefull for gestures like doubletap, where you need to know if the
  16675. * previous gesture was a tap
  16676. *
  16677. * options that have been set by the instance can be received by calling inst.options
  16678. *
  16679. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16680. * The first param is the name of your gesture, the second the event argument
  16681. *
  16682. *
  16683. * Register gestures
  16684. * --------------------
  16685. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16686. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16687. * manually and pass your gesture object as a param
  16688. *
  16689. */
  16690. /**
  16691. * Hold
  16692. * Touch stays at the same place for x time
  16693. * @events hold
  16694. */
  16695. Hammer.gestures.Hold = {
  16696. name: 'hold',
  16697. index: 10,
  16698. defaults: {
  16699. hold_timeout : 500,
  16700. hold_threshold : 1
  16701. },
  16702. timer: null,
  16703. handler: function holdGesture(ev, inst) {
  16704. switch(ev.eventType) {
  16705. case Hammer.EVENT_START:
  16706. // clear any running timers
  16707. clearTimeout(this.timer);
  16708. // set the gesture so we can check in the timeout if it still is
  16709. Hammer.detection.current.name = this.name;
  16710. // set timer and if after the timeout it still is hold,
  16711. // we trigger the hold event
  16712. this.timer = setTimeout(function() {
  16713. if(Hammer.detection.current.name == 'hold') {
  16714. inst.trigger('hold', ev);
  16715. }
  16716. }, inst.options.hold_timeout);
  16717. break;
  16718. // when you move or end we clear the timer
  16719. case Hammer.EVENT_MOVE:
  16720. if(ev.distance > inst.options.hold_threshold) {
  16721. clearTimeout(this.timer);
  16722. }
  16723. break;
  16724. case Hammer.EVENT_END:
  16725. clearTimeout(this.timer);
  16726. break;
  16727. }
  16728. }
  16729. };
  16730. /**
  16731. * Tap/DoubleTap
  16732. * Quick touch at a place or double at the same place
  16733. * @events tap, doubletap
  16734. */
  16735. Hammer.gestures.Tap = {
  16736. name: 'tap',
  16737. index: 100,
  16738. defaults: {
  16739. tap_max_touchtime : 250,
  16740. tap_max_distance : 10,
  16741. tap_always : true,
  16742. doubletap_distance : 20,
  16743. doubletap_interval : 300
  16744. },
  16745. handler: function tapGesture(ev, inst) {
  16746. if(ev.eventType == Hammer.EVENT_END) {
  16747. // previous gesture, for the double tap since these are two different gesture detections
  16748. var prev = Hammer.detection.previous,
  16749. did_doubletap = false;
  16750. // when the touchtime is higher then the max touch time
  16751. // or when the moving distance is too much
  16752. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16753. ev.distance > inst.options.tap_max_distance) {
  16754. return;
  16755. }
  16756. // check if double tap
  16757. if(prev && prev.name == 'tap' &&
  16758. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16759. ev.distance < inst.options.doubletap_distance) {
  16760. inst.trigger('doubletap', ev);
  16761. did_doubletap = true;
  16762. }
  16763. // do a single tap
  16764. if(!did_doubletap || inst.options.tap_always) {
  16765. Hammer.detection.current.name = 'tap';
  16766. inst.trigger(Hammer.detection.current.name, ev);
  16767. }
  16768. }
  16769. }
  16770. };
  16771. /**
  16772. * Swipe
  16773. * triggers swipe events when the end velocity is above the threshold
  16774. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16775. */
  16776. Hammer.gestures.Swipe = {
  16777. name: 'swipe',
  16778. index: 40,
  16779. defaults: {
  16780. // set 0 for unlimited, but this can conflict with transform
  16781. swipe_max_touches : 1,
  16782. swipe_velocity : 0.7
  16783. },
  16784. handler: function swipeGesture(ev, inst) {
  16785. if(ev.eventType == Hammer.EVENT_END) {
  16786. // max touches
  16787. if(inst.options.swipe_max_touches > 0 &&
  16788. ev.touches.length > inst.options.swipe_max_touches) {
  16789. return;
  16790. }
  16791. // when the distance we moved is too small we skip this gesture
  16792. // or we can be already in dragging
  16793. if(ev.velocityX > inst.options.swipe_velocity ||
  16794. ev.velocityY > inst.options.swipe_velocity) {
  16795. // trigger swipe events
  16796. inst.trigger(this.name, ev);
  16797. inst.trigger(this.name + ev.direction, ev);
  16798. }
  16799. }
  16800. }
  16801. };
  16802. /**
  16803. * Drag
  16804. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16805. * moving left and right is a good practice. When all the drag events are blocking
  16806. * you disable scrolling on that area.
  16807. * @events drag, drapleft, dragright, dragup, dragdown
  16808. */
  16809. Hammer.gestures.Drag = {
  16810. name: 'drag',
  16811. index: 50,
  16812. defaults: {
  16813. drag_min_distance : 10,
  16814. // set 0 for unlimited, but this can conflict with transform
  16815. drag_max_touches : 1,
  16816. // prevent default browser behavior when dragging occurs
  16817. // be careful with it, it makes the element a blocking element
  16818. // when you are using the drag gesture, it is a good practice to set this true
  16819. drag_block_horizontal : false,
  16820. drag_block_vertical : false,
  16821. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16822. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16823. drag_lock_to_axis : false,
  16824. // drag lock only kicks in when distance > drag_lock_min_distance
  16825. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16826. drag_lock_min_distance : 25
  16827. },
  16828. triggered: false,
  16829. handler: function dragGesture(ev, inst) {
  16830. // current gesture isnt drag, but dragged is true
  16831. // this means an other gesture is busy. now call dragend
  16832. if(Hammer.detection.current.name != this.name && this.triggered) {
  16833. inst.trigger(this.name +'end', ev);
  16834. this.triggered = false;
  16835. return;
  16836. }
  16837. // max touches
  16838. if(inst.options.drag_max_touches > 0 &&
  16839. ev.touches.length > inst.options.drag_max_touches) {
  16840. return;
  16841. }
  16842. switch(ev.eventType) {
  16843. case Hammer.EVENT_START:
  16844. this.triggered = false;
  16845. break;
  16846. case Hammer.EVENT_MOVE:
  16847. // when the distance we moved is too small we skip this gesture
  16848. // or we can be already in dragging
  16849. if(ev.distance < inst.options.drag_min_distance &&
  16850. Hammer.detection.current.name != this.name) {
  16851. return;
  16852. }
  16853. // we are dragging!
  16854. Hammer.detection.current.name = this.name;
  16855. // lock drag to axis?
  16856. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16857. ev.drag_locked_to_axis = true;
  16858. }
  16859. var last_direction = Hammer.detection.current.lastEvent.direction;
  16860. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16861. // keep direction on the axis that the drag gesture started on
  16862. if(Hammer.utils.isVertical(last_direction)) {
  16863. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16864. }
  16865. else {
  16866. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16867. }
  16868. }
  16869. // first time, trigger dragstart event
  16870. if(!this.triggered) {
  16871. inst.trigger(this.name +'start', ev);
  16872. this.triggered = true;
  16873. }
  16874. // trigger normal event
  16875. inst.trigger(this.name, ev);
  16876. // direction event, like dragdown
  16877. inst.trigger(this.name + ev.direction, ev);
  16878. // block the browser events
  16879. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16880. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16881. ev.preventDefault();
  16882. }
  16883. break;
  16884. case Hammer.EVENT_END:
  16885. // trigger dragend
  16886. if(this.triggered) {
  16887. inst.trigger(this.name +'end', ev);
  16888. }
  16889. this.triggered = false;
  16890. break;
  16891. }
  16892. }
  16893. };
  16894. /**
  16895. * Transform
  16896. * User want to scale or rotate with 2 fingers
  16897. * @events transform, pinch, pinchin, pinchout, rotate
  16898. */
  16899. Hammer.gestures.Transform = {
  16900. name: 'transform',
  16901. index: 45,
  16902. defaults: {
  16903. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16904. transform_min_scale : 0.01,
  16905. // rotation in degrees
  16906. transform_min_rotation : 1,
  16907. // prevent default browser behavior when two touches are on the screen
  16908. // but it makes the element a blocking element
  16909. // when you are using the transform gesture, it is a good practice to set this true
  16910. transform_always_block : false
  16911. },
  16912. triggered: false,
  16913. handler: function transformGesture(ev, inst) {
  16914. // current gesture isnt drag, but dragged is true
  16915. // this means an other gesture is busy. now call dragend
  16916. if(Hammer.detection.current.name != this.name && this.triggered) {
  16917. inst.trigger(this.name +'end', ev);
  16918. this.triggered = false;
  16919. return;
  16920. }
  16921. // atleast multitouch
  16922. if(ev.touches.length < 2) {
  16923. return;
  16924. }
  16925. // prevent default when two fingers are on the screen
  16926. if(inst.options.transform_always_block) {
  16927. ev.preventDefault();
  16928. }
  16929. switch(ev.eventType) {
  16930. case Hammer.EVENT_START:
  16931. this.triggered = false;
  16932. break;
  16933. case Hammer.EVENT_MOVE:
  16934. var scale_threshold = Math.abs(1-ev.scale);
  16935. var rotation_threshold = Math.abs(ev.rotation);
  16936. // when the distance we moved is too small we skip this gesture
  16937. // or we can be already in dragging
  16938. if(scale_threshold < inst.options.transform_min_scale &&
  16939. rotation_threshold < inst.options.transform_min_rotation) {
  16940. return;
  16941. }
  16942. // we are transforming!
  16943. Hammer.detection.current.name = this.name;
  16944. // first time, trigger dragstart event
  16945. if(!this.triggered) {
  16946. inst.trigger(this.name +'start', ev);
  16947. this.triggered = true;
  16948. }
  16949. inst.trigger(this.name, ev); // basic transform event
  16950. // trigger rotate event
  16951. if(rotation_threshold > inst.options.transform_min_rotation) {
  16952. inst.trigger('rotate', ev);
  16953. }
  16954. // trigger pinch event
  16955. if(scale_threshold > inst.options.transform_min_scale) {
  16956. inst.trigger('pinch', ev);
  16957. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16958. }
  16959. break;
  16960. case Hammer.EVENT_END:
  16961. // trigger dragend
  16962. if(this.triggered) {
  16963. inst.trigger(this.name +'end', ev);
  16964. }
  16965. this.triggered = false;
  16966. break;
  16967. }
  16968. }
  16969. };
  16970. /**
  16971. * Touch
  16972. * Called as first, tells the user has touched the screen
  16973. * @events touch
  16974. */
  16975. Hammer.gestures.Touch = {
  16976. name: 'touch',
  16977. index: -Infinity,
  16978. defaults: {
  16979. // call preventDefault at touchstart, and makes the element blocking by
  16980. // disabling the scrolling of the page, but it improves gestures like
  16981. // transforming and dragging.
  16982. // be careful with using this, it can be very annoying for users to be stuck
  16983. // on the page
  16984. prevent_default: false,
  16985. // disable mouse events, so only touch (or pen!) input triggers events
  16986. prevent_mouseevents: false
  16987. },
  16988. handler: function touchGesture(ev, inst) {
  16989. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16990. ev.stopDetect();
  16991. return;
  16992. }
  16993. if(inst.options.prevent_default) {
  16994. ev.preventDefault();
  16995. }
  16996. if(ev.eventType == Hammer.EVENT_START) {
  16997. inst.trigger(this.name, ev);
  16998. }
  16999. }
  17000. };
  17001. /**
  17002. * Release
  17003. * Called as last, tells the user has released the screen
  17004. * @events release
  17005. */
  17006. Hammer.gestures.Release = {
  17007. name: 'release',
  17008. index: Infinity,
  17009. handler: function releaseGesture(ev, inst) {
  17010. if(ev.eventType == Hammer.EVENT_END) {
  17011. inst.trigger(this.name, ev);
  17012. }
  17013. }
  17014. };
  17015. // node export
  17016. if(typeof module === 'object' && typeof module.exports === 'object'){
  17017. module.exports = Hammer;
  17018. }
  17019. // just window export
  17020. else {
  17021. window.Hammer = Hammer;
  17022. // requireJS module definition
  17023. if(typeof window.define === 'function' && window.define.amd) {
  17024. window.define('hammer', [], function() {
  17025. return Hammer;
  17026. });
  17027. }
  17028. }
  17029. })(this);
  17030. },{}],4:[function(require,module,exports){
  17031. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  17032. //! version : 2.6.0
  17033. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17034. //! license : MIT
  17035. //! momentjs.com
  17036. (function (undefined) {
  17037. /************************************
  17038. Constants
  17039. ************************************/
  17040. var moment,
  17041. VERSION = "2.6.0",
  17042. // the global-scope this is NOT the global object in Node.js
  17043. globalScope = typeof global !== 'undefined' ? global : this,
  17044. oldGlobalMoment,
  17045. round = Math.round,
  17046. i,
  17047. YEAR = 0,
  17048. MONTH = 1,
  17049. DATE = 2,
  17050. HOUR = 3,
  17051. MINUTE = 4,
  17052. SECOND = 5,
  17053. MILLISECOND = 6,
  17054. // internal storage for language config files
  17055. languages = {},
  17056. // moment internal properties
  17057. momentProperties = {
  17058. _isAMomentObject: null,
  17059. _i : null,
  17060. _f : null,
  17061. _l : null,
  17062. _strict : null,
  17063. _isUTC : null,
  17064. _offset : null, // optional. Combine with _isUTC
  17065. _pf : null,
  17066. _lang : null // optional
  17067. },
  17068. // check for nodeJS
  17069. hasModule = (typeof module !== 'undefined' && module.exports),
  17070. // ASP.NET json date format regex
  17071. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17072. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17073. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17074. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17075. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17076. // format tokens
  17077. 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,
  17078. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17079. // parsing token regexes
  17080. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17081. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17082. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17083. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17084. parseTokenDigits = /\d+/, // nonzero number of digits
  17085. 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.
  17086. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17087. parseTokenT = /T/i, // T (ISO separator)
  17088. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17089. parseTokenOrdinal = /\d{1,2}/,
  17090. //strict parsing regexes
  17091. parseTokenOneDigit = /\d/, // 0 - 9
  17092. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17093. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17094. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17095. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17096. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17097. // iso 8601 regex
  17098. // 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)
  17099. 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)?)?$/,
  17100. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17101. isoDates = [
  17102. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17103. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17104. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17105. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17106. ['YYYY-DDD', /\d{4}-\d{3}/]
  17107. ],
  17108. // iso time formats and regexes
  17109. isoTimes = [
  17110. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  17111. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17112. ['HH:mm', /(T| )\d\d:\d\d/],
  17113. ['HH', /(T| )\d\d/]
  17114. ],
  17115. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17116. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17117. // getter and setter names
  17118. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17119. unitMillisecondFactors = {
  17120. 'Milliseconds' : 1,
  17121. 'Seconds' : 1e3,
  17122. 'Minutes' : 6e4,
  17123. 'Hours' : 36e5,
  17124. 'Days' : 864e5,
  17125. 'Months' : 2592e6,
  17126. 'Years' : 31536e6
  17127. },
  17128. unitAliases = {
  17129. ms : 'millisecond',
  17130. s : 'second',
  17131. m : 'minute',
  17132. h : 'hour',
  17133. d : 'day',
  17134. D : 'date',
  17135. w : 'week',
  17136. W : 'isoWeek',
  17137. M : 'month',
  17138. Q : 'quarter',
  17139. y : 'year',
  17140. DDD : 'dayOfYear',
  17141. e : 'weekday',
  17142. E : 'isoWeekday',
  17143. gg: 'weekYear',
  17144. GG: 'isoWeekYear'
  17145. },
  17146. camelFunctions = {
  17147. dayofyear : 'dayOfYear',
  17148. isoweekday : 'isoWeekday',
  17149. isoweek : 'isoWeek',
  17150. weekyear : 'weekYear',
  17151. isoweekyear : 'isoWeekYear'
  17152. },
  17153. // format function strings
  17154. formatFunctions = {},
  17155. // tokens to ordinalize and pad
  17156. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17157. paddedTokens = 'M D H h m s w W'.split(' '),
  17158. formatTokenFunctions = {
  17159. M : function () {
  17160. return this.month() + 1;
  17161. },
  17162. MMM : function (format) {
  17163. return this.lang().monthsShort(this, format);
  17164. },
  17165. MMMM : function (format) {
  17166. return this.lang().months(this, format);
  17167. },
  17168. D : function () {
  17169. return this.date();
  17170. },
  17171. DDD : function () {
  17172. return this.dayOfYear();
  17173. },
  17174. d : function () {
  17175. return this.day();
  17176. },
  17177. dd : function (format) {
  17178. return this.lang().weekdaysMin(this, format);
  17179. },
  17180. ddd : function (format) {
  17181. return this.lang().weekdaysShort(this, format);
  17182. },
  17183. dddd : function (format) {
  17184. return this.lang().weekdays(this, format);
  17185. },
  17186. w : function () {
  17187. return this.week();
  17188. },
  17189. W : function () {
  17190. return this.isoWeek();
  17191. },
  17192. YY : function () {
  17193. return leftZeroFill(this.year() % 100, 2);
  17194. },
  17195. YYYY : function () {
  17196. return leftZeroFill(this.year(), 4);
  17197. },
  17198. YYYYY : function () {
  17199. return leftZeroFill(this.year(), 5);
  17200. },
  17201. YYYYYY : function () {
  17202. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17203. return sign + leftZeroFill(Math.abs(y), 6);
  17204. },
  17205. gg : function () {
  17206. return leftZeroFill(this.weekYear() % 100, 2);
  17207. },
  17208. gggg : function () {
  17209. return leftZeroFill(this.weekYear(), 4);
  17210. },
  17211. ggggg : function () {
  17212. return leftZeroFill(this.weekYear(), 5);
  17213. },
  17214. GG : function () {
  17215. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17216. },
  17217. GGGG : function () {
  17218. return leftZeroFill(this.isoWeekYear(), 4);
  17219. },
  17220. GGGGG : function () {
  17221. return leftZeroFill(this.isoWeekYear(), 5);
  17222. },
  17223. e : function () {
  17224. return this.weekday();
  17225. },
  17226. E : function () {
  17227. return this.isoWeekday();
  17228. },
  17229. a : function () {
  17230. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17231. },
  17232. A : function () {
  17233. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17234. },
  17235. H : function () {
  17236. return this.hours();
  17237. },
  17238. h : function () {
  17239. return this.hours() % 12 || 12;
  17240. },
  17241. m : function () {
  17242. return this.minutes();
  17243. },
  17244. s : function () {
  17245. return this.seconds();
  17246. },
  17247. S : function () {
  17248. return toInt(this.milliseconds() / 100);
  17249. },
  17250. SS : function () {
  17251. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17252. },
  17253. SSS : function () {
  17254. return leftZeroFill(this.milliseconds(), 3);
  17255. },
  17256. SSSS : function () {
  17257. return leftZeroFill(this.milliseconds(), 3);
  17258. },
  17259. Z : function () {
  17260. var a = -this.zone(),
  17261. b = "+";
  17262. if (a < 0) {
  17263. a = -a;
  17264. b = "-";
  17265. }
  17266. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17267. },
  17268. ZZ : function () {
  17269. var a = -this.zone(),
  17270. b = "+";
  17271. if (a < 0) {
  17272. a = -a;
  17273. b = "-";
  17274. }
  17275. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17276. },
  17277. z : function () {
  17278. return this.zoneAbbr();
  17279. },
  17280. zz : function () {
  17281. return this.zoneName();
  17282. },
  17283. X : function () {
  17284. return this.unix();
  17285. },
  17286. Q : function () {
  17287. return this.quarter();
  17288. }
  17289. },
  17290. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17291. function defaultParsingFlags() {
  17292. // We need to deep clone this object, and es5 standard is not very
  17293. // helpful.
  17294. return {
  17295. empty : false,
  17296. unusedTokens : [],
  17297. unusedInput : [],
  17298. overflow : -2,
  17299. charsLeftOver : 0,
  17300. nullInput : false,
  17301. invalidMonth : null,
  17302. invalidFormat : false,
  17303. userInvalidated : false,
  17304. iso: false
  17305. };
  17306. }
  17307. function deprecate(msg, fn) {
  17308. var firstTime = true;
  17309. function printMsg() {
  17310. if (moment.suppressDeprecationWarnings === false &&
  17311. typeof console !== 'undefined' && console.warn) {
  17312. console.warn("Deprecation warning: " + msg);
  17313. }
  17314. }
  17315. return extend(function () {
  17316. if (firstTime) {
  17317. printMsg();
  17318. firstTime = false;
  17319. }
  17320. return fn.apply(this, arguments);
  17321. }, fn);
  17322. }
  17323. function padToken(func, count) {
  17324. return function (a) {
  17325. return leftZeroFill(func.call(this, a), count);
  17326. };
  17327. }
  17328. function ordinalizeToken(func, period) {
  17329. return function (a) {
  17330. return this.lang().ordinal(func.call(this, a), period);
  17331. };
  17332. }
  17333. while (ordinalizeTokens.length) {
  17334. i = ordinalizeTokens.pop();
  17335. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17336. }
  17337. while (paddedTokens.length) {
  17338. i = paddedTokens.pop();
  17339. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17340. }
  17341. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17342. /************************************
  17343. Constructors
  17344. ************************************/
  17345. function Language() {
  17346. }
  17347. // Moment prototype object
  17348. function Moment(config) {
  17349. checkOverflow(config);
  17350. extend(this, config);
  17351. }
  17352. // Duration Constructor
  17353. function Duration(duration) {
  17354. var normalizedInput = normalizeObjectUnits(duration),
  17355. years = normalizedInput.year || 0,
  17356. quarters = normalizedInput.quarter || 0,
  17357. months = normalizedInput.month || 0,
  17358. weeks = normalizedInput.week || 0,
  17359. days = normalizedInput.day || 0,
  17360. hours = normalizedInput.hour || 0,
  17361. minutes = normalizedInput.minute || 0,
  17362. seconds = normalizedInput.second || 0,
  17363. milliseconds = normalizedInput.millisecond || 0;
  17364. // representation for dateAddRemove
  17365. this._milliseconds = +milliseconds +
  17366. seconds * 1e3 + // 1000
  17367. minutes * 6e4 + // 1000 * 60
  17368. hours * 36e5; // 1000 * 60 * 60
  17369. // Because of dateAddRemove treats 24 hours as different from a
  17370. // day when working around DST, we need to store them separately
  17371. this._days = +days +
  17372. weeks * 7;
  17373. // It is impossible translate months into days without knowing
  17374. // which months you are are talking about, so we have to store
  17375. // it separately.
  17376. this._months = +months +
  17377. quarters * 3 +
  17378. years * 12;
  17379. this._data = {};
  17380. this._bubble();
  17381. }
  17382. /************************************
  17383. Helpers
  17384. ************************************/
  17385. function extend(a, b) {
  17386. for (var i in b) {
  17387. if (b.hasOwnProperty(i)) {
  17388. a[i] = b[i];
  17389. }
  17390. }
  17391. if (b.hasOwnProperty("toString")) {
  17392. a.toString = b.toString;
  17393. }
  17394. if (b.hasOwnProperty("valueOf")) {
  17395. a.valueOf = b.valueOf;
  17396. }
  17397. return a;
  17398. }
  17399. function cloneMoment(m) {
  17400. var result = {}, i;
  17401. for (i in m) {
  17402. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17403. result[i] = m[i];
  17404. }
  17405. }
  17406. return result;
  17407. }
  17408. function absRound(number) {
  17409. if (number < 0) {
  17410. return Math.ceil(number);
  17411. } else {
  17412. return Math.floor(number);
  17413. }
  17414. }
  17415. // left zero fill a number
  17416. // see http://jsperf.com/left-zero-filling for performance comparison
  17417. function leftZeroFill(number, targetLength, forceSign) {
  17418. var output = '' + Math.abs(number),
  17419. sign = number >= 0;
  17420. while (output.length < targetLength) {
  17421. output = '0' + output;
  17422. }
  17423. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17424. }
  17425. // helper function for _.addTime and _.subtractTime
  17426. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17427. var milliseconds = duration._milliseconds,
  17428. days = duration._days,
  17429. months = duration._months;
  17430. updateOffset = updateOffset == null ? true : updateOffset;
  17431. if (milliseconds) {
  17432. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17433. }
  17434. if (days) {
  17435. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17436. }
  17437. if (months) {
  17438. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17439. }
  17440. if (updateOffset) {
  17441. moment.updateOffset(mom, days || months);
  17442. }
  17443. }
  17444. // check if is an array
  17445. function isArray(input) {
  17446. return Object.prototype.toString.call(input) === '[object Array]';
  17447. }
  17448. function isDate(input) {
  17449. return Object.prototype.toString.call(input) === '[object Date]' ||
  17450. input instanceof Date;
  17451. }
  17452. // compare two arrays, return the number of differences
  17453. function compareArrays(array1, array2, dontConvert) {
  17454. var len = Math.min(array1.length, array2.length),
  17455. lengthDiff = Math.abs(array1.length - array2.length),
  17456. diffs = 0,
  17457. i;
  17458. for (i = 0; i < len; i++) {
  17459. if ((dontConvert && array1[i] !== array2[i]) ||
  17460. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17461. diffs++;
  17462. }
  17463. }
  17464. return diffs + lengthDiff;
  17465. }
  17466. function normalizeUnits(units) {
  17467. if (units) {
  17468. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17469. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17470. }
  17471. return units;
  17472. }
  17473. function normalizeObjectUnits(inputObject) {
  17474. var normalizedInput = {},
  17475. normalizedProp,
  17476. prop;
  17477. for (prop in inputObject) {
  17478. if (inputObject.hasOwnProperty(prop)) {
  17479. normalizedProp = normalizeUnits(prop);
  17480. if (normalizedProp) {
  17481. normalizedInput[normalizedProp] = inputObject[prop];
  17482. }
  17483. }
  17484. }
  17485. return normalizedInput;
  17486. }
  17487. function makeList(field) {
  17488. var count, setter;
  17489. if (field.indexOf('week') === 0) {
  17490. count = 7;
  17491. setter = 'day';
  17492. }
  17493. else if (field.indexOf('month') === 0) {
  17494. count = 12;
  17495. setter = 'month';
  17496. }
  17497. else {
  17498. return;
  17499. }
  17500. moment[field] = function (format, index) {
  17501. var i, getter,
  17502. method = moment.fn._lang[field],
  17503. results = [];
  17504. if (typeof format === 'number') {
  17505. index = format;
  17506. format = undefined;
  17507. }
  17508. getter = function (i) {
  17509. var m = moment().utc().set(setter, i);
  17510. return method.call(moment.fn._lang, m, format || '');
  17511. };
  17512. if (index != null) {
  17513. return getter(index);
  17514. }
  17515. else {
  17516. for (i = 0; i < count; i++) {
  17517. results.push(getter(i));
  17518. }
  17519. return results;
  17520. }
  17521. };
  17522. }
  17523. function toInt(argumentForCoercion) {
  17524. var coercedNumber = +argumentForCoercion,
  17525. value = 0;
  17526. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17527. if (coercedNumber >= 0) {
  17528. value = Math.floor(coercedNumber);
  17529. } else {
  17530. value = Math.ceil(coercedNumber);
  17531. }
  17532. }
  17533. return value;
  17534. }
  17535. function daysInMonth(year, month) {
  17536. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17537. }
  17538. function weeksInYear(year, dow, doy) {
  17539. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17540. }
  17541. function daysInYear(year) {
  17542. return isLeapYear(year) ? 366 : 365;
  17543. }
  17544. function isLeapYear(year) {
  17545. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17546. }
  17547. function checkOverflow(m) {
  17548. var overflow;
  17549. if (m._a && m._pf.overflow === -2) {
  17550. overflow =
  17551. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17552. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17553. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17554. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17555. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17556. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17557. -1;
  17558. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17559. overflow = DATE;
  17560. }
  17561. m._pf.overflow = overflow;
  17562. }
  17563. }
  17564. function isValid(m) {
  17565. if (m._isValid == null) {
  17566. m._isValid = !isNaN(m._d.getTime()) &&
  17567. m._pf.overflow < 0 &&
  17568. !m._pf.empty &&
  17569. !m._pf.invalidMonth &&
  17570. !m._pf.nullInput &&
  17571. !m._pf.invalidFormat &&
  17572. !m._pf.userInvalidated;
  17573. if (m._strict) {
  17574. m._isValid = m._isValid &&
  17575. m._pf.charsLeftOver === 0 &&
  17576. m._pf.unusedTokens.length === 0;
  17577. }
  17578. }
  17579. return m._isValid;
  17580. }
  17581. function normalizeLanguage(key) {
  17582. return key ? key.toLowerCase().replace('_', '-') : key;
  17583. }
  17584. // Return a moment from input, that is local/utc/zone equivalent to model.
  17585. function makeAs(input, model) {
  17586. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17587. moment(input).local();
  17588. }
  17589. /************************************
  17590. Languages
  17591. ************************************/
  17592. extend(Language.prototype, {
  17593. set : function (config) {
  17594. var prop, i;
  17595. for (i in config) {
  17596. prop = config[i];
  17597. if (typeof prop === 'function') {
  17598. this[i] = prop;
  17599. } else {
  17600. this['_' + i] = prop;
  17601. }
  17602. }
  17603. },
  17604. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17605. months : function (m) {
  17606. return this._months[m.month()];
  17607. },
  17608. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17609. monthsShort : function (m) {
  17610. return this._monthsShort[m.month()];
  17611. },
  17612. monthsParse : function (monthName) {
  17613. var i, mom, regex;
  17614. if (!this._monthsParse) {
  17615. this._monthsParse = [];
  17616. }
  17617. for (i = 0; i < 12; i++) {
  17618. // make the regex if we don't have it already
  17619. if (!this._monthsParse[i]) {
  17620. mom = moment.utc([2000, i]);
  17621. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17622. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17623. }
  17624. // test the regex
  17625. if (this._monthsParse[i].test(monthName)) {
  17626. return i;
  17627. }
  17628. }
  17629. },
  17630. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17631. weekdays : function (m) {
  17632. return this._weekdays[m.day()];
  17633. },
  17634. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17635. weekdaysShort : function (m) {
  17636. return this._weekdaysShort[m.day()];
  17637. },
  17638. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17639. weekdaysMin : function (m) {
  17640. return this._weekdaysMin[m.day()];
  17641. },
  17642. weekdaysParse : function (weekdayName) {
  17643. var i, mom, regex;
  17644. if (!this._weekdaysParse) {
  17645. this._weekdaysParse = [];
  17646. }
  17647. for (i = 0; i < 7; i++) {
  17648. // make the regex if we don't have it already
  17649. if (!this._weekdaysParse[i]) {
  17650. mom = moment([2000, 1]).day(i);
  17651. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17652. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17653. }
  17654. // test the regex
  17655. if (this._weekdaysParse[i].test(weekdayName)) {
  17656. return i;
  17657. }
  17658. }
  17659. },
  17660. _longDateFormat : {
  17661. LT : "h:mm A",
  17662. L : "MM/DD/YYYY",
  17663. LL : "MMMM D YYYY",
  17664. LLL : "MMMM D YYYY LT",
  17665. LLLL : "dddd, MMMM D YYYY LT"
  17666. },
  17667. longDateFormat : function (key) {
  17668. var output = this._longDateFormat[key];
  17669. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17670. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17671. return val.slice(1);
  17672. });
  17673. this._longDateFormat[key] = output;
  17674. }
  17675. return output;
  17676. },
  17677. isPM : function (input) {
  17678. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17679. // Using charAt should be more compatible.
  17680. return ((input + '').toLowerCase().charAt(0) === 'p');
  17681. },
  17682. _meridiemParse : /[ap]\.?m?\.?/i,
  17683. meridiem : function (hours, minutes, isLower) {
  17684. if (hours > 11) {
  17685. return isLower ? 'pm' : 'PM';
  17686. } else {
  17687. return isLower ? 'am' : 'AM';
  17688. }
  17689. },
  17690. _calendar : {
  17691. sameDay : '[Today at] LT',
  17692. nextDay : '[Tomorrow at] LT',
  17693. nextWeek : 'dddd [at] LT',
  17694. lastDay : '[Yesterday at] LT',
  17695. lastWeek : '[Last] dddd [at] LT',
  17696. sameElse : 'L'
  17697. },
  17698. calendar : function (key, mom) {
  17699. var output = this._calendar[key];
  17700. return typeof output === 'function' ? output.apply(mom) : output;
  17701. },
  17702. _relativeTime : {
  17703. future : "in %s",
  17704. past : "%s ago",
  17705. s : "a few seconds",
  17706. m : "a minute",
  17707. mm : "%d minutes",
  17708. h : "an hour",
  17709. hh : "%d hours",
  17710. d : "a day",
  17711. dd : "%d days",
  17712. M : "a month",
  17713. MM : "%d months",
  17714. y : "a year",
  17715. yy : "%d years"
  17716. },
  17717. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17718. var output = this._relativeTime[string];
  17719. return (typeof output === 'function') ?
  17720. output(number, withoutSuffix, string, isFuture) :
  17721. output.replace(/%d/i, number);
  17722. },
  17723. pastFuture : function (diff, output) {
  17724. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17725. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17726. },
  17727. ordinal : function (number) {
  17728. return this._ordinal.replace("%d", number);
  17729. },
  17730. _ordinal : "%d",
  17731. preparse : function (string) {
  17732. return string;
  17733. },
  17734. postformat : function (string) {
  17735. return string;
  17736. },
  17737. week : function (mom) {
  17738. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17739. },
  17740. _week : {
  17741. dow : 0, // Sunday is the first day of the week.
  17742. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17743. },
  17744. _invalidDate: 'Invalid date',
  17745. invalidDate: function () {
  17746. return this._invalidDate;
  17747. }
  17748. });
  17749. // Loads a language definition into the `languages` cache. The function
  17750. // takes a key and optionally values. If not in the browser and no values
  17751. // are provided, it will load the language file module. As a convenience,
  17752. // this function also returns the language values.
  17753. function loadLang(key, values) {
  17754. values.abbr = key;
  17755. if (!languages[key]) {
  17756. languages[key] = new Language();
  17757. }
  17758. languages[key].set(values);
  17759. return languages[key];
  17760. }
  17761. // Remove a language from the `languages` cache. Mostly useful in tests.
  17762. function unloadLang(key) {
  17763. delete languages[key];
  17764. }
  17765. // Determines which language definition to use and returns it.
  17766. //
  17767. // With no parameters, it will return the global language. If you
  17768. // pass in a language key, such as 'en', it will return the
  17769. // definition for 'en', so long as 'en' has already been loaded using
  17770. // moment.lang.
  17771. function getLangDefinition(key) {
  17772. var i = 0, j, lang, next, split,
  17773. get = function (k) {
  17774. if (!languages[k] && hasModule) {
  17775. try {
  17776. require('./lang/' + k);
  17777. } catch (e) { }
  17778. }
  17779. return languages[k];
  17780. };
  17781. if (!key) {
  17782. return moment.fn._lang;
  17783. }
  17784. if (!isArray(key)) {
  17785. //short-circuit everything else
  17786. lang = get(key);
  17787. if (lang) {
  17788. return lang;
  17789. }
  17790. key = [key];
  17791. }
  17792. //pick the language from the array
  17793. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17794. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17795. while (i < key.length) {
  17796. split = normalizeLanguage(key[i]).split('-');
  17797. j = split.length;
  17798. next = normalizeLanguage(key[i + 1]);
  17799. next = next ? next.split('-') : null;
  17800. while (j > 0) {
  17801. lang = get(split.slice(0, j).join('-'));
  17802. if (lang) {
  17803. return lang;
  17804. }
  17805. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17806. //the next array item is better than a shallower substring of this one
  17807. break;
  17808. }
  17809. j--;
  17810. }
  17811. i++;
  17812. }
  17813. return moment.fn._lang;
  17814. }
  17815. /************************************
  17816. Formatting
  17817. ************************************/
  17818. function removeFormattingTokens(input) {
  17819. if (input.match(/\[[\s\S]/)) {
  17820. return input.replace(/^\[|\]$/g, "");
  17821. }
  17822. return input.replace(/\\/g, "");
  17823. }
  17824. function makeFormatFunction(format) {
  17825. var array = format.match(formattingTokens), i, length;
  17826. for (i = 0, length = array.length; i < length; i++) {
  17827. if (formatTokenFunctions[array[i]]) {
  17828. array[i] = formatTokenFunctions[array[i]];
  17829. } else {
  17830. array[i] = removeFormattingTokens(array[i]);
  17831. }
  17832. }
  17833. return function (mom) {
  17834. var output = "";
  17835. for (i = 0; i < length; i++) {
  17836. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17837. }
  17838. return output;
  17839. };
  17840. }
  17841. // format date using native date object
  17842. function formatMoment(m, format) {
  17843. if (!m.isValid()) {
  17844. return m.lang().invalidDate();
  17845. }
  17846. format = expandFormat(format, m.lang());
  17847. if (!formatFunctions[format]) {
  17848. formatFunctions[format] = makeFormatFunction(format);
  17849. }
  17850. return formatFunctions[format](m);
  17851. }
  17852. function expandFormat(format, lang) {
  17853. var i = 5;
  17854. function replaceLongDateFormatTokens(input) {
  17855. return lang.longDateFormat(input) || input;
  17856. }
  17857. localFormattingTokens.lastIndex = 0;
  17858. while (i >= 0 && localFormattingTokens.test(format)) {
  17859. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17860. localFormattingTokens.lastIndex = 0;
  17861. i -= 1;
  17862. }
  17863. return format;
  17864. }
  17865. /************************************
  17866. Parsing
  17867. ************************************/
  17868. // get the regex to find the next token
  17869. function getParseRegexForToken(token, config) {
  17870. var a, strict = config._strict;
  17871. switch (token) {
  17872. case 'Q':
  17873. return parseTokenOneDigit;
  17874. case 'DDDD':
  17875. return parseTokenThreeDigits;
  17876. case 'YYYY':
  17877. case 'GGGG':
  17878. case 'gggg':
  17879. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17880. case 'Y':
  17881. case 'G':
  17882. case 'g':
  17883. return parseTokenSignedNumber;
  17884. case 'YYYYYY':
  17885. case 'YYYYY':
  17886. case 'GGGGG':
  17887. case 'ggggg':
  17888. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17889. case 'S':
  17890. if (strict) { return parseTokenOneDigit; }
  17891. /* falls through */
  17892. case 'SS':
  17893. if (strict) { return parseTokenTwoDigits; }
  17894. /* falls through */
  17895. case 'SSS':
  17896. if (strict) { return parseTokenThreeDigits; }
  17897. /* falls through */
  17898. case 'DDD':
  17899. return parseTokenOneToThreeDigits;
  17900. case 'MMM':
  17901. case 'MMMM':
  17902. case 'dd':
  17903. case 'ddd':
  17904. case 'dddd':
  17905. return parseTokenWord;
  17906. case 'a':
  17907. case 'A':
  17908. return getLangDefinition(config._l)._meridiemParse;
  17909. case 'X':
  17910. return parseTokenTimestampMs;
  17911. case 'Z':
  17912. case 'ZZ':
  17913. return parseTokenTimezone;
  17914. case 'T':
  17915. return parseTokenT;
  17916. case 'SSSS':
  17917. return parseTokenDigits;
  17918. case 'MM':
  17919. case 'DD':
  17920. case 'YY':
  17921. case 'GG':
  17922. case 'gg':
  17923. case 'HH':
  17924. case 'hh':
  17925. case 'mm':
  17926. case 'ss':
  17927. case 'ww':
  17928. case 'WW':
  17929. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17930. case 'M':
  17931. case 'D':
  17932. case 'd':
  17933. case 'H':
  17934. case 'h':
  17935. case 'm':
  17936. case 's':
  17937. case 'w':
  17938. case 'W':
  17939. case 'e':
  17940. case 'E':
  17941. return parseTokenOneOrTwoDigits;
  17942. case 'Do':
  17943. return parseTokenOrdinal;
  17944. default :
  17945. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17946. return a;
  17947. }
  17948. }
  17949. function timezoneMinutesFromString(string) {
  17950. string = string || "";
  17951. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17952. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17953. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17954. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17955. return parts[0] === '+' ? -minutes : minutes;
  17956. }
  17957. // function to convert string input to date
  17958. function addTimeToArrayFromToken(token, input, config) {
  17959. var a, datePartArray = config._a;
  17960. switch (token) {
  17961. // QUARTER
  17962. case 'Q':
  17963. if (input != null) {
  17964. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  17965. }
  17966. break;
  17967. // MONTH
  17968. case 'M' : // fall through to MM
  17969. case 'MM' :
  17970. if (input != null) {
  17971. datePartArray[MONTH] = toInt(input) - 1;
  17972. }
  17973. break;
  17974. case 'MMM' : // fall through to MMMM
  17975. case 'MMMM' :
  17976. a = getLangDefinition(config._l).monthsParse(input);
  17977. // if we didn't find a month name, mark the date as invalid.
  17978. if (a != null) {
  17979. datePartArray[MONTH] = a;
  17980. } else {
  17981. config._pf.invalidMonth = input;
  17982. }
  17983. break;
  17984. // DAY OF MONTH
  17985. case 'D' : // fall through to DD
  17986. case 'DD' :
  17987. if (input != null) {
  17988. datePartArray[DATE] = toInt(input);
  17989. }
  17990. break;
  17991. case 'Do' :
  17992. if (input != null) {
  17993. datePartArray[DATE] = toInt(parseInt(input, 10));
  17994. }
  17995. break;
  17996. // DAY OF YEAR
  17997. case 'DDD' : // fall through to DDDD
  17998. case 'DDDD' :
  17999. if (input != null) {
  18000. config._dayOfYear = toInt(input);
  18001. }
  18002. break;
  18003. // YEAR
  18004. case 'YY' :
  18005. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  18006. break;
  18007. case 'YYYY' :
  18008. case 'YYYYY' :
  18009. case 'YYYYYY' :
  18010. datePartArray[YEAR] = toInt(input);
  18011. break;
  18012. // AM / PM
  18013. case 'a' : // fall through to A
  18014. case 'A' :
  18015. config._isPm = getLangDefinition(config._l).isPM(input);
  18016. break;
  18017. // 24 HOUR
  18018. case 'H' : // fall through to hh
  18019. case 'HH' : // fall through to hh
  18020. case 'h' : // fall through to hh
  18021. case 'hh' :
  18022. datePartArray[HOUR] = toInt(input);
  18023. break;
  18024. // MINUTE
  18025. case 'm' : // fall through to mm
  18026. case 'mm' :
  18027. datePartArray[MINUTE] = toInt(input);
  18028. break;
  18029. // SECOND
  18030. case 's' : // fall through to ss
  18031. case 'ss' :
  18032. datePartArray[SECOND] = toInt(input);
  18033. break;
  18034. // MILLISECOND
  18035. case 'S' :
  18036. case 'SS' :
  18037. case 'SSS' :
  18038. case 'SSSS' :
  18039. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18040. break;
  18041. // UNIX TIMESTAMP WITH MS
  18042. case 'X':
  18043. config._d = new Date(parseFloat(input) * 1000);
  18044. break;
  18045. // TIMEZONE
  18046. case 'Z' : // fall through to ZZ
  18047. case 'ZZ' :
  18048. config._useUTC = true;
  18049. config._tzm = timezoneMinutesFromString(input);
  18050. break;
  18051. case 'w':
  18052. case 'ww':
  18053. case 'W':
  18054. case 'WW':
  18055. case 'd':
  18056. case 'dd':
  18057. case 'ddd':
  18058. case 'dddd':
  18059. case 'e':
  18060. case 'E':
  18061. token = token.substr(0, 1);
  18062. /* falls through */
  18063. case 'gg':
  18064. case 'gggg':
  18065. case 'GG':
  18066. case 'GGGG':
  18067. case 'GGGGG':
  18068. token = token.substr(0, 2);
  18069. if (input) {
  18070. config._w = config._w || {};
  18071. config._w[token] = input;
  18072. }
  18073. break;
  18074. }
  18075. }
  18076. // convert an array to a date.
  18077. // the array should mirror the parameters below
  18078. // note: all values past the year are optional and will default to the lowest possible value.
  18079. // [year, month, day , hour, minute, second, millisecond]
  18080. function dateFromConfig(config) {
  18081. var i, date, input = [], currentDate,
  18082. yearToUse, fixYear, w, temp, lang, weekday, week;
  18083. if (config._d) {
  18084. return;
  18085. }
  18086. currentDate = currentDateArray(config);
  18087. //compute day of the year from weeks and weekdays
  18088. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18089. fixYear = function (val) {
  18090. var intVal = parseInt(val, 10);
  18091. return val ?
  18092. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  18093. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18094. };
  18095. w = config._w;
  18096. if (w.GG != null || w.W != null || w.E != null) {
  18097. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18098. }
  18099. else {
  18100. lang = getLangDefinition(config._l);
  18101. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18102. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18103. week = parseInt(w.w, 10) || 1;
  18104. //if we're parsing 'd', then the low day numbers may be next week
  18105. if (w.d != null && weekday < lang._week.dow) {
  18106. week++;
  18107. }
  18108. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18109. }
  18110. config._a[YEAR] = temp.year;
  18111. config._dayOfYear = temp.dayOfYear;
  18112. }
  18113. //if the day of the year is set, figure out what it is
  18114. if (config._dayOfYear) {
  18115. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18116. if (config._dayOfYear > daysInYear(yearToUse)) {
  18117. config._pf._overflowDayOfYear = true;
  18118. }
  18119. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18120. config._a[MONTH] = date.getUTCMonth();
  18121. config._a[DATE] = date.getUTCDate();
  18122. }
  18123. // Default to current date.
  18124. // * if no year, month, day of month are given, default to today
  18125. // * if day of month is given, default month and year
  18126. // * if month is given, default only year
  18127. // * if year is given, don't default anything
  18128. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18129. config._a[i] = input[i] = currentDate[i];
  18130. }
  18131. // Zero out whatever was not defaulted, including time
  18132. for (; i < 7; i++) {
  18133. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18134. }
  18135. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18136. input[HOUR] += toInt((config._tzm || 0) / 60);
  18137. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18138. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18139. }
  18140. function dateFromObject(config) {
  18141. var normalizedInput;
  18142. if (config._d) {
  18143. return;
  18144. }
  18145. normalizedInput = normalizeObjectUnits(config._i);
  18146. config._a = [
  18147. normalizedInput.year,
  18148. normalizedInput.month,
  18149. normalizedInput.day,
  18150. normalizedInput.hour,
  18151. normalizedInput.minute,
  18152. normalizedInput.second,
  18153. normalizedInput.millisecond
  18154. ];
  18155. dateFromConfig(config);
  18156. }
  18157. function currentDateArray(config) {
  18158. var now = new Date();
  18159. if (config._useUTC) {
  18160. return [
  18161. now.getUTCFullYear(),
  18162. now.getUTCMonth(),
  18163. now.getUTCDate()
  18164. ];
  18165. } else {
  18166. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18167. }
  18168. }
  18169. // date from string and format string
  18170. function makeDateFromStringAndFormat(config) {
  18171. config._a = [];
  18172. config._pf.empty = true;
  18173. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18174. var lang = getLangDefinition(config._l),
  18175. string = '' + config._i,
  18176. i, parsedInput, tokens, token, skipped,
  18177. stringLength = string.length,
  18178. totalParsedInputLength = 0;
  18179. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18180. for (i = 0; i < tokens.length; i++) {
  18181. token = tokens[i];
  18182. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18183. if (parsedInput) {
  18184. skipped = string.substr(0, string.indexOf(parsedInput));
  18185. if (skipped.length > 0) {
  18186. config._pf.unusedInput.push(skipped);
  18187. }
  18188. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18189. totalParsedInputLength += parsedInput.length;
  18190. }
  18191. // don't parse if it's not a known token
  18192. if (formatTokenFunctions[token]) {
  18193. if (parsedInput) {
  18194. config._pf.empty = false;
  18195. }
  18196. else {
  18197. config._pf.unusedTokens.push(token);
  18198. }
  18199. addTimeToArrayFromToken(token, parsedInput, config);
  18200. }
  18201. else if (config._strict && !parsedInput) {
  18202. config._pf.unusedTokens.push(token);
  18203. }
  18204. }
  18205. // add remaining unparsed input length to the string
  18206. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18207. if (string.length > 0) {
  18208. config._pf.unusedInput.push(string);
  18209. }
  18210. // handle am pm
  18211. if (config._isPm && config._a[HOUR] < 12) {
  18212. config._a[HOUR] += 12;
  18213. }
  18214. // if is 12 am, change hours to 0
  18215. if (config._isPm === false && config._a[HOUR] === 12) {
  18216. config._a[HOUR] = 0;
  18217. }
  18218. dateFromConfig(config);
  18219. checkOverflow(config);
  18220. }
  18221. function unescapeFormat(s) {
  18222. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18223. return p1 || p2 || p3 || p4;
  18224. });
  18225. }
  18226. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18227. function regexpEscape(s) {
  18228. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18229. }
  18230. // date from string and array of format strings
  18231. function makeDateFromStringAndArray(config) {
  18232. var tempConfig,
  18233. bestMoment,
  18234. scoreToBeat,
  18235. i,
  18236. currentScore;
  18237. if (config._f.length === 0) {
  18238. config._pf.invalidFormat = true;
  18239. config._d = new Date(NaN);
  18240. return;
  18241. }
  18242. for (i = 0; i < config._f.length; i++) {
  18243. currentScore = 0;
  18244. tempConfig = extend({}, config);
  18245. tempConfig._pf = defaultParsingFlags();
  18246. tempConfig._f = config._f[i];
  18247. makeDateFromStringAndFormat(tempConfig);
  18248. if (!isValid(tempConfig)) {
  18249. continue;
  18250. }
  18251. // if there is any input that was not parsed add a penalty for that format
  18252. currentScore += tempConfig._pf.charsLeftOver;
  18253. //or tokens
  18254. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18255. tempConfig._pf.score = currentScore;
  18256. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18257. scoreToBeat = currentScore;
  18258. bestMoment = tempConfig;
  18259. }
  18260. }
  18261. extend(config, bestMoment || tempConfig);
  18262. }
  18263. // date from iso format
  18264. function makeDateFromString(config) {
  18265. var i, l,
  18266. string = config._i,
  18267. match = isoRegex.exec(string);
  18268. if (match) {
  18269. config._pf.iso = true;
  18270. for (i = 0, l = isoDates.length; i < l; i++) {
  18271. if (isoDates[i][1].exec(string)) {
  18272. // match[5] should be "T" or undefined
  18273. config._f = isoDates[i][0] + (match[6] || " ");
  18274. break;
  18275. }
  18276. }
  18277. for (i = 0, l = isoTimes.length; i < l; i++) {
  18278. if (isoTimes[i][1].exec(string)) {
  18279. config._f += isoTimes[i][0];
  18280. break;
  18281. }
  18282. }
  18283. if (string.match(parseTokenTimezone)) {
  18284. config._f += "Z";
  18285. }
  18286. makeDateFromStringAndFormat(config);
  18287. }
  18288. else {
  18289. moment.createFromInputFallback(config);
  18290. }
  18291. }
  18292. function makeDateFromInput(config) {
  18293. var input = config._i,
  18294. matched = aspNetJsonRegex.exec(input);
  18295. if (input === undefined) {
  18296. config._d = new Date();
  18297. } else if (matched) {
  18298. config._d = new Date(+matched[1]);
  18299. } else if (typeof input === 'string') {
  18300. makeDateFromString(config);
  18301. } else if (isArray(input)) {
  18302. config._a = input.slice(0);
  18303. dateFromConfig(config);
  18304. } else if (isDate(input)) {
  18305. config._d = new Date(+input);
  18306. } else if (typeof(input) === 'object') {
  18307. dateFromObject(config);
  18308. } else if (typeof(input) === 'number') {
  18309. // from milliseconds
  18310. config._d = new Date(input);
  18311. } else {
  18312. moment.createFromInputFallback(config);
  18313. }
  18314. }
  18315. function makeDate(y, m, d, h, M, s, ms) {
  18316. //can't just apply() to create a date:
  18317. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18318. var date = new Date(y, m, d, h, M, s, ms);
  18319. //the date constructor doesn't accept years < 1970
  18320. if (y < 1970) {
  18321. date.setFullYear(y);
  18322. }
  18323. return date;
  18324. }
  18325. function makeUTCDate(y) {
  18326. var date = new Date(Date.UTC.apply(null, arguments));
  18327. if (y < 1970) {
  18328. date.setUTCFullYear(y);
  18329. }
  18330. return date;
  18331. }
  18332. function parseWeekday(input, language) {
  18333. if (typeof input === 'string') {
  18334. if (!isNaN(input)) {
  18335. input = parseInt(input, 10);
  18336. }
  18337. else {
  18338. input = language.weekdaysParse(input);
  18339. if (typeof input !== 'number') {
  18340. return null;
  18341. }
  18342. }
  18343. }
  18344. return input;
  18345. }
  18346. /************************************
  18347. Relative Time
  18348. ************************************/
  18349. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18350. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18351. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18352. }
  18353. function relativeTime(milliseconds, withoutSuffix, lang) {
  18354. var seconds = round(Math.abs(milliseconds) / 1000),
  18355. minutes = round(seconds / 60),
  18356. hours = round(minutes / 60),
  18357. days = round(hours / 24),
  18358. years = round(days / 365),
  18359. args = seconds < 45 && ['s', seconds] ||
  18360. minutes === 1 && ['m'] ||
  18361. minutes < 45 && ['mm', minutes] ||
  18362. hours === 1 && ['h'] ||
  18363. hours < 22 && ['hh', hours] ||
  18364. days === 1 && ['d'] ||
  18365. days <= 25 && ['dd', days] ||
  18366. days <= 45 && ['M'] ||
  18367. days < 345 && ['MM', round(days / 30)] ||
  18368. years === 1 && ['y'] || ['yy', years];
  18369. args[2] = withoutSuffix;
  18370. args[3] = milliseconds > 0;
  18371. args[4] = lang;
  18372. return substituteTimeAgo.apply({}, args);
  18373. }
  18374. /************************************
  18375. Week of Year
  18376. ************************************/
  18377. // firstDayOfWeek 0 = sun, 6 = sat
  18378. // the day of the week that starts the week
  18379. // (usually sunday or monday)
  18380. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18381. // the first week is the week that contains the first
  18382. // of this day of the week
  18383. // (eg. ISO weeks use thursday (4))
  18384. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18385. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18386. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18387. adjustedMoment;
  18388. if (daysToDayOfWeek > end) {
  18389. daysToDayOfWeek -= 7;
  18390. }
  18391. if (daysToDayOfWeek < end - 7) {
  18392. daysToDayOfWeek += 7;
  18393. }
  18394. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18395. return {
  18396. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18397. year: adjustedMoment.year()
  18398. };
  18399. }
  18400. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18401. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18402. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18403. weekday = weekday != null ? weekday : firstDayOfWeek;
  18404. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18405. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18406. return {
  18407. year: dayOfYear > 0 ? year : year - 1,
  18408. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18409. };
  18410. }
  18411. /************************************
  18412. Top Level Functions
  18413. ************************************/
  18414. function makeMoment(config) {
  18415. var input = config._i,
  18416. format = config._f;
  18417. if (input === null || (format === undefined && input === '')) {
  18418. return moment.invalid({nullInput: true});
  18419. }
  18420. if (typeof input === 'string') {
  18421. config._i = input = getLangDefinition().preparse(input);
  18422. }
  18423. if (moment.isMoment(input)) {
  18424. config = cloneMoment(input);
  18425. config._d = new Date(+input._d);
  18426. } else if (format) {
  18427. if (isArray(format)) {
  18428. makeDateFromStringAndArray(config);
  18429. } else {
  18430. makeDateFromStringAndFormat(config);
  18431. }
  18432. } else {
  18433. makeDateFromInput(config);
  18434. }
  18435. return new Moment(config);
  18436. }
  18437. moment = function (input, format, lang, strict) {
  18438. var c;
  18439. if (typeof(lang) === "boolean") {
  18440. strict = lang;
  18441. lang = undefined;
  18442. }
  18443. // object construction must be done this way.
  18444. // https://github.com/moment/moment/issues/1423
  18445. c = {};
  18446. c._isAMomentObject = true;
  18447. c._i = input;
  18448. c._f = format;
  18449. c._l = lang;
  18450. c._strict = strict;
  18451. c._isUTC = false;
  18452. c._pf = defaultParsingFlags();
  18453. return makeMoment(c);
  18454. };
  18455. moment.suppressDeprecationWarnings = false;
  18456. moment.createFromInputFallback = deprecate(
  18457. "moment construction falls back to js Date. This is " +
  18458. "discouraged and will be removed in upcoming major " +
  18459. "release. Please refer to " +
  18460. "https://github.com/moment/moment/issues/1407 for more info.",
  18461. function (config) {
  18462. config._d = new Date(config._i);
  18463. });
  18464. // creating with utc
  18465. moment.utc = function (input, format, lang, strict) {
  18466. var c;
  18467. if (typeof(lang) === "boolean") {
  18468. strict = lang;
  18469. lang = undefined;
  18470. }
  18471. // object construction must be done this way.
  18472. // https://github.com/moment/moment/issues/1423
  18473. c = {};
  18474. c._isAMomentObject = true;
  18475. c._useUTC = true;
  18476. c._isUTC = true;
  18477. c._l = lang;
  18478. c._i = input;
  18479. c._f = format;
  18480. c._strict = strict;
  18481. c._pf = defaultParsingFlags();
  18482. return makeMoment(c).utc();
  18483. };
  18484. // creating with unix timestamp (in seconds)
  18485. moment.unix = function (input) {
  18486. return moment(input * 1000);
  18487. };
  18488. // duration
  18489. moment.duration = function (input, key) {
  18490. var duration = input,
  18491. // matching against regexp is expensive, do it on demand
  18492. match = null,
  18493. sign,
  18494. ret,
  18495. parseIso;
  18496. if (moment.isDuration(input)) {
  18497. duration = {
  18498. ms: input._milliseconds,
  18499. d: input._days,
  18500. M: input._months
  18501. };
  18502. } else if (typeof input === 'number') {
  18503. duration = {};
  18504. if (key) {
  18505. duration[key] = input;
  18506. } else {
  18507. duration.milliseconds = input;
  18508. }
  18509. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18510. sign = (match[1] === "-") ? -1 : 1;
  18511. duration = {
  18512. y: 0,
  18513. d: toInt(match[DATE]) * sign,
  18514. h: toInt(match[HOUR]) * sign,
  18515. m: toInt(match[MINUTE]) * sign,
  18516. s: toInt(match[SECOND]) * sign,
  18517. ms: toInt(match[MILLISECOND]) * sign
  18518. };
  18519. } else if (!!(match = isoDurationRegex.exec(input))) {
  18520. sign = (match[1] === "-") ? -1 : 1;
  18521. parseIso = function (inp) {
  18522. // We'd normally use ~~inp for this, but unfortunately it also
  18523. // converts floats to ints.
  18524. // inp may be undefined, so careful calling replace on it.
  18525. var res = inp && parseFloat(inp.replace(',', '.'));
  18526. // apply sign while we're at it
  18527. return (isNaN(res) ? 0 : res) * sign;
  18528. };
  18529. duration = {
  18530. y: parseIso(match[2]),
  18531. M: parseIso(match[3]),
  18532. d: parseIso(match[4]),
  18533. h: parseIso(match[5]),
  18534. m: parseIso(match[6]),
  18535. s: parseIso(match[7]),
  18536. w: parseIso(match[8])
  18537. };
  18538. }
  18539. ret = new Duration(duration);
  18540. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18541. ret._lang = input._lang;
  18542. }
  18543. return ret;
  18544. };
  18545. // version number
  18546. moment.version = VERSION;
  18547. // default format
  18548. moment.defaultFormat = isoFormat;
  18549. // Plugins that add properties should also add the key here (null value),
  18550. // so we can properly clone ourselves.
  18551. moment.momentProperties = momentProperties;
  18552. // This function will be called whenever a moment is mutated.
  18553. // It is intended to keep the offset in sync with the timezone.
  18554. moment.updateOffset = function () {};
  18555. // This function will load languages and then set the global language. If
  18556. // no arguments are passed in, it will simply return the current global
  18557. // language key.
  18558. moment.lang = function (key, values) {
  18559. var r;
  18560. if (!key) {
  18561. return moment.fn._lang._abbr;
  18562. }
  18563. if (values) {
  18564. loadLang(normalizeLanguage(key), values);
  18565. } else if (values === null) {
  18566. unloadLang(key);
  18567. key = 'en';
  18568. } else if (!languages[key]) {
  18569. getLangDefinition(key);
  18570. }
  18571. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18572. return r._abbr;
  18573. };
  18574. // returns language data
  18575. moment.langData = function (key) {
  18576. if (key && key._lang && key._lang._abbr) {
  18577. key = key._lang._abbr;
  18578. }
  18579. return getLangDefinition(key);
  18580. };
  18581. // compare moment object
  18582. moment.isMoment = function (obj) {
  18583. return obj instanceof Moment ||
  18584. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18585. };
  18586. // for typechecking Duration objects
  18587. moment.isDuration = function (obj) {
  18588. return obj instanceof Duration;
  18589. };
  18590. for (i = lists.length - 1; i >= 0; --i) {
  18591. makeList(lists[i]);
  18592. }
  18593. moment.normalizeUnits = function (units) {
  18594. return normalizeUnits(units);
  18595. };
  18596. moment.invalid = function (flags) {
  18597. var m = moment.utc(NaN);
  18598. if (flags != null) {
  18599. extend(m._pf, flags);
  18600. }
  18601. else {
  18602. m._pf.userInvalidated = true;
  18603. }
  18604. return m;
  18605. };
  18606. moment.parseZone = function () {
  18607. return moment.apply(null, arguments).parseZone();
  18608. };
  18609. moment.parseTwoDigitYear = function (input) {
  18610. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18611. };
  18612. /************************************
  18613. Moment Prototype
  18614. ************************************/
  18615. extend(moment.fn = Moment.prototype, {
  18616. clone : function () {
  18617. return moment(this);
  18618. },
  18619. valueOf : function () {
  18620. return +this._d + ((this._offset || 0) * 60000);
  18621. },
  18622. unix : function () {
  18623. return Math.floor(+this / 1000);
  18624. },
  18625. toString : function () {
  18626. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18627. },
  18628. toDate : function () {
  18629. return this._offset ? new Date(+this) : this._d;
  18630. },
  18631. toISOString : function () {
  18632. var m = moment(this).utc();
  18633. if (0 < m.year() && m.year() <= 9999) {
  18634. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18635. } else {
  18636. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18637. }
  18638. },
  18639. toArray : function () {
  18640. var m = this;
  18641. return [
  18642. m.year(),
  18643. m.month(),
  18644. m.date(),
  18645. m.hours(),
  18646. m.minutes(),
  18647. m.seconds(),
  18648. m.milliseconds()
  18649. ];
  18650. },
  18651. isValid : function () {
  18652. return isValid(this);
  18653. },
  18654. isDSTShifted : function () {
  18655. if (this._a) {
  18656. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18657. }
  18658. return false;
  18659. },
  18660. parsingFlags : function () {
  18661. return extend({}, this._pf);
  18662. },
  18663. invalidAt: function () {
  18664. return this._pf.overflow;
  18665. },
  18666. utc : function () {
  18667. return this.zone(0);
  18668. },
  18669. local : function () {
  18670. this.zone(0);
  18671. this._isUTC = false;
  18672. return this;
  18673. },
  18674. format : function (inputString) {
  18675. var output = formatMoment(this, inputString || moment.defaultFormat);
  18676. return this.lang().postformat(output);
  18677. },
  18678. add : function (input, val) {
  18679. var dur;
  18680. // switch args to support add('s', 1) and add(1, 's')
  18681. if (typeof input === 'string') {
  18682. dur = moment.duration(+val, input);
  18683. } else {
  18684. dur = moment.duration(input, val);
  18685. }
  18686. addOrSubtractDurationFromMoment(this, dur, 1);
  18687. return this;
  18688. },
  18689. subtract : function (input, val) {
  18690. var dur;
  18691. // switch args to support subtract('s', 1) and subtract(1, 's')
  18692. if (typeof input === 'string') {
  18693. dur = moment.duration(+val, input);
  18694. } else {
  18695. dur = moment.duration(input, val);
  18696. }
  18697. addOrSubtractDurationFromMoment(this, dur, -1);
  18698. return this;
  18699. },
  18700. diff : function (input, units, asFloat) {
  18701. var that = makeAs(input, this),
  18702. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18703. diff, output;
  18704. units = normalizeUnits(units);
  18705. if (units === 'year' || units === 'month') {
  18706. // average number of days in the months in the given dates
  18707. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18708. // difference in months
  18709. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18710. // adjust by taking difference in days, average number of days
  18711. // and dst in the given months.
  18712. output += ((this - moment(this).startOf('month')) -
  18713. (that - moment(that).startOf('month'))) / diff;
  18714. // same as above but with zones, to negate all dst
  18715. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18716. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18717. if (units === 'year') {
  18718. output = output / 12;
  18719. }
  18720. } else {
  18721. diff = (this - that);
  18722. output = units === 'second' ? diff / 1e3 : // 1000
  18723. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18724. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18725. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18726. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18727. diff;
  18728. }
  18729. return asFloat ? output : absRound(output);
  18730. },
  18731. from : function (time, withoutSuffix) {
  18732. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18733. },
  18734. fromNow : function (withoutSuffix) {
  18735. return this.from(moment(), withoutSuffix);
  18736. },
  18737. calendar : function () {
  18738. // We want to compare the start of today, vs this.
  18739. // Getting start-of-today depends on whether we're zone'd or not.
  18740. var sod = makeAs(moment(), this).startOf('day'),
  18741. diff = this.diff(sod, 'days', true),
  18742. format = diff < -6 ? 'sameElse' :
  18743. diff < -1 ? 'lastWeek' :
  18744. diff < 0 ? 'lastDay' :
  18745. diff < 1 ? 'sameDay' :
  18746. diff < 2 ? 'nextDay' :
  18747. diff < 7 ? 'nextWeek' : 'sameElse';
  18748. return this.format(this.lang().calendar(format, this));
  18749. },
  18750. isLeapYear : function () {
  18751. return isLeapYear(this.year());
  18752. },
  18753. isDST : function () {
  18754. return (this.zone() < this.clone().month(0).zone() ||
  18755. this.zone() < this.clone().month(5).zone());
  18756. },
  18757. day : function (input) {
  18758. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18759. if (input != null) {
  18760. input = parseWeekday(input, this.lang());
  18761. return this.add({ d : input - day });
  18762. } else {
  18763. return day;
  18764. }
  18765. },
  18766. month : makeAccessor('Month', true),
  18767. startOf: function (units) {
  18768. units = normalizeUnits(units);
  18769. // the following switch intentionally omits break keywords
  18770. // to utilize falling through the cases.
  18771. switch (units) {
  18772. case 'year':
  18773. this.month(0);
  18774. /* falls through */
  18775. case 'quarter':
  18776. case 'month':
  18777. this.date(1);
  18778. /* falls through */
  18779. case 'week':
  18780. case 'isoWeek':
  18781. case 'day':
  18782. this.hours(0);
  18783. /* falls through */
  18784. case 'hour':
  18785. this.minutes(0);
  18786. /* falls through */
  18787. case 'minute':
  18788. this.seconds(0);
  18789. /* falls through */
  18790. case 'second':
  18791. this.milliseconds(0);
  18792. /* falls through */
  18793. }
  18794. // weeks are a special case
  18795. if (units === 'week') {
  18796. this.weekday(0);
  18797. } else if (units === 'isoWeek') {
  18798. this.isoWeekday(1);
  18799. }
  18800. // quarters are also special
  18801. if (units === 'quarter') {
  18802. this.month(Math.floor(this.month() / 3) * 3);
  18803. }
  18804. return this;
  18805. },
  18806. endOf: function (units) {
  18807. units = normalizeUnits(units);
  18808. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18809. },
  18810. isAfter: function (input, units) {
  18811. units = typeof units !== 'undefined' ? units : 'millisecond';
  18812. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18813. },
  18814. isBefore: function (input, units) {
  18815. units = typeof units !== 'undefined' ? units : 'millisecond';
  18816. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18817. },
  18818. isSame: function (input, units) {
  18819. units = units || 'ms';
  18820. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18821. },
  18822. min: function (other) {
  18823. other = moment.apply(null, arguments);
  18824. return other < this ? this : other;
  18825. },
  18826. max: function (other) {
  18827. other = moment.apply(null, arguments);
  18828. return other > this ? this : other;
  18829. },
  18830. // keepTime = true means only change the timezone, without affecting
  18831. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18832. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18833. // adjust the time as needed, to be valid.
  18834. //
  18835. // Keeping the time actually adds/subtracts (one hour)
  18836. // from the actual represented time. That is why we call updateOffset
  18837. // a second time. In case it wants us to change the offset again
  18838. // _changeInProgress == true case, then we have to adjust, because
  18839. // there is no such time in the given timezone.
  18840. zone : function (input, keepTime) {
  18841. var offset = this._offset || 0;
  18842. if (input != null) {
  18843. if (typeof input === "string") {
  18844. input = timezoneMinutesFromString(input);
  18845. }
  18846. if (Math.abs(input) < 16) {
  18847. input = input * 60;
  18848. }
  18849. this._offset = input;
  18850. this._isUTC = true;
  18851. if (offset !== input) {
  18852. if (!keepTime || this._changeInProgress) {
  18853. addOrSubtractDurationFromMoment(this,
  18854. moment.duration(offset - input, 'm'), 1, false);
  18855. } else if (!this._changeInProgress) {
  18856. this._changeInProgress = true;
  18857. moment.updateOffset(this, true);
  18858. this._changeInProgress = null;
  18859. }
  18860. }
  18861. } else {
  18862. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18863. }
  18864. return this;
  18865. },
  18866. zoneAbbr : function () {
  18867. return this._isUTC ? "UTC" : "";
  18868. },
  18869. zoneName : function () {
  18870. return this._isUTC ? "Coordinated Universal Time" : "";
  18871. },
  18872. parseZone : function () {
  18873. if (this._tzm) {
  18874. this.zone(this._tzm);
  18875. } else if (typeof this._i === 'string') {
  18876. this.zone(this._i);
  18877. }
  18878. return this;
  18879. },
  18880. hasAlignedHourOffset : function (input) {
  18881. if (!input) {
  18882. input = 0;
  18883. }
  18884. else {
  18885. input = moment(input).zone();
  18886. }
  18887. return (this.zone() - input) % 60 === 0;
  18888. },
  18889. daysInMonth : function () {
  18890. return daysInMonth(this.year(), this.month());
  18891. },
  18892. dayOfYear : function (input) {
  18893. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18894. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18895. },
  18896. quarter : function (input) {
  18897. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  18898. },
  18899. weekYear : function (input) {
  18900. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18901. return input == null ? year : this.add("y", (input - year));
  18902. },
  18903. isoWeekYear : function (input) {
  18904. var year = weekOfYear(this, 1, 4).year;
  18905. return input == null ? year : this.add("y", (input - year));
  18906. },
  18907. week : function (input) {
  18908. var week = this.lang().week(this);
  18909. return input == null ? week : this.add("d", (input - week) * 7);
  18910. },
  18911. isoWeek : function (input) {
  18912. var week = weekOfYear(this, 1, 4).week;
  18913. return input == null ? week : this.add("d", (input - week) * 7);
  18914. },
  18915. weekday : function (input) {
  18916. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18917. return input == null ? weekday : this.add("d", input - weekday);
  18918. },
  18919. isoWeekday : function (input) {
  18920. // behaves the same as moment#day except
  18921. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18922. // as a setter, sunday should belong to the previous week.
  18923. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18924. },
  18925. isoWeeksInYear : function () {
  18926. return weeksInYear(this.year(), 1, 4);
  18927. },
  18928. weeksInYear : function () {
  18929. var weekInfo = this._lang._week;
  18930. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  18931. },
  18932. get : function (units) {
  18933. units = normalizeUnits(units);
  18934. return this[units]();
  18935. },
  18936. set : function (units, value) {
  18937. units = normalizeUnits(units);
  18938. if (typeof this[units] === 'function') {
  18939. this[units](value);
  18940. }
  18941. return this;
  18942. },
  18943. // If passed a language key, it will set the language for this
  18944. // instance. Otherwise, it will return the language configuration
  18945. // variables for this instance.
  18946. lang : function (key) {
  18947. if (key === undefined) {
  18948. return this._lang;
  18949. } else {
  18950. this._lang = getLangDefinition(key);
  18951. return this;
  18952. }
  18953. }
  18954. });
  18955. function rawMonthSetter(mom, value) {
  18956. var dayOfMonth;
  18957. // TODO: Move this out of here!
  18958. if (typeof value === 'string') {
  18959. value = mom.lang().monthsParse(value);
  18960. // TODO: Another silent failure?
  18961. if (typeof value !== 'number') {
  18962. return mom;
  18963. }
  18964. }
  18965. dayOfMonth = Math.min(mom.date(),
  18966. daysInMonth(mom.year(), value));
  18967. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  18968. return mom;
  18969. }
  18970. function rawGetter(mom, unit) {
  18971. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  18972. }
  18973. function rawSetter(mom, unit, value) {
  18974. if (unit === 'Month') {
  18975. return rawMonthSetter(mom, value);
  18976. } else {
  18977. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  18978. }
  18979. }
  18980. function makeAccessor(unit, keepTime) {
  18981. return function (value) {
  18982. if (value != null) {
  18983. rawSetter(this, unit, value);
  18984. moment.updateOffset(this, keepTime);
  18985. return this;
  18986. } else {
  18987. return rawGetter(this, unit);
  18988. }
  18989. };
  18990. }
  18991. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  18992. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  18993. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  18994. // Setting the hour should keep the time, because the user explicitly
  18995. // specified which hour he wants. So trying to maintain the same hour (in
  18996. // a new timezone) makes sense. Adding/subtracting hours does not follow
  18997. // this rule.
  18998. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  18999. // moment.fn.month is defined separately
  19000. moment.fn.date = makeAccessor('Date', true);
  19001. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  19002. moment.fn.year = makeAccessor('FullYear', true);
  19003. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  19004. // add plural methods
  19005. moment.fn.days = moment.fn.day;
  19006. moment.fn.months = moment.fn.month;
  19007. moment.fn.weeks = moment.fn.week;
  19008. moment.fn.isoWeeks = moment.fn.isoWeek;
  19009. moment.fn.quarters = moment.fn.quarter;
  19010. // add aliased format methods
  19011. moment.fn.toJSON = moment.fn.toISOString;
  19012. /************************************
  19013. Duration Prototype
  19014. ************************************/
  19015. extend(moment.duration.fn = Duration.prototype, {
  19016. _bubble : function () {
  19017. var milliseconds = this._milliseconds,
  19018. days = this._days,
  19019. months = this._months,
  19020. data = this._data,
  19021. seconds, minutes, hours, years;
  19022. // The following code bubbles up values, see the tests for
  19023. // examples of what that means.
  19024. data.milliseconds = milliseconds % 1000;
  19025. seconds = absRound(milliseconds / 1000);
  19026. data.seconds = seconds % 60;
  19027. minutes = absRound(seconds / 60);
  19028. data.minutes = minutes % 60;
  19029. hours = absRound(minutes / 60);
  19030. data.hours = hours % 24;
  19031. days += absRound(hours / 24);
  19032. data.days = days % 30;
  19033. months += absRound(days / 30);
  19034. data.months = months % 12;
  19035. years = absRound(months / 12);
  19036. data.years = years;
  19037. },
  19038. weeks : function () {
  19039. return absRound(this.days() / 7);
  19040. },
  19041. valueOf : function () {
  19042. return this._milliseconds +
  19043. this._days * 864e5 +
  19044. (this._months % 12) * 2592e6 +
  19045. toInt(this._months / 12) * 31536e6;
  19046. },
  19047. humanize : function (withSuffix) {
  19048. var difference = +this,
  19049. output = relativeTime(difference, !withSuffix, this.lang());
  19050. if (withSuffix) {
  19051. output = this.lang().pastFuture(difference, output);
  19052. }
  19053. return this.lang().postformat(output);
  19054. },
  19055. add : function (input, val) {
  19056. // supports only 2.0-style add(1, 's') or add(moment)
  19057. var dur = moment.duration(input, val);
  19058. this._milliseconds += dur._milliseconds;
  19059. this._days += dur._days;
  19060. this._months += dur._months;
  19061. this._bubble();
  19062. return this;
  19063. },
  19064. subtract : function (input, val) {
  19065. var dur = moment.duration(input, val);
  19066. this._milliseconds -= dur._milliseconds;
  19067. this._days -= dur._days;
  19068. this._months -= dur._months;
  19069. this._bubble();
  19070. return this;
  19071. },
  19072. get : function (units) {
  19073. units = normalizeUnits(units);
  19074. return this[units.toLowerCase() + 's']();
  19075. },
  19076. as : function (units) {
  19077. units = normalizeUnits(units);
  19078. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19079. },
  19080. lang : moment.fn.lang,
  19081. toIsoString : function () {
  19082. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19083. var years = Math.abs(this.years()),
  19084. months = Math.abs(this.months()),
  19085. days = Math.abs(this.days()),
  19086. hours = Math.abs(this.hours()),
  19087. minutes = Math.abs(this.minutes()),
  19088. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19089. if (!this.asSeconds()) {
  19090. // this is the same as C#'s (Noda) and python (isodate)...
  19091. // but not other JS (goog.date)
  19092. return 'P0D';
  19093. }
  19094. return (this.asSeconds() < 0 ? '-' : '') +
  19095. 'P' +
  19096. (years ? years + 'Y' : '') +
  19097. (months ? months + 'M' : '') +
  19098. (days ? days + 'D' : '') +
  19099. ((hours || minutes || seconds) ? 'T' : '') +
  19100. (hours ? hours + 'H' : '') +
  19101. (minutes ? minutes + 'M' : '') +
  19102. (seconds ? seconds + 'S' : '');
  19103. }
  19104. });
  19105. function makeDurationGetter(name) {
  19106. moment.duration.fn[name] = function () {
  19107. return this._data[name];
  19108. };
  19109. }
  19110. function makeDurationAsGetter(name, factor) {
  19111. moment.duration.fn['as' + name] = function () {
  19112. return +this / factor;
  19113. };
  19114. }
  19115. for (i in unitMillisecondFactors) {
  19116. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19117. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19118. makeDurationGetter(i.toLowerCase());
  19119. }
  19120. }
  19121. makeDurationAsGetter('Weeks', 6048e5);
  19122. moment.duration.fn.asMonths = function () {
  19123. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19124. };
  19125. /************************************
  19126. Default Lang
  19127. ************************************/
  19128. // Set default language, other languages will inherit from English.
  19129. moment.lang('en', {
  19130. ordinal : function (number) {
  19131. var b = number % 10,
  19132. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19133. (b === 1) ? 'st' :
  19134. (b === 2) ? 'nd' :
  19135. (b === 3) ? 'rd' : 'th';
  19136. return number + output;
  19137. }
  19138. });
  19139. /* EMBED_LANGUAGES */
  19140. /************************************
  19141. Exposing Moment
  19142. ************************************/
  19143. function makeGlobal(shouldDeprecate) {
  19144. /*global ender:false */
  19145. if (typeof ender !== 'undefined') {
  19146. return;
  19147. }
  19148. oldGlobalMoment = globalScope.moment;
  19149. if (shouldDeprecate) {
  19150. globalScope.moment = deprecate(
  19151. "Accessing Moment through the global scope is " +
  19152. "deprecated, and will be removed in an upcoming " +
  19153. "release.",
  19154. moment);
  19155. } else {
  19156. globalScope.moment = moment;
  19157. }
  19158. }
  19159. // CommonJS module is defined
  19160. if (hasModule) {
  19161. module.exports = moment;
  19162. } else if (typeof define === "function" && define.amd) {
  19163. define("moment", function (require, exports, module) {
  19164. if (module.config && module.config() && module.config().noGlobal === true) {
  19165. // release the global variable
  19166. globalScope.moment = oldGlobalMoment;
  19167. }
  19168. return moment;
  19169. });
  19170. makeGlobal(true);
  19171. } else {
  19172. makeGlobal();
  19173. }
  19174. }).call(this);
  19175. },{}],5:[function(require,module,exports){
  19176. /**
  19177. * Copyright 2012 Craig Campbell
  19178. *
  19179. * Licensed under the Apache License, Version 2.0 (the "License");
  19180. * you may not use this file except in compliance with the License.
  19181. * You may obtain a copy of the License at
  19182. *
  19183. * http://www.apache.org/licenses/LICENSE-2.0
  19184. *
  19185. * Unless required by applicable law or agreed to in writing, software
  19186. * distributed under the License is distributed on an "AS IS" BASIS,
  19187. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19188. * See the License for the specific language governing permissions and
  19189. * limitations under the License.
  19190. *
  19191. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19192. * no external dependencies
  19193. *
  19194. * @version 1.1.2
  19195. * @url craig.is/killing/mice
  19196. */
  19197. /**
  19198. * mapping of special keycodes to their corresponding keys
  19199. *
  19200. * everything in this dictionary cannot use keypress events
  19201. * so it has to be here to map to the correct keycodes for
  19202. * keyup/keydown events
  19203. *
  19204. * @type {Object}
  19205. */
  19206. var _MAP = {
  19207. 8: 'backspace',
  19208. 9: 'tab',
  19209. 13: 'enter',
  19210. 16: 'shift',
  19211. 17: 'ctrl',
  19212. 18: 'alt',
  19213. 20: 'capslock',
  19214. 27: 'esc',
  19215. 32: 'space',
  19216. 33: 'pageup',
  19217. 34: 'pagedown',
  19218. 35: 'end',
  19219. 36: 'home',
  19220. 37: 'left',
  19221. 38: 'up',
  19222. 39: 'right',
  19223. 40: 'down',
  19224. 45: 'ins',
  19225. 46: 'del',
  19226. 91: 'meta',
  19227. 93: 'meta',
  19228. 224: 'meta'
  19229. },
  19230. /**
  19231. * mapping for special characters so they can support
  19232. *
  19233. * this dictionary is only used incase you want to bind a
  19234. * keyup or keydown event to one of these keys
  19235. *
  19236. * @type {Object}
  19237. */
  19238. _KEYCODE_MAP = {
  19239. 106: '*',
  19240. 107: '+',
  19241. 109: '-',
  19242. 110: '.',
  19243. 111 : '/',
  19244. 186: ';',
  19245. 187: '=',
  19246. 188: ',',
  19247. 189: '-',
  19248. 190: '.',
  19249. 191: '/',
  19250. 192: '`',
  19251. 219: '[',
  19252. 220: '\\',
  19253. 221: ']',
  19254. 222: '\''
  19255. },
  19256. /**
  19257. * this is a mapping of keys that require shift on a US keypad
  19258. * back to the non shift equivelents
  19259. *
  19260. * this is so you can use keyup events with these keys
  19261. *
  19262. * note that this will only work reliably on US keyboards
  19263. *
  19264. * @type {Object}
  19265. */
  19266. _SHIFT_MAP = {
  19267. '~': '`',
  19268. '!': '1',
  19269. '@': '2',
  19270. '#': '3',
  19271. '$': '4',
  19272. '%': '5',
  19273. '^': '6',
  19274. '&': '7',
  19275. '*': '8',
  19276. '(': '9',
  19277. ')': '0',
  19278. '_': '-',
  19279. '+': '=',
  19280. ':': ';',
  19281. '\"': '\'',
  19282. '<': ',',
  19283. '>': '.',
  19284. '?': '/',
  19285. '|': '\\'
  19286. },
  19287. /**
  19288. * this is a list of special strings you can use to map
  19289. * to modifier keys when you specify your keyboard shortcuts
  19290. *
  19291. * @type {Object}
  19292. */
  19293. _SPECIAL_ALIASES = {
  19294. 'option': 'alt',
  19295. 'command': 'meta',
  19296. 'return': 'enter',
  19297. 'escape': 'esc'
  19298. },
  19299. /**
  19300. * variable to store the flipped version of _MAP from above
  19301. * needed to check if we should use keypress or not when no action
  19302. * is specified
  19303. *
  19304. * @type {Object|undefined}
  19305. */
  19306. _REVERSE_MAP,
  19307. /**
  19308. * a list of all the callbacks setup via Mousetrap.bind()
  19309. *
  19310. * @type {Object}
  19311. */
  19312. _callbacks = {},
  19313. /**
  19314. * direct map of string combinations to callbacks used for trigger()
  19315. *
  19316. * @type {Object}
  19317. */
  19318. _direct_map = {},
  19319. /**
  19320. * keeps track of what level each sequence is at since multiple
  19321. * sequences can start out with the same sequence
  19322. *
  19323. * @type {Object}
  19324. */
  19325. _sequence_levels = {},
  19326. /**
  19327. * variable to store the setTimeout call
  19328. *
  19329. * @type {null|number}
  19330. */
  19331. _reset_timer,
  19332. /**
  19333. * temporary state where we will ignore the next keyup
  19334. *
  19335. * @type {boolean|string}
  19336. */
  19337. _ignore_next_keyup = false,
  19338. /**
  19339. * are we currently inside of a sequence?
  19340. * type of action ("keyup" or "keydown" or "keypress") or false
  19341. *
  19342. * @type {boolean|string}
  19343. */
  19344. _inside_sequence = false;
  19345. /**
  19346. * loop through the f keys, f1 to f19 and add them to the map
  19347. * programatically
  19348. */
  19349. for (var i = 1; i < 20; ++i) {
  19350. _MAP[111 + i] = 'f' + i;
  19351. }
  19352. /**
  19353. * loop through to map numbers on the numeric keypad
  19354. */
  19355. for (i = 0; i <= 9; ++i) {
  19356. _MAP[i + 96] = i;
  19357. }
  19358. /**
  19359. * cross browser add event method
  19360. *
  19361. * @param {Element|HTMLDocument} object
  19362. * @param {string} type
  19363. * @param {Function} callback
  19364. * @returns void
  19365. */
  19366. function _addEvent(object, type, callback) {
  19367. if (object.addEventListener) {
  19368. return object.addEventListener(type, callback, false);
  19369. }
  19370. object.attachEvent('on' + type, callback);
  19371. }
  19372. /**
  19373. * takes the event and returns the key character
  19374. *
  19375. * @param {Event} e
  19376. * @return {string}
  19377. */
  19378. function _characterFromEvent(e) {
  19379. // for keypress events we should return the character as is
  19380. if (e.type == 'keypress') {
  19381. return String.fromCharCode(e.which);
  19382. }
  19383. // for non keypress events the special maps are needed
  19384. if (_MAP[e.which]) {
  19385. return _MAP[e.which];
  19386. }
  19387. if (_KEYCODE_MAP[e.which]) {
  19388. return _KEYCODE_MAP[e.which];
  19389. }
  19390. // if it is not in the special map
  19391. return String.fromCharCode(e.which).toLowerCase();
  19392. }
  19393. /**
  19394. * should we stop this event before firing off callbacks
  19395. *
  19396. * @param {Event} e
  19397. * @return {boolean}
  19398. */
  19399. function _stop(e) {
  19400. var element = e.target || e.srcElement,
  19401. tag_name = element.tagName;
  19402. // if the element has the class "mousetrap" then no need to stop
  19403. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19404. return false;
  19405. }
  19406. // stop for input, select, and textarea
  19407. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19408. }
  19409. /**
  19410. * checks if two arrays are equal
  19411. *
  19412. * @param {Array} modifiers1
  19413. * @param {Array} modifiers2
  19414. * @returns {boolean}
  19415. */
  19416. function _modifiersMatch(modifiers1, modifiers2) {
  19417. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19418. }
  19419. /**
  19420. * resets all sequence counters except for the ones passed in
  19421. *
  19422. * @param {Object} do_not_reset
  19423. * @returns void
  19424. */
  19425. function _resetSequences(do_not_reset) {
  19426. do_not_reset = do_not_reset || {};
  19427. var active_sequences = false,
  19428. key;
  19429. for (key in _sequence_levels) {
  19430. if (do_not_reset[key]) {
  19431. active_sequences = true;
  19432. continue;
  19433. }
  19434. _sequence_levels[key] = 0;
  19435. }
  19436. if (!active_sequences) {
  19437. _inside_sequence = false;
  19438. }
  19439. }
  19440. /**
  19441. * finds all callbacks that match based on the keycode, modifiers,
  19442. * and action
  19443. *
  19444. * @param {string} character
  19445. * @param {Array} modifiers
  19446. * @param {string} action
  19447. * @param {boolean=} remove - should we remove any matches
  19448. * @param {string=} combination
  19449. * @returns {Array}
  19450. */
  19451. function _getMatches(character, modifiers, action, remove, combination) {
  19452. var i,
  19453. callback,
  19454. matches = [];
  19455. // if there are no events related to this keycode
  19456. if (!_callbacks[character]) {
  19457. return [];
  19458. }
  19459. // if a modifier key is coming up on its own we should allow it
  19460. if (action == 'keyup' && _isModifier(character)) {
  19461. modifiers = [character];
  19462. }
  19463. // loop through all callbacks for the key that was pressed
  19464. // and see if any of them match
  19465. for (i = 0; i < _callbacks[character].length; ++i) {
  19466. callback = _callbacks[character][i];
  19467. // if this is a sequence but it is not at the right level
  19468. // then move onto the next match
  19469. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19470. continue;
  19471. }
  19472. // if the action we are looking for doesn't match the action we got
  19473. // then we should keep going
  19474. if (action != callback.action) {
  19475. continue;
  19476. }
  19477. // if this is a keypress event that means that we need to only
  19478. // look at the character, otherwise check the modifiers as
  19479. // well
  19480. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19481. // remove is used so if you change your mind and call bind a
  19482. // second time with a new function the first one is overwritten
  19483. if (remove && callback.combo == combination) {
  19484. _callbacks[character].splice(i, 1);
  19485. }
  19486. matches.push(callback);
  19487. }
  19488. }
  19489. return matches;
  19490. }
  19491. /**
  19492. * takes a key event and figures out what the modifiers are
  19493. *
  19494. * @param {Event} e
  19495. * @returns {Array}
  19496. */
  19497. function _eventModifiers(e) {
  19498. var modifiers = [];
  19499. if (e.shiftKey) {
  19500. modifiers.push('shift');
  19501. }
  19502. if (e.altKey) {
  19503. modifiers.push('alt');
  19504. }
  19505. if (e.ctrlKey) {
  19506. modifiers.push('ctrl');
  19507. }
  19508. if (e.metaKey) {
  19509. modifiers.push('meta');
  19510. }
  19511. return modifiers;
  19512. }
  19513. /**
  19514. * actually calls the callback function
  19515. *
  19516. * if your callback function returns false this will use the jquery
  19517. * convention - prevent default and stop propogation on the event
  19518. *
  19519. * @param {Function} callback
  19520. * @param {Event} e
  19521. * @returns void
  19522. */
  19523. function _fireCallback(callback, e) {
  19524. if (callback(e) === false) {
  19525. if (e.preventDefault) {
  19526. e.preventDefault();
  19527. }
  19528. if (e.stopPropagation) {
  19529. e.stopPropagation();
  19530. }
  19531. e.returnValue = false;
  19532. e.cancelBubble = true;
  19533. }
  19534. }
  19535. /**
  19536. * handles a character key event
  19537. *
  19538. * @param {string} character
  19539. * @param {Event} e
  19540. * @returns void
  19541. */
  19542. function _handleCharacter(character, e) {
  19543. // if this event should not happen stop here
  19544. if (_stop(e)) {
  19545. return;
  19546. }
  19547. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19548. i,
  19549. do_not_reset = {},
  19550. processed_sequence_callback = false;
  19551. // loop through matching callbacks for this key event
  19552. for (i = 0; i < callbacks.length; ++i) {
  19553. // fire for all sequence callbacks
  19554. // this is because if for example you have multiple sequences
  19555. // bound such as "g i" and "g t" they both need to fire the
  19556. // callback for matching g cause otherwise you can only ever
  19557. // match the first one
  19558. if (callbacks[i].seq) {
  19559. processed_sequence_callback = true;
  19560. // keep a list of which sequences were matches for later
  19561. do_not_reset[callbacks[i].seq] = 1;
  19562. _fireCallback(callbacks[i].callback, e);
  19563. continue;
  19564. }
  19565. // if there were no sequence matches but we are still here
  19566. // that means this is a regular match so we should fire that
  19567. if (!processed_sequence_callback && !_inside_sequence) {
  19568. _fireCallback(callbacks[i].callback, e);
  19569. }
  19570. }
  19571. // if you are inside of a sequence and the key you are pressing
  19572. // is not a modifier key then we should reset all sequences
  19573. // that were not matched by this key event
  19574. if (e.type == _inside_sequence && !_isModifier(character)) {
  19575. _resetSequences(do_not_reset);
  19576. }
  19577. }
  19578. /**
  19579. * handles a keydown event
  19580. *
  19581. * @param {Event} e
  19582. * @returns void
  19583. */
  19584. function _handleKey(e) {
  19585. // normalize e.which for key events
  19586. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19587. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19588. var character = _characterFromEvent(e);
  19589. // no character found then stop
  19590. if (!character) {
  19591. return;
  19592. }
  19593. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19594. _ignore_next_keyup = false;
  19595. return;
  19596. }
  19597. _handleCharacter(character, e);
  19598. }
  19599. /**
  19600. * determines if the keycode specified is a modifier key or not
  19601. *
  19602. * @param {string} key
  19603. * @returns {boolean}
  19604. */
  19605. function _isModifier(key) {
  19606. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19607. }
  19608. /**
  19609. * called to set a 1 second timeout on the specified sequence
  19610. *
  19611. * this is so after each key press in the sequence you have 1 second
  19612. * to press the next key before you have to start over
  19613. *
  19614. * @returns void
  19615. */
  19616. function _resetSequenceTimer() {
  19617. clearTimeout(_reset_timer);
  19618. _reset_timer = setTimeout(_resetSequences, 1000);
  19619. }
  19620. /**
  19621. * reverses the map lookup so that we can look for specific keys
  19622. * to see what can and can't use keypress
  19623. *
  19624. * @return {Object}
  19625. */
  19626. function _getReverseMap() {
  19627. if (!_REVERSE_MAP) {
  19628. _REVERSE_MAP = {};
  19629. for (var key in _MAP) {
  19630. // pull out the numeric keypad from here cause keypress should
  19631. // be able to detect the keys from the character
  19632. if (key > 95 && key < 112) {
  19633. continue;
  19634. }
  19635. if (_MAP.hasOwnProperty(key)) {
  19636. _REVERSE_MAP[_MAP[key]] = key;
  19637. }
  19638. }
  19639. }
  19640. return _REVERSE_MAP;
  19641. }
  19642. /**
  19643. * picks the best action based on the key combination
  19644. *
  19645. * @param {string} key - character for key
  19646. * @param {Array} modifiers
  19647. * @param {string=} action passed in
  19648. */
  19649. function _pickBestAction(key, modifiers, action) {
  19650. // if no action was picked in we should try to pick the one
  19651. // that we think would work best for this key
  19652. if (!action) {
  19653. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19654. }
  19655. // modifier keys don't work as expected with keypress,
  19656. // switch to keydown
  19657. if (action == 'keypress' && modifiers.length) {
  19658. action = 'keydown';
  19659. }
  19660. return action;
  19661. }
  19662. /**
  19663. * binds a key sequence to an event
  19664. *
  19665. * @param {string} combo - combo specified in bind call
  19666. * @param {Array} keys
  19667. * @param {Function} callback
  19668. * @param {string=} action
  19669. * @returns void
  19670. */
  19671. function _bindSequence(combo, keys, callback, action) {
  19672. // start off by adding a sequence level record for this combination
  19673. // and setting the level to 0
  19674. _sequence_levels[combo] = 0;
  19675. // if there is no action pick the best one for the first key
  19676. // in the sequence
  19677. if (!action) {
  19678. action = _pickBestAction(keys[0], []);
  19679. }
  19680. /**
  19681. * callback to increase the sequence level for this sequence and reset
  19682. * all other sequences that were active
  19683. *
  19684. * @param {Event} e
  19685. * @returns void
  19686. */
  19687. var _increaseSequence = function(e) {
  19688. _inside_sequence = action;
  19689. ++_sequence_levels[combo];
  19690. _resetSequenceTimer();
  19691. },
  19692. /**
  19693. * wraps the specified callback inside of another function in order
  19694. * to reset all sequence counters as soon as this sequence is done
  19695. *
  19696. * @param {Event} e
  19697. * @returns void
  19698. */
  19699. _callbackAndReset = function(e) {
  19700. _fireCallback(callback, e);
  19701. // we should ignore the next key up if the action is key down
  19702. // or keypress. this is so if you finish a sequence and
  19703. // release the key the final key will not trigger a keyup
  19704. if (action !== 'keyup') {
  19705. _ignore_next_keyup = _characterFromEvent(e);
  19706. }
  19707. // weird race condition if a sequence ends with the key
  19708. // another sequence begins with
  19709. setTimeout(_resetSequences, 10);
  19710. },
  19711. i;
  19712. // loop through keys one at a time and bind the appropriate callback
  19713. // function. for any key leading up to the final one it should
  19714. // increase the sequence. after the final, it should reset all sequences
  19715. for (i = 0; i < keys.length; ++i) {
  19716. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19717. }
  19718. }
  19719. /**
  19720. * binds a single keyboard combination
  19721. *
  19722. * @param {string} combination
  19723. * @param {Function} callback
  19724. * @param {string=} action
  19725. * @param {string=} sequence_name - name of sequence if part of sequence
  19726. * @param {number=} level - what part of the sequence the command is
  19727. * @returns void
  19728. */
  19729. function _bindSingle(combination, callback, action, sequence_name, level) {
  19730. // make sure multiple spaces in a row become a single space
  19731. combination = combination.replace(/\s+/g, ' ');
  19732. var sequence = combination.split(' '),
  19733. i,
  19734. key,
  19735. keys,
  19736. modifiers = [];
  19737. // if this pattern is a sequence of keys then run through this method
  19738. // to reprocess each pattern one key at a time
  19739. if (sequence.length > 1) {
  19740. return _bindSequence(combination, sequence, callback, action);
  19741. }
  19742. // take the keys from this pattern and figure out what the actual
  19743. // pattern is all about
  19744. keys = combination === '+' ? ['+'] : combination.split('+');
  19745. for (i = 0; i < keys.length; ++i) {
  19746. key = keys[i];
  19747. // normalize key names
  19748. if (_SPECIAL_ALIASES[key]) {
  19749. key = _SPECIAL_ALIASES[key];
  19750. }
  19751. // if this is not a keypress event then we should
  19752. // be smart about using shift keys
  19753. // this will only work for US keyboards however
  19754. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19755. key = _SHIFT_MAP[key];
  19756. modifiers.push('shift');
  19757. }
  19758. // if this key is a modifier then add it to the list of modifiers
  19759. if (_isModifier(key)) {
  19760. modifiers.push(key);
  19761. }
  19762. }
  19763. // depending on what the key combination is
  19764. // we will try to pick the best event for it
  19765. action = _pickBestAction(key, modifiers, action);
  19766. // make sure to initialize array if this is the first time
  19767. // a callback is added for this key
  19768. if (!_callbacks[key]) {
  19769. _callbacks[key] = [];
  19770. }
  19771. // remove an existing match if there is one
  19772. _getMatches(key, modifiers, action, !sequence_name, combination);
  19773. // add this call back to the array
  19774. // if it is a sequence put it at the beginning
  19775. // if not put it at the end
  19776. //
  19777. // this is important because the way these are processed expects
  19778. // the sequence ones to come first
  19779. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19780. callback: callback,
  19781. modifiers: modifiers,
  19782. action: action,
  19783. seq: sequence_name,
  19784. level: level,
  19785. combo: combination
  19786. });
  19787. }
  19788. /**
  19789. * binds multiple combinations to the same callback
  19790. *
  19791. * @param {Array} combinations
  19792. * @param {Function} callback
  19793. * @param {string|undefined} action
  19794. * @returns void
  19795. */
  19796. function _bindMultiple(combinations, callback, action) {
  19797. for (var i = 0; i < combinations.length; ++i) {
  19798. _bindSingle(combinations[i], callback, action);
  19799. }
  19800. }
  19801. // start!
  19802. _addEvent(document, 'keypress', _handleKey);
  19803. _addEvent(document, 'keydown', _handleKey);
  19804. _addEvent(document, 'keyup', _handleKey);
  19805. var mousetrap = {
  19806. /**
  19807. * binds an event to mousetrap
  19808. *
  19809. * can be a single key, a combination of keys separated with +,
  19810. * a comma separated list of keys, an array of keys, or
  19811. * a sequence of keys separated by spaces
  19812. *
  19813. * be sure to list the modifier keys first to make sure that the
  19814. * correct key ends up getting bound (the last key in the pattern)
  19815. *
  19816. * @param {string|Array} keys
  19817. * @param {Function} callback
  19818. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19819. * @returns void
  19820. */
  19821. bind: function(keys, callback, action) {
  19822. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19823. _direct_map[keys + ':' + action] = callback;
  19824. return this;
  19825. },
  19826. /**
  19827. * unbinds an event to mousetrap
  19828. *
  19829. * the unbinding sets the callback function of the specified key combo
  19830. * to an empty function and deletes the corresponding key in the
  19831. * _direct_map dict.
  19832. *
  19833. * the keycombo+action has to be exactly the same as
  19834. * it was defined in the bind method
  19835. *
  19836. * TODO: actually remove this from the _callbacks dictionary instead
  19837. * of binding an empty function
  19838. *
  19839. * @param {string|Array} keys
  19840. * @param {string} action
  19841. * @returns void
  19842. */
  19843. unbind: function(keys, action) {
  19844. if (_direct_map[keys + ':' + action]) {
  19845. delete _direct_map[keys + ':' + action];
  19846. this.bind(keys, function() {}, action);
  19847. }
  19848. return this;
  19849. },
  19850. /**
  19851. * triggers an event that has already been bound
  19852. *
  19853. * @param {string} keys
  19854. * @param {string=} action
  19855. * @returns void
  19856. */
  19857. trigger: function(keys, action) {
  19858. _direct_map[keys + ':' + action]();
  19859. return this;
  19860. },
  19861. /**
  19862. * resets the library back to its initial state. this is useful
  19863. * if you want to clear out the current keyboard shortcuts and bind
  19864. * new ones - for example if you switch to another page
  19865. *
  19866. * @returns void
  19867. */
  19868. reset: function() {
  19869. _callbacks = {};
  19870. _direct_map = {};
  19871. return this;
  19872. }
  19873. };
  19874. module.exports = mousetrap;
  19875. },{}]},{},[1])
  19876. (1)
  19877. });